@wildshard/engine 0.1.19 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +4 -0
  3. package/package.json +4 -2
  4. package/scripts/app-build/gen.ts +11 -0
  5. package/scripts/cell-mem-bench.mjs +2 -0
  6. package/scripts/check-devserver.mjs +1 -1
  7. package/scripts/grid-crossing-tour.mjs +11 -4
  8. package/scripts/grid-crossing-walk-proof.mjs +4 -2
  9. package/scripts/land.mjs +2 -1
  10. package/scripts/loading-flow/benchmax.mjs +34 -11
  11. package/scripts/loading-flow/deskbench.mjs +276 -0
  12. package/scripts/loading-flow/stalls.d.mts +17 -3
  13. package/scripts/loading-flow/stalls.mjs +82 -3
  14. package/scripts/nightly-model.ts +9 -6
  15. package/scripts/offline-proof.mjs +7 -1
  16. package/scripts/parity/boot-smoke.mjs +13 -2
  17. package/scripts/pin-format.ts +5 -2
  18. package/scripts/pins-reuse.d.mts +1 -0
  19. package/scripts/pins-reuse.mjs +22 -0
  20. package/scripts/scratch-dir.mjs +95 -0
  21. package/scripts/scratch-sweep.mjs +182 -0
  22. package/scripts/tsconfig.json +2 -12
  23. package/scripts/vps/harden-prometheus.sh +3 -0
  24. package/scripts/worktree-reap.mjs +54 -8
  25. package/scripts/worktree.mjs +19 -5
  26. package/src/client/engine/anim/rigParser.ts +2 -2
  27. package/src/client/engine/core/Game.ts +63 -19
  28. package/src/client/engine/core/gpuOnly.ts +10 -0
  29. package/src/client/engine/core/renderBudget.ts +134 -0
  30. package/src/client/engine/net/redial.ts +40 -5
  31. package/src/client/engine/render/dataLook.ts +70 -7
  32. package/src/client/engine/render/families/pbr.ts +2 -0
  33. package/src/client/engine/render/families/registry.ts +11 -2
  34. package/src/client/engine/render/families/sceneSurface.ts +116 -0
  35. package/src/client/engine/render/look.ts +7 -1
  36. package/src/client/engine/render/precompile.ts +4 -2
  37. package/src/client/engine/render/tiers.ts +4 -1
  38. package/src/client/engine/world/declaredProps.ts +5 -1
  39. package/src/client/engine/world/skyRig.ts +4 -1
  40. package/src/client/engine/world/terrainTileView.ts +64 -23
  41. package/src/client/game/devScene/hook.ts +149 -12
  42. package/src/client/game/devScene/liveLook.ts +21 -0
  43. package/src/client/game/grid/live.ts +45 -8
  44. package/src/client/game/grid/liveSession.ts +23 -4
  45. package/src/client/game/grid/pageEntry.ts +12 -1
  46. package/src/client/game/grid/productInputs.ts +22 -11
  47. package/src/client/game/grid/session.ts +13 -4
  48. package/src/client/game/session/finish.ts +4 -1
  49. package/src/client/game/shardfile/client.ts +24 -7
  50. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  51. package/src/client/game/shardfile/clientViews.ts +36 -8
  52. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  53. package/src/client/game/shardfile/groundMerge.ts +57 -5
  54. package/src/client/game/shardfile/hybrid.ts +2 -0
  55. package/src/client/game/shardfile/look.ts +1 -1
  56. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  57. package/src/client/game/shardfile/tileContent.ts +1 -1
  58. package/src/client/game/shardfile/tileDriver.ts +38 -11
  59. package/src/client/game/shardfile/wirePage.ts +7 -3
  60. package/src/client/game/shardfile/worldScenes.ts +17 -10
  61. package/src/client/host/online/doctor.ts +20 -7
  62. package/src/client/host/online/doctorView.ts +2 -0
  63. package/src/client/host/online/linkScreens.ts +83 -5
  64. package/src/client/host/online/shell.ts +13 -4
  65. package/src/client/host/standalone/shell.ts +37 -1
  66. package/src/server/game/quest/eliteDrops.ts +7 -3
  67. package/src/server/game/riding/nativeTaming.ts +13 -2
  68. package/src/server/host/dedicated/cellHost.ts +14 -2
  69. package/src/server/host/dedicated/cellProtocol.ts +2 -0
  70. package/src/server/host/dedicated/dedicatedRoom.ts +24 -7
  71. package/src/server/host/dedicated/serverMetrics.ts +9 -0
  72. package/src/server/host/dedicated/workerTable.ts +31 -24
  73. package/src/server/host/standalone/serverHost.ts +56 -10
  74. package/src/server/host/standalone/serverProduct.ts +9 -7
  75. package/src/server/host/standalone/serverRuntime.ts +1 -1
  76. package/src/shared/engine/core/framePacing.ts +12 -1
  77. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  78. package/src/shared/game/devColliders.ts +60 -0
  79. package/src/shared/game/devGameplay.ts +41 -0
@@ -53,6 +53,7 @@ import { yieldTask } from '../../../shared/engine/core/workSlice';
53
53
  import { buildHeld, heldDrawDeferred, noteFrameDrawn } from '../../../shared/engine/core/framePacing';
54
54
  import { isDev, onDev } from './devMode';
55
55
  import { activeDevPixels, drawingPixelRatio } from './devPixels';
56
+ import { RenderBudget, budgetCeiling } from './renderBudget';
56
57
  import { graphicsMode, lowPowerOn, noteFastFrames, PIXELS_EVENT } from './graphicsMode';
57
58
  import { flagOn, frameCapFor, noteShipped, presetLabel, setFrameReadout, type ShippedLook } from './graphicsQuality';
58
59
  import { classifyFrames } from '../boot/lowPower';
@@ -179,6 +180,11 @@ const ARRIVAL_RADIUS = 125;
179
180
  /** one engine colour chain, built (Game.buildComposer): its effects, in order, and by name */
180
181
  interface BuiltChain { clean: boolean; order: Effect[]; fx: Omit<EngineEffects, 'order'> }
181
182
 
183
+ /** GC6: candidates a live display transform gets before it links on its next draw */
184
+ export const POST_PASS_ATTEMPTS = 4;
185
+ /** GC6: the longest an entered frame waits on live display transform preparation */
186
+ export const POST_PREPARATION_WAIT_MS = 12_000;
187
+
182
188
  /** An entered frame's preparation trace (`Game.entryPreparation`): its destination root, owner, running phase, measured
183
189
  * work counts and scalar timings. A named type, so consumers of the emitted declarations see it (a private field's type
184
190
  * is not emitted). */
@@ -526,10 +532,10 @@ export class Game {
526
532
  if (tracedBoot) recordGpuCheckpoint(this.renderer, 'renderer:created');
527
533
  // QA row 25 / MG2: a Developer's screen × density pick (core/devPixels.ts), else a phone's Low graphics
528
534
  // (core/graphicsMode.ts), stands in for the tier's cap; either applies live
529
- this.renderer.setPixelRatio(drawingPixelRatio(window.devicePixelRatio, TIER_CONFIG.dpr, this.phoneGraphics));
535
+ this.renderer.setPixelRatio(this.wantedRatio());
530
536
  // the new ratio waits for the frame that draws (RT3: never in the task that decided it, whose cleared canvas nothing
531
537
  // would replace; under a menu or the title the world stays as it was until play draws again)
532
- const repixel = (): void => { const ratio = drawingPixelRatio(window.devicePixelRatio, TIER_CONFIG.dpr, this.phoneGraphics); this.pickedRatio = ratio === this.renderer.getPixelRatio() ? null : ratio; this.applyQuality(); };
538
+ const repixel = (): void => { const ratio = this.wantedRatio(); this.pickedRatio = ratio === this.renderer.getPixelRatio() ? null : ratio; this.applyQuality(); };
533
539
  this.engineScope.listen(document, PIXELS_EVENT, repixel);
534
540
  // MG8 prototype: the player has control, so the boot's shadow draws are done: a no-shadows mode clears the maps once more
535
541
  this.engineScope.listen(document, 'ws:control-ready', () => { this.qualityClearedMaps = new WeakSet(); });
@@ -551,6 +557,7 @@ export class Game {
551
557
  // change tells the page (Settings, the first-play card) and lands in the next drawn frame
552
558
  this.engineScope.listen(document, 'visibilitychange', () => {
553
559
  if (document.visibilityState !== 'visible') return;
560
+ this.budget?.reset(); // NB5: the frames from before the page went away are not this page's pace
554
561
  const stamps: number[] = [];
555
562
  const tick = (now: number): void => {
556
563
  if (this.engineScope.disposed || document.visibilityState !== 'visible') return;
@@ -1096,18 +1103,24 @@ export class Game {
1096
1103
  const geometry = postTriangle(), mesh = new THREE.Mesh(geometry, pass.fullscreenMaterial), scene = new THREE.Scene();
1097
1104
  const target = pass.renderToScreen ? null : composer.inputBuffer;
1098
1105
  try {
1099
- let published = false;
1100
- while (current() && !published) published = await prepareEffectPass(pass, async material => {
1101
- mesh.material = material;
1102
- await runPrecompile(this.renderer, this.camera, [{ label: engineString('s_178612197e2b'), root: mesh, target: scene, rt: target }], 1,
1103
- undefined, undefined, current, false, () => waitForDrawnFrame(this.engineScope, () => this.frameCount, current));
1104
- }, material => {
1105
- mesh.material = material;
1106
- const prior = this.renderer.getRenderTarget(), face = this.renderer.getActiveCubeFace(), mip = this.renderer.getActiveMipmapLevel();
1107
- this.renderer.setRenderTarget(target);
1108
- try { this.renderer.compile(mesh, this.camera, scene); }
1109
- finally { this.renderer.setRenderTarget(prior, face, mip); }
1110
- }, current);
1106
+ // GC6 (QA 11-14 row 6): a pass that left the chain, or whose shader keeps changing under each candidate, never
1107
+ // published: the loop ran for ever and every entered frame awaiting it stayed unready. Past a few candidates it
1108
+ // links on its next draw (the boot path).
1109
+ let published = false, attempts = 0;
1110
+ while (current() && composer.passes.includes(pass) && !published) {
1111
+ if (attempts++ >= POST_PASS_ATTEMPTS) { pass.recompile(); break; }
1112
+ published = await prepareEffectPass(pass, async material => {
1113
+ mesh.material = material;
1114
+ await runPrecompile(this.renderer, this.camera, [{ label: engineString('s_178612197e2b'), root: mesh, target: scene, rt: target }], 1,
1115
+ undefined, undefined, current, false, () => waitForDrawnFrame(this.engineScope, () => this.frameCount, current));
1116
+ }, material => {
1117
+ mesh.material = material;
1118
+ const prior = this.renderer.getRenderTarget(), face = this.renderer.getActiveCubeFace(), mip = this.renderer.getActiveMipmapLevel();
1119
+ this.renderer.setRenderTarget(target);
1120
+ try { this.renderer.compile(mesh, this.camera, scene); }
1121
+ finally { this.renderer.setRenderTarget(prior, face, mip); }
1122
+ }, current);
1123
+ }
1111
1124
  } finally { geometry.dispose(); }
1112
1125
  };
1113
1126
  const work = prepare();
@@ -1169,10 +1182,18 @@ export class Game {
1169
1182
  // and first draws. An early composer lends only the compiler above; doing
1170
1183
  // the crossing warm-up here would add parked/offscreen frame variants.
1171
1184
  if (this.frameCount === 0) { trace.completed = true; return; }
1185
+ // GC6 (QA 11-14 row 6): a display transform's preparation that never settles (a lost link, a dead owner's frame
1186
+ // wait) held Nalati's on-road entry at afterPlay for ever: in the cell, no control. Past POST_PREPARATION_WAIT_MS
1187
+ // the entry goes on and that pass links on its first draw (D196: a stall reveals with what had linked).
1188
+ const postStarted = diagnosticNow();
1172
1189
  for (;;) {
1173
- const pending = this.postPreparation;
1174
- await pending;
1190
+ const pending = this.postPreparation, left = POST_PREPARATION_WAIT_MS - (diagnosticNow() - postStarted);
1191
+ let timer: ReturnType<Scope['timeout']> | undefined;
1192
+ const timedOut = left <= 0 || await Promise.race([pending.then(() => false),
1193
+ new Promise<boolean>(resolve => { timer = this.engineScope.timeout(left, () => { resolve(true); }); })])
1194
+ .finally(() => { if (timer !== undefined) this.engineScope.cancelTimer(timer); });
1175
1195
  if (!current()) throw new Error('Shader warm-up owner left');
1196
+ if (timedOut) { trace.stalled = 'post-preparation'; console.warn(`[entry] ${owner.name}: display transform preparation still running after ${String(POST_PREPARATION_WAIT_MS)} ms; entering without it`); break; }
1176
1197
  if (this.postPreparation === pending) break;
1177
1198
  }
1178
1199
  enter('shaders-and-composer');
@@ -1687,8 +1708,26 @@ export class Game {
1687
1708
  // MG8: Settings ▸ Graphics ▸ Pixel density replaces the boot-time render scale on a phone (Jake ~23:45: one pixel control)
1688
1709
  private readonly phoneGraphics: boolean = TIER === 'phone';
1689
1710
  resize(): void { this.fitSize(); this.kickLoop(); }
1711
+ /** NB5 (renderBudget.ts): the desktop's pixel budget and dynamic resolution, on the tier's own scale only: never a phone
1712
+ * (MG8's Pixel density; Jake 2026-10-20, no dynamic resolution on the phone), a Developer's pixel pick or a player's saved
1713
+ * render scale (Settings ▸ Graphics, gfxPrefs.dpr) */
1714
+ private budget: RenderBudget | null = null;
1715
+ private budgetOn(): boolean { return !this.phoneGraphics && activeDevPixels() === null && gfxPrefs.dpr === 'auto' && this.slowPacing === null; }
1716
+ /** NB5: the next drawn frame follows vsyncs skipped on purpose (a build hold): its interval is not the frame's cost */
1717
+ private budgetSkip = false;
1718
+ /** The drawing buffer's pixel ratio the page wants now: the budget's on the desktop's own scale, else drawingPixelRatio. */
1719
+ private wantedRatio(): number {
1720
+ const base = drawingPixelRatio(window.devicePixelRatio, TIER_CONFIG.dpr, this.phoneGraphics);
1721
+ if (!this.budgetOn()) { this.budget = null; return base; }
1722
+ const ceiling = budgetCeiling(window.innerWidth, viewportHeight(), window.devicePixelRatio, base);
1723
+ if (this.budget === null) this.budget = new RenderBudget(ceiling);
1724
+ else if (this.budget.ceiling !== ceiling) this.budget.resize(ceiling);
1725
+ return this.budget.ratio;
1726
+ }
1690
1727
  private fitSize(): void {
1691
1728
  const w = window.innerWidth, h = viewportHeight();
1729
+ // a new window size moves the budget's ceiling (a smaller ratio lands now: this resize redraws anyway)
1730
+ if (this.budget !== null) { const ratio = this.wantedRatio(); if (ratio !== this.renderer.getPixelRatio()) this.renderer.setPixelRatio(ratio); }
1692
1731
  this.camera.aspect = w / h;
1693
1732
  this.camera.updateProjectionMatrix();
1694
1733
  this.renderer.setSize(w, h);
@@ -1725,13 +1764,14 @@ export class Game {
1725
1764
  // worker messages and input; like a capped vsync, a skipped one does nothing. A capture draws at the tier's own
1726
1765
  // scale on its own clock: no spacing, and any lowered scale restored
1727
1766
  const capture = this.app.clock.mode === 'capture';
1728
- if (capture) this.slowPacing?.restore();
1767
+ if (capture) { this.slowPacing?.restore(); this.budget?.restore(); }
1729
1768
  const pacing = capture ? null : this.slowPacing;
1730
1769
  if (pacedSkip(pacing, lastRun, this.pacedStart, forceFrame, buildHeld())) return;
1731
1770
  // G782: held at a cell's wall with build slices running, skip vsyncs up to the 30 fps held floor (framePacing.ts);
1732
1771
  // like a capped vsync, a skipped one does nothing, so the drawn frame's dt is the whole interval
1733
- if (!forceFrame && heldDrawDeferred()) return;
1772
+ if (!forceFrame && heldDrawDeferred()) { this.budgetSkip = true; return; }
1734
1773
  const cap = frameCapFps();
1774
+ if (cap > 0) this.budget?.restore(); // NB5: a cap sets its own pace; the tier's own scale under it
1735
1775
  if (cap > 0 && !forceFrame) {
1736
1776
  const anchor = frameCapAnchor(lastDrawn, now ?? lastRun, cap);
1737
1777
  if (anchor === null) return;
@@ -1771,7 +1811,8 @@ export class Game {
1771
1811
  // QA row 25: a Developer pixel pick (core/devPixels.ts) holds against the software pacing's scale while it is set
1772
1812
  const paced = this.stepOnly ? null : this.slowPacing?.takeRatio() ?? null, picked = this.stepOnly ? null : this.pickedRatio;
1773
1813
  if (picked !== null) this.pickedRatio = null;
1774
- const ratio = picked ?? (paced !== null && activeDevPixels() === null ? paced : null);
1814
+ const budgeted = this.stepOnly || picked !== null || paced !== null ? null : this.budget?.takeRatio() ?? null;
1815
+ const ratio = picked ?? (paced !== null && activeDevPixels() === null ? paced : null) ?? (this.budgetOn() ? budgeted : null);
1775
1816
  if (ratio !== null) { this.renderer.setPixelRatio(ratio); this.fitSize(); }
1776
1817
  sky.update(realDt);
1777
1818
  // planet + sun disc travel with the camera so they stay "infinitely" far
@@ -1806,6 +1847,9 @@ export class Game {
1806
1847
  noteFrameDrawn(done, now, cap, cap > 0 && Number.isFinite(lastDrawn) ? lastDrawn : undefined); // Builds share the cap recovery deadline; actual rAF still measures display cadence.
1807
1848
  this.app.cpu.end();
1808
1849
  if (pacing !== null) this.measurePacedFrame(lastRun);
1850
+ // NB5: dynamic resolution reads the drawn frame's interval (uncapped play only: a cap or a capture sets its own pace)
1851
+ else if (this.budget !== null && !capture && cap === 0 && !forceFrame && !this.app.clock.paused && !this.budgetSkip) this.budget.measured(liveDt * 1000);
1852
+ this.budgetSkip = false;
1809
1853
  this.workMs[this.frameI] = work;
1810
1854
  this.frameRafTime = now ?? null;
1811
1855
  this.frameCount++;
@@ -48,6 +48,16 @@ function releaseCpuCopy(this: BufferAttribute): void {
48
48
  this.array = this.array.slice(0, 0);
49
49
  Object.defineProperty(this, 'needsUpdate', { configurable: true, get: () => false, set: (value: boolean) => { if (value) lateWrite(this); } });
50
50
  }
51
+ /**
52
+ * SHARD-SOURCE AP18 (dev only: `wildshard watch`'s ground swap): upload a whole new copy of a GPU-only attribute into its
53
+ * buffer. The array is the same length as the first upload's, so the buffer is rewritten in place (no second buffer); its
54
+ * CPU copy goes again once uploaded.
55
+ */
56
+ export function refillGpuOnly(attribute: BufferAttribute, array: Float32Array): void {
57
+ if (array.length !== attribute.count * attribute.itemSize) throw new Error(`gpu-only: a refill of ${array.length} values for ${attribute.count * attribute.itemSize}`);
58
+ Reflect.deleteProperty(attribute, 'needsUpdate');
59
+ attribute.array = array; attribute.needsUpdate = true;
60
+ }
51
61
  function lateWrite(attribute: BufferAttribute): void {
52
62
  const where = releasedAs.get(attribute) ?? 'gpu-only';
53
63
  if (lateWriters.has(where)) return;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * NINE-DRAGON-BENCHMAX NB5, widened (meta QA-FEEDBACK-2026-11-14 rows 2, 3 and 5; Jake, desktop Chrome on his Mac:
3
+ * "nine dragon is fucked on desktop", "nalati is shist too 30 fps", "driftwood all over the place 40-70 FPS"). The J343 bar
4
+ * is 60 fps on desktop. The desktop's drawing buffer, in two parts:
5
+ *
6
+ * - a pixel budget: the buffer never holds more than DESKTOP_PIXEL_BUDGET pixels, whatever the window. The tier's 1.5 cap
7
+ * alone let a big window grow without end (a 2560x1440 window at 1.5 is 8.3 Mpx; Jake's 1496x717 at 1.5 is 2.4 Mpx, under
8
+ * the budget, so his ceiling stays 1.5);
9
+ * - dynamic resolution: the render scale steps down fast and back up slowly from the drawn frame's own interval, between
10
+ * a floor (one buffer pixel per CSS pixel where the ceiling allows it) and that ceiling. A frame that misses 60 fps
11
+ * tries one step down; if the next frames are no faster the frame is not bound by its pixels (the main thread, a busy
12
+ * machine), so the step is taken back and held off for a while: a softer frame that buys nothing is never kept.
13
+ *
14
+ * Desktop only, and only the tier's own scale: the phone keeps its one Pixel density control (MG8) and "Render scale stays
15
+ * 2x on the phone (no dynamic resolution)" (Jake, 2026-10-20). A Developer's pixel pick, a player's saved render scale, a
16
+ * capture, a frame cap or a software rasterizer's pacing each leave the scale alone. Pure: it is driven by measured
17
+ * intervals alone, so the tests drive it with numbers.
18
+ */
19
+
20
+ /** The desktop drawing buffer's most pixels (fable-phoneperf's cleanroom budget is 3.5 to 4.5 Mpx on a desktop). */
21
+ export const DESKTOP_PIXEL_BUDGET = 4_200_000;
22
+ /** A window's frames over this median interval (ms) miss 60 fps: step down. */
23
+ export const OVER_MS: number = 1000 / 58;
24
+ /** A window's frames under this median interval (ms) have headroom for a step up (~80 fps). */
25
+ export const UNDER_MS = 12.5;
26
+ /** Drawn frames per decision. */
27
+ export const BUDGET_WINDOW = 30;
28
+ /** Calm windows in a row before one step up. */
29
+ export const RAISE_WINDOWS = 6;
30
+ /** A step down must make the frame at least this much faster (share of its interval) to be kept. */
31
+ export const STEP_PAYS = 0.06;
32
+ /** After a step that did not pay, no step down for this many windows; each unpaid step in a row doubles it, to at most
33
+ * MAX_HOLD_WINDOWS (a frame bound by its main thread is not re-tried, and re-softened, every few seconds). */
34
+ export const UNPAID_HOLD_WINDOWS = 20;
35
+ export const MAX_HOLD_WINDOWS = 160;
36
+ /** Pixel ratios snap to eighths (each change reallocates the composer's targets). */
37
+ const SNAP = 8;
38
+
39
+ /** The buffer's pixel ratio ceiling for a window: the tier's cap, the screen's own density, and the pixel budget. */
40
+ export function budgetCeiling(cssWidth: number, cssHeight: number, device: number, tierCap: number, budget: number = DESKTOP_PIXEL_BUDGET): number {
41
+ const cap = Math.min(device, tierCap), css = Math.max(1, cssWidth * cssHeight);
42
+ const fits = Math.sqrt(budget / css);
43
+ // snapped as a whole, so the ceiling is always one of budgetSteps' own eighths (a 1.1 screen draws at 1, never 1.125)
44
+ return Math.max(1 / SNAP, Math.floor(Math.min(cap, fits) * SNAP) / SNAP);
45
+ }
46
+
47
+ /** The lowest ratio dynamic resolution takes: one buffer pixel per CSS pixel, or 3/4 of a ceiling already under that. */
48
+ export function budgetFloor(ceiling: number): number {
49
+ return ceiling > 1 ? 1 : Math.max(1 / SNAP, Math.floor(ceiling * 0.75 * SNAP) / SNAP);
50
+ }
51
+
52
+ /** The steps between floor and ceiling, ascending, an eighth apart (both ends included). */
53
+ export function budgetSteps(floor: number, ceiling: number): number[] {
54
+ const steps: number[] = [];
55
+ for (let r = ceiling; r > floor + 1e-9; r -= 1 / SNAP) steps.push(Math.round(r * SNAP) / SNAP);
56
+ steps.push(floor);
57
+ return [...new Set(steps)].sort((a, b) => a - b);
58
+ }
59
+
60
+ const median = (values: readonly number[]): number => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)] ?? 0;
61
+
62
+ /** One page's render budget. */
63
+ export class RenderBudget {
64
+ private steps: number[];
65
+ private at: number;
66
+ private readonly intervals: number[] = [];
67
+ private calm = 0;
68
+ private hold = 0;
69
+ private nextHold = UNPAID_HOLD_WINDOWS;
70
+ /** the step down on trial: the median it was taken against and the step it came from */
71
+ private trial: { before: number; from: number } | null = null;
72
+ private pending: number | null = null;
73
+
74
+ constructor(ceiling: number) { this.steps = budgetSteps(budgetFloor(ceiling), ceiling); this.at = this.steps.length - 1; }
75
+
76
+ /** The ratio frames draw at now. */
77
+ get ratio(): number { return this.steps[this.at] ?? 1; }
78
+ /** The ceiling (the window's budget). */
79
+ get ceiling(): number { return this.steps.at(-1) ?? 1; }
80
+
81
+ /** A new window size or screen: a new ceiling. Returns the ratio to draw at (the current one, or the new ceiling if lower). */
82
+ resize(ceiling: number): number {
83
+ const was = this.ratio;
84
+ this.steps = budgetSteps(budgetFloor(ceiling), ceiling);
85
+ const keep = this.steps.findIndex((r) => r >= was - 1e-9);
86
+ this.at = keep === -1 ? this.steps.length - 1 : keep;
87
+ this.reset();
88
+ return this.ratio;
89
+ }
90
+
91
+ /** Back to the ceiling (a capture draws at the tier's own scale), from the next drawn frame. */
92
+ restore(): void { this.reset(); this.move(this.steps.length - 1); }
93
+
94
+ /** Forget the measurements (a resize, a capture, a page coming back): the next window starts afresh. */
95
+ reset(): void { this.intervals.length = 0; this.calm = 0; this.trial = null; }
96
+
97
+ /** The ratio to set right before the next frame draws, once (RT3: a resize clears the canvas, so it lands in the frame that draws). */
98
+ takeRatio(): number | null { const next = this.pending; this.pending = null; return next; }
99
+
100
+ /** A drawn frame's interval (ms, from the last drawn frame). Returns the new ratio when it changes, else null. */
101
+ measured(intervalMs: number): number | null {
102
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) return null;
103
+ this.intervals.push(intervalMs);
104
+ if (this.intervals.length < BUDGET_WINDOW) return null;
105
+ const m = median(this.intervals);
106
+ this.intervals.length = 0;
107
+ if (this.hold > 0) this.hold--;
108
+ const trial = this.trial;
109
+ if (trial !== null) {
110
+ this.trial = null;
111
+ // the step down didn't pay: not bound by pixels at this view; take it back and hold off
112
+ if (m > trial.before * (1 - STEP_PAYS)) {
113
+ this.hold = this.nextHold; this.nextHold = Math.min(MAX_HOLD_WINDOWS, this.nextHold * 2); this.calm = 0;
114
+ return this.move(trial.from);
115
+ }
116
+ this.nextHold = UNPAID_HOLD_WINDOWS;
117
+ }
118
+ if (m > OVER_MS) {
119
+ this.calm = 0;
120
+ if (this.hold > 0 || this.at === 0) return null;
121
+ this.trial = { before: m, from: this.at };
122
+ return this.move(this.at - 1);
123
+ }
124
+ this.calm = m < UNDER_MS ? this.calm + 1 : 0;
125
+ if (this.calm >= RAISE_WINDOWS && this.at < this.steps.length - 1) { this.calm = 0; return this.move(this.at + 1); }
126
+ return null;
127
+ }
128
+
129
+ private move(to: number): number | null {
130
+ if (to === this.at) return null;
131
+ this.at = to; this.pending = this.ratio; this.intervals.length = 0;
132
+ return this.ratio;
133
+ }
134
+ }
@@ -11,7 +11,11 @@ export type LinkState = 'live' | 'reconnecting' | 'resuming' | 'lost' | 'full' |
11
11
  * page was out of view, `offline` is a device that says it has no network (FM4b mode 2). It rides `onState`'s reason for `reconnecting` and `resuming`. */
12
12
  export type LinkCause = 'silent' | 'closed' | 'restart' | 'hidden' | 'updating' | 'offline';
13
13
  /** Where the dial is, for a screen that shows it: dials so far, the wait to the next (null while one is out), and how long it's been down. */
14
- export interface LinkProgress { readonly dials: number; readonly nextDialMs: number | null; readonly downMs: number }
14
+ export interface LinkProgress { readonly dials: number; readonly nextDialMs: number | null; readonly downMs: number; readonly away?: LinkAway }
15
+ /** FM4b modes 4 and 45: the page was away for `ms` and came back to a quiet or closed link. `hidden` is time out of view the page
16
+ * measured (visibilitychange); `asleep` is a gap in the page's own clock ticks while it wasn't known hidden (a sleep, a frozen tab).
17
+ * It says nothing about the world's hold on the seat (J114): only what this page measured. */
18
+ export interface LinkAway { readonly ms: number; readonly how: 'hidden' | 'asleep' }
15
19
 
16
20
  /** No frame for this long: say so. The predictor's ring is full by then, so the player holds still. */
17
21
  const STRIP_MS = 1000;
@@ -24,6 +28,8 @@ const GIVE_UP_MS = 120_000;
24
28
  /** The waits between dials, then the last for ever, each ±20%. */
25
29
  const DIAL_WAITS_MS = [250, 500, 1000, 2000, 4000], DIAL_JITTER = 0.2;
26
30
  const WATCH_MS = 100;
31
+ /** FM4b modes 4 and 45: away this long (out of view, or no clock tick at all) and back to a quiet link is the Welcome back card. */
32
+ const AWAY_MS = 30_000;
27
33
  /** Words from a server that a redial would only hear again. */
28
34
  const FINAL = new Set(['reload', 'refused', 'replaced']);
29
35
  /** J178: the world is full, and a seat frees when someone leaves: this long between tries, for as long as the player waits. */
@@ -81,8 +87,12 @@ export class Redial {
81
87
  private cause: LinkCause = 'closed';
82
88
  /** When the device last said it went offline while the link was down; null while it has a network. */
83
89
  private offlineAt: number | null = null;
90
+ /** The watch's last tick: a gap after it is time the page did nothing at all (FM4b mode 45). */
91
+ private tickAt: number;
92
+ private awayFor: LinkAway | null = null;
84
93
  constructor(options: RedialOptions) {
85
94
  this.options = options; this.transport = options.transport; this.now = options.now ?? diagnosticNow; this.random = options.random ?? jitterFrom(this.now()); this.online = options.online ?? browserOnline;
95
+ this.tickAt = this.now();
86
96
  this.offFrame = options.client.onFrame(() => { this.heard(); });
87
97
  this.offClose = this.watchClose(options.transport);
88
98
  this.scope.interval(WATCH_MS, () => { this.watch(); });
@@ -96,11 +106,14 @@ export class Redial {
96
106
  /** The dial's progress now. */
97
107
  get progress(): LinkProgress {
98
108
  const now = this.now(), down = this.phase !== 'up';
99
- return { dials: this.dials, nextDialMs: this.phase === 'down' && this.dialled === null ? Math.max(0, this.dialAt - now) : null, downMs: down ? Math.max(0, now - this.lostAt) : 0 };
109
+ const away = this.awayFor === null ? {} : { away: this.awayFor };
110
+ return { dials: this.dials, nextDialMs: this.phase === 'down' && this.dialled === null ? Math.max(0, this.dialAt - now) : null, downMs: down ? Math.max(0, now - this.lostAt) : 0, ...away };
100
111
  }
101
- /** The page came back into view (an iPhone returning to Safari): a link that went quiet while hidden redials at once. */
102
- check(): void {
112
+ /** The page came back into view (an iPhone returning to Safari): a link that went quiet while hidden redials at once.
113
+ * `hiddenMs` is how long the page measured itself out of view (FM4b mode 4). */
114
+ check(hiddenMs = 0): void {
103
115
  const now = this.now();
116
+ this.woke(now, hiddenMs);
104
117
  if (this.phase === 'up' && this.heardAt !== null && now - this.heardAt >= STRIP_MS) { this.because('hidden'); this.lose(now); }
105
118
  // a link that went silent while the page was away was the page's absence: say welcome back
106
119
  if (this.phase === 'down') { if (this.cause === 'silent') this.because('hidden'); this.dialAt = now; }
@@ -118,11 +131,12 @@ export class Redial {
118
131
  private heard(): void {
119
132
  const now = this.now(), wasDown = this.phase === 'down';
120
133
  this.heardAt = now;
121
- if (wasDown) { this.phase = 'up'; this.dialled = null; this.dials = 0; this.waitingForSeat = false; this.offlineAt = null; }
134
+ if (wasDown) { this.phase = 'up'; this.dialled = null; this.dials = 0; this.waitingForSeat = false; this.offlineAt = null; this.awayFor = null; }
122
135
  this.show('live');
123
136
  }
124
137
  private watch(): void {
125
138
  const now = this.now();
139
+ this.woke(now, 0);
126
140
  if (this.phase === 'up') {
127
141
  if (this.heardAt === null) return;
128
142
  const silent = now - this.heardAt;
@@ -180,6 +194,27 @@ export class Redial {
180
194
  if (this.phase === 'up') { if (this.cause !== 'updating') this.because(reason === 'restart' ? 'restart' : this.online() ? 'closed' : 'offline'); this.lose(now, false); }
181
195
  else if (this.phase === 'down') { if (reason === 'restart') this.because('restart'); this.failedDial(now); }
182
196
  }
197
+ /**
198
+ * FM4b modes 4 and 45: the page was away (out of view for `hiddenMs`, or no clock tick for 30 s) and comes back to a link that is
199
+ * quiet or down. The time away is not dialling time: a link lost while away counts its give-up clock from the return, and one
200
+ * already down moves its clock on by the gap no dial could go out in, so a phone back after 4 minutes dials for 2 minutes more
201
+ * and never opens on Couldn't reconnect. A healthy return (frames heard within the last second) changes nothing.
202
+ */
203
+ private woke(now: number, hiddenMs: number): void {
204
+ const gap = now - this.tickAt;
205
+ this.tickAt = now;
206
+ if (gap < AWAY_MS && hiddenMs < AWAY_MS) return;
207
+ const how = hiddenMs >= AWAY_MS || this.awayFor?.how === 'hidden' ? 'hidden' : 'asleep', ms = Math.max(gap, hiddenMs, this.awayFor?.ms ?? 0);
208
+ if (this.phase === 'up') {
209
+ if (this.heardAt === null || now - this.heardAt < STRIP_MS) return;
210
+ this.awayFor = { ms, how }; this.because('hidden'); this.heardAt = now; this.lose(now);
211
+ } else if (this.phase === 'down' && !this.waitingForSeat) {
212
+ // the suspended gap moves the give-up clock on; hidden time with ticks running was dialled through, so it counts
213
+ if (gap >= AWAY_MS) { this.lostAt += gap; if (this.offlineAt !== null) this.offlineAt += gap; }
214
+ this.awayFor = { ms, how }; this.dialAt = now;
215
+ if (this.cause === 'silent' || this.cause === 'closed') this.because('hidden');
216
+ }
217
+ }
183
218
  /** The link is gone or no use: from now it is dialled, and a player's 35 s count from the last frame. */
184
219
  private lose(now: number, close = true): void {
185
220
  this.phase = 'down'; this.lostAt = this.heardAt ?? now; this.dialled = null; this.dialAt = now + (DIAL_WAITS_MS[0] ?? 0) * (1 + (this.random() * 2 - 1) * DIAL_JITTER);
@@ -12,13 +12,14 @@ import * as THREE from 'three';
12
12
  import type { PaintedNumbers } from '@wildshard/format/paintedLook';
13
13
  import { BlendFunction, Effect, LookupTexture, ToneMappingMode } from 'postprocessing';
14
14
  import { DEFAULT_NORMALIZED_DAY, normalizedDayClock, DayCycle } from '../../../shared/engine/world/dayCycle';
15
- import type { LookStrategy, SkyBackdropTargets, TerrainPainter } from './look';
15
+ import type { EngineEffects, LookStrategy, SkyBackdropTargets, TerrainPainter } from './look';
16
16
  import { LUT_SIZE, fetchLut } from './lut';
17
17
  import { PATCH_ORDER, patchShader, setInheritedPatch, type ShaderSource } from './shaderPatches';
18
18
  import { Scope } from '../../../shared/engine/app/scope';
19
19
  import { curveAt, type Curve } from '@wildshard/format/materials';
20
- import type { GraphIr } from '@wildshard/format/materialGraph';
20
+ import type { GraphBudget, GraphIr } from '@wildshard/format/materialGraph';
21
21
  import { loadLookGraphCompiler } from './graphBackend';
22
+ import { LOOK_SKY_BUDGET } from '@wildshard/format/look-sky';
22
23
  import { EmissiveLook } from './families/emissive';
23
24
  import { familyMaterial } from './families/registry';
24
25
  import { ToonLook } from './families/toon';
@@ -77,6 +78,13 @@ export interface DataLookSpec {
77
78
  readonly exposure?: number;
78
79
  readonly vignette?: LookVignette | null;
79
80
  readonly bloomRadius?: number | null;
81
+ /**
82
+ * SHARD-SOURCE AP14 (`look.sky`): the dome's painted sky, an unlit material graph over the dome's direction
83
+ * (`normalize(positionLocal)`), compiled on the page's renderer with the backdrop in place of the gradient. The
84
+ * environment (`light.environment`) is filtered from the same dome, so reflections show the painted sky. Absent or
85
+ * null: the gradient of the keys' zenith and horizon.
86
+ */
87
+ readonly sky?: GraphIr | null;
80
88
  }
81
89
 
82
90
  /** A sampled look: plain numbers, blended between the two keys around a time of day. */
@@ -118,13 +126,23 @@ export function sampleLook(keys: readonly LookKey[], time: number, out: LookSamp
118
126
  return out;
119
127
  }
120
128
 
129
+
130
+ /**
131
+ * SHARD-SOURCE AP17: what a data look takes in place (`LookStrategy.liveLook`, driven by `wildshard watch` through engine's
132
+ * dev hook v2): its spec as a fresh build would read it, plus the engine bloom's intensity and threshold (the level grade's
133
+ * at boot). The keys, the sun's arc, exposure, tone, vignette and bloom go live; the light rows and the LUT must not change.
134
+ */
135
+ export interface LiveLook extends Omit<DataLookSpec, 'lut'> {
136
+ readonly lut: string | null;
137
+ readonly bloom: { readonly intensity: number; readonly threshold: number; readonly radius: number | null };
138
+ }
121
139
  /** The engine clock for a data look (an hour clock with one day-long segment, the sun on the day's arc). */
122
140
  export function dataLookClock(day: LookDay, dayOverride: number | null): DayCycle {
123
141
  return normalizedDayClock(day, dayOverride);
124
142
  }
125
143
 
126
144
  /** The engine's gradient dome: radius 600 m, drawn first, unfogged, kept on the camera by Game (the backdrop's `clouds`). */
127
- function gradientDome(): { dome: THREE.Mesh<THREE.SphereGeometry, THREE.ShaderMaterial>; zenith: THREE.Color; horizon: THREE.Color } {
145
+ function gradientDome(): { dome: THREE.Mesh<THREE.SphereGeometry, THREE.Material>; zenith: THREE.Color; horizon: THREE.Color } {
128
146
  const zenith = new THREE.Color(), horizon = new THREE.Color();
129
147
  const material = new THREE.ShaderMaterial({ side: THREE.BackSide, depthWrite: false, fog: false,
130
148
  uniforms: { uZenith: { value: zenith }, uHorizon: { value: horizon } },
@@ -136,6 +154,18 @@ function gradientDome(): { dome: THREE.Mesh<THREE.SphereGeometry, THREE.ShaderMa
136
154
  return { dome, zenith, horizon };
137
155
  }
138
156
 
157
+ /**
158
+ * AP14: a look's painted sky on the dome: its graph compiled (by `compile`, the page's look-graph compiler) as an unlit
159
+ * material drawn on the inside of the sphere, first, unfogged and writing no depth, as the gradient's material is (the
160
+ * old material is freed).
161
+ */
162
+ export function paintDome(dome: THREE.Mesh<THREE.SphereGeometry, THREE.Material>, sky: GraphIr, compile: (ir: GraphIr, opts: { readonly budget: GraphBudget }) => { readonly material: THREE.Material }): void {
163
+ const { material } = compile(sky, { budget: LOOK_SKY_BUDGET });
164
+ material.side = THREE.BackSide; material.depthWrite = false; material.name = 'engine.look.sky';
165
+ if ('fog' in material) material.fog = false;
166
+ dome.material.dispose(); dome.material = material;
167
+ }
168
+
139
169
  async function lutTexture(url: string | Uint8Array | null): Promise<LookupTexture | null> {
140
170
  if (url === null) return null;
141
171
  const data = typeof url === 'string' ? await fetchLut(url) : Uint8Array.from(url);
@@ -239,9 +269,15 @@ ${mist ? `
239
269
  #endif`);
240
270
  shader.fragmentShader = `#ifdef USE_FOG\nuniform float wsLookFogNear; uniform float wsLookFogFar; uniform float wsLookFogEnabled;\n#endif\n${patched}`;
241
271
  };
242
- const owned: { dome: THREE.Mesh<THREE.SphereGeometry, THREE.ShaderMaterial> | null; lut: LookupTexture | null; pools: THREE.Object3D | null; rim: boolean;
272
+ const owned: { dome: THREE.Mesh<THREE.SphereGeometry, THREE.Material> | null; lut: LookupTexture | null; pools: THREE.Object3D | null; rim: boolean;
243
273
  lamps: ReturnType<typeof lampLights> | null; bounce: ReturnType<typeof bounceLight> | null; environment: THREE.WebGLRenderTarget | null;
244
- glow: THREE.Object3D[] | null } = { dome: null, lut: null, pools: null, rim: false, lamps: null, bounce: null, environment: null, glow: null };
274
+ glow: THREE.Object3D[] | null; fx: EngineEffects | null; exposure: ExposureEffect | null; clock: DayCycle | null;
275
+ chain: { vignette: { offset: number; darkness: number }; radius: number } | null } = { dome: null, lut: null, pools: null, rim: false, lamps: null, bounce: null, environment: null, glow: null,
276
+ fx: null, exposure: null, clock: null, chain: null };
277
+ // AP17: what `liveLook` last set (the light rows and the LUT are compared with the build's, never set)
278
+ let day = spec.day, dayOverride = spec.dayOverride;
279
+ const fixedOf = (light: DataLookSpec['light'], lut: unknown): string => JSON.stringify({ light: light ?? null, lut: typeof lut === 'string' || lut === null ? lut : 'bytes' });
280
+ const fixed = fixedOf(spec.light, spec.lut);
245
281
  const shadow = spec.light?.shadow ?? null;
246
282
  const bounceRow = spec.light?.bounce ?? null;
247
283
  // the bounce exists from the backdrop on (it follows the clock's sun there); compose adds it to the scene
@@ -254,6 +290,27 @@ ${mist ? `
254
290
  keys = next;
255
291
  return true;
256
292
  },
293
+ liveLook: (next) => {
294
+ const { fx, clock, chain } = owned;
295
+ // check everything first: a refusal changes nothing
296
+ if (fx === null || clock === null || chain === null) return false;
297
+ if (next.keys.length === 0 || next.keys.some((key) => (key.fog.near !== undefined) !== linear)) return false;
298
+ // the light rows and the LUT are built once; an exposure on a chain built without one, a new day length or a new fixed
299
+ // time of day each need a new look
300
+ if (fixedOf(next.light, next.lut) !== fixed || ((next.exposure ?? 0) !== 0 && owned.exposure === null)) return false;
301
+ if (next.day.minutes !== day.minutes || next.dayOverride !== dayOverride) return false;
302
+ keys = next.keys; day = next.day; dayOverride = next.dayOverride;
303
+ Object.assign(clock.spec.sun as { maxElevation: number; azimuthOffset: number }, { maxElevation: next.day.maxElevation, azimuthOffset: next.day.azimuth });
304
+ const exposure = owned.exposure?.uniforms.get('uExposure');
305
+ if (exposure !== undefined) exposure.value = 2 ** (next.exposure ?? 0);
306
+ const tone = next.aces === true ? ToneMappingMode.ACES_FILMIC : next.neutral === true ? ToneMappingMode.NEUTRAL : ToneMappingMode.AGX;
307
+ if (fx.tone.mode !== tone) fx.tone.mode = tone;
308
+ const vignette = next.vignette ?? chain.vignette;
309
+ fx.vignette.offset = vignette.offset; fx.vignette.darkness = vignette.darkness;
310
+ fx.bloom.intensity = next.bloom.intensity; fx.bloom.luminanceMaterial.threshold = next.bloom.threshold;
311
+ fx.bloom.mipmapBlurPass.radius = next.bloom.radius ?? next.bloomRadius ?? chain.radius;
312
+ return true;
313
+ },
257
314
  // the sky builds before the composer: the level scope takes the dome and the LUT here
258
315
  mode: 'extend', chain: 'clean', compose: ({ engineChain, scene, scope, fx, renderer }) => {
259
316
  const rim = spec.light?.rim ?? null, pools = spec.light?.pools ?? null, lamps = spec.light?.lamps ?? null;
@@ -328,6 +385,9 @@ ${mist ? `
328
385
  if (dome !== null) { scope.own(dome.geometry); scope.own(dome.material); scope.onDispose(() => { dome.removeFromParent(); }); }
329
386
  if (lut !== null) scope.own(lut);
330
387
  const chain = engineChain('clean');
388
+ // AP17: the chain as the engine built it, before this look's own vignette and bloom spread, for `liveLook`
389
+ owned.fx = fx; owned.chain = { vignette: { offset: fx.vignette.offset, darkness: fx.vignette.darkness }, radius: fx.bloom.mipmapBlurPass.radius };
390
+ scope.onDispose(() => { if (owned.fx === fx) { owned.fx = null; owned.chain = null; owned.exposure = null; } });
331
391
  // B2: the Neutral curve keeps the look's saturated albedo saturated, where AgX would grey it (asked after the clean chain)
332
392
  if (spec.neutral === true) fx.tone.mode = ToneMappingMode.NEUTRAL;
333
393
  // M4.7: ACES, the look's own vignette and bloom spread, and its exposure ahead of the curve
@@ -335,7 +395,7 @@ ${mist ? `
335
395
  if (spec.vignette !== undefined && spec.vignette !== null) { fx.vignette.offset = spec.vignette.offset; fx.vignette.darkness = spec.vignette.darkness; }
336
396
  if (spec.bloomRadius !== undefined && spec.bloomRadius !== null) fx.bloom.mipmapBlurPass.radius = spec.bloomRadius;
337
397
  const stops = spec.exposure ?? 0, at = chain.indexOf(fx.tone);
338
- if (stops !== 0 && at !== -1) { const exposure = new ExposureEffect(stops); scope.own(exposure); chain.splice(at, 0, exposure); }
398
+ if (stops !== 0 && at !== -1) { const exposure = new ExposureEffect(stops); scope.own(exposure); chain.splice(at, 0, exposure); owned.exposure = exposure; }
339
399
  return { chain };
340
400
  },
341
401
  // G992: no sun disc or corona over the gradient dome. A 1° disc read as a blurred speck with a halo ("half-assed moon
@@ -343,9 +403,12 @@ ${mist ? `
343
403
  sky: { clouds: false, planet: false, sun: { disc: false, halo: false } },
344
404
  // M4.7: the look's shadow radius and normal bias (its strength is set on the cascades each frame, below)
345
405
  ...(shadow === null ? {} : { shadows: { rig: 'tier' as const, radius: shadow.radius, normalBias: shadow.normalBias } }),
346
- backdrop: async ({ sky }) => {
406
+ backdrop: async ({ sky, renderer }) => {
347
407
  const clock = dataLookClock(spec.day, spec.dayOverride), now = lookSample();
408
+ owned.clock = clock;
348
409
  const { dome, zenith, horizon } = gradientDome();
410
+ // AP14: the painted sky replaces the gradient before the compose filters the environment from the dome
411
+ if (spec.sky !== undefined && spec.sky !== null) paintDome(dome, spec.sky, (await loadLookGraphCompiler(renderer)).compileGraph);
349
412
  owned.dome = dome;
350
413
  const bounce = owned.bounce;
351
414
  let targets: SkyBackdropTargets | null = null, flicker = 0;
@@ -62,6 +62,8 @@ export function compilePbr(params: PbrMaterialParams, textures: TextureResolver,
62
62
  alphaTest: params.alphaCutoff,
63
63
  });
64
64
  m.name = 'family:pbr';
65
+ // M4.3: the surface's own glow, added over its lit colour (lamp glass that the sun still lights); absent = black
66
+ if (params.emissive !== undefined) { m.emissive.setRGB(...params.emissive, THREE.SRGBColorSpace); m.emissiveIntensity = params.emissiveIntensity ?? 1; }
65
67
  if (params.ground !== null && params.measure !== null) throw new Error('material family: a PBR surface takes a ground or a measure layer, not both');
66
68
  if (params.ground !== null) applyGround(m, params.ground, textures, emitterPools);
67
69
  if (params.measure !== null) applyMeasure(m, params.measure);
@@ -16,6 +16,7 @@ import { parseFamilyMaterial, type FamilyMaterialParams } from '@wildshard/forma
16
16
  import { compileEmissive, type EmissiveLook } from './emissive';
17
17
  import { compilePainterly, type PainterlyLook } from './painterly';
18
18
  import { compilePbr, type TextureResolver } from './pbr';
19
+ import { applySceneEmissive, applySceneSurface } from './sceneSurface';
19
20
  import { updateGround } from './ground';
20
21
  import { compileToon, type ToonLook } from './toon';
21
22
 
@@ -39,13 +40,21 @@ const live = new Map<THREE.Material, FamilyMaterialParams>();
39
40
 
40
41
  function compile(params: FamilyMaterialParams, ctx: FamilyContext): THREE.Material {
41
42
  if (params.family === 'toon') return compileToon(params, ctx.toon);
42
- if (params.family === 'pbr') return compilePbr(params, ctx.textures, ctx.emitterPools);
43
+ if (params.family === 'pbr') {
44
+ // SHARD-SOURCE AP10, AP12: a scene's alpha, decal offset, sway and uv scroll, on the emissive look's clock
45
+ const m = compilePbr(params, ctx.textures, ctx.emitterPools);
46
+ applySceneSurface(m, params, ctx.emissive?.uniforms.famEmitTime);
47
+ return m;
48
+ }
43
49
  if (params.family === 'painterly') {
44
50
  if (ctx.painterly === undefined) throw new Error('material family: a painterly entry needs a painterly look in its family context');
45
51
  return compilePainterly(params, ctx.painterly, ctx.textures);
46
52
  }
47
53
  if (ctx.emissive === undefined) throw new Error('material family: an emissive entry needs an emissive look in its family context');
48
- return compileEmissive(params, ctx.emissive, ctx.textures);
54
+ const m = compileEmissive(params, ctx.emissive, ctx.textures);
55
+ // SHARD-SOURCE AP11, AP12: alpha cards, camera-facing cards and their declared motion
56
+ applySceneEmissive(m, params, ctx.emissive.uniforms.famEmitTime);
57
+ return m;
49
58
  }
50
59
 
51
60
  /**