File size: 19,944 Bytes
f46efae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scroll Causality Bench — Emitted vs Observed Pixel Invariance</title>
<style>
  :root{--bg:#0b0e14;--panel:#131824;--ink:#dce2ee;--dim:#8b94a7;--acc:#4fd1a5;--warn:#f6ad55;--bad:#fc8181;--mag:#c084fc;}
  *{box-sizing:border-box;margin:0;}
  body{background:var(--bg);color:var(--ink);font:13px/1.45 ui-monospace,Menlo,Consolas,monospace;padding:14px;}
  h1{font-size:16px;color:var(--acc);margin-bottom:2px;}
  .sub{color:var(--dim);font-size:11px;margin-bottom:10px;max-width:1200px;}
  .grid{display:grid;grid-template-columns:300px 340px 1fr;gap:10px;align-items:start;}
  .panel{background:var(--panel);border:1px solid #232b3d;border-radius:8px;padding:10px;}
  .panel h2{font-size:10px;letter-spacing:.08em;text-transform:uppercase;color:var(--dim);margin-bottom:6px;}
  canvas{display:block;width:100%;border-radius:6px;background:#000;}
  video{display:none;}
  .stat{display:flex;justify-content:space-between;gap:8px;padding:2px 0;border-bottom:1px dotted #222b40;font-size:11px;}
  .stat .k{color:var(--dim);} .stat .v{text-align:right;}
  .v.acc{color:var(--acc);} .v.warn{color:var(--warn);} .v.bad{color:var(--bad);} .v.mag{color:var(--mag);}
  button{background:#1c2740;color:var(--ink);border:1px solid #35446b;padding:5px 10px;border-radius:5px;font:inherit;cursor:pointer;margin:2px 4px 2px 0;font-size:11px;}
  button:hover{background:#25345a;}
  button.primary{border-color:var(--acc);color:var(--acc);}
  label{font-size:10px;color:var(--dim);display:block;margin-top:5px;}
  input[type=range]{width:100%;margin:2px 0 6px;}
  .verdict{padding:4px 6px;border-radius:5px;font-size:11px;margin:3px 0;}
  .v-tl{border:1px solid var(--acc);color:var(--acc);}
  .v-nl{border:1px solid var(--warn);color:var(--warn);}
  .v-sl{border:1px solid var(--bad);color:var(--bad);}
  table{width:100%;font-size:10px;border-collapse:collapse;margin-top:4px;}
  td,th{padding:2px 4px;border-bottom:1px dotted #222b40;text-align:right;}
  th{color:var(--dim);text-align:left;font-weight:normal;}
  td.cl{text-align:left;}
  #log{height:130px;overflow-y:auto;font-size:10px;}
  #log div{padding:2px 0;border-bottom:1px dotted #1c2334;}
  .ok{color:var(--acc);} .warn{color:var(--warn);} .bad{color:var(--bad);} .dim{color:var(--dim);}
  .footer{margin-top:10px;color:var(--dim);font-size:10px;max-width:1200px;}
</style>
</head>
<body>
<h1>Scroll Causality Bench — Screen Emission vs Camera Observation</h1>
<div class="sub">The screen writes the past: a multi-class test pattern scrolls downward at speed v. The webcam (point it at the screen — phone works) is the observer. The bench continuously cross-correlates emitted vs received luminance to measure the causal lag τ and coupling ρ, checks per-channel color invariance (does R stay R through the observer?), and classifies each content class by its causal relation. A simulated redshift channel runs in parallel as the physics comparator.</div>
<div class="grid">
  <div>
    <div class="panel">
      <h2>Emitted past (scrolling classes)</h2>
      <canvas id="emitCv" width="300" height="300"></canvas>
      <label>scroll speed v (px/frame): <span id="vVal">1.5</span></label>
      <input type="range" id="vParam" min="0.2" max="6" step="0.1" value="1.5">
      <label>redshift channel: delay τ₀ + blur (1+z) + spectral tilt</label>
      <input type="range" id="zParam" min="0" max="4" step="0.1" value="1">
      <div style="margin-top:4px">
        <button id="camBtn" class="primary">Open camera (observer)</button>
        <button id="stopCam">Stop camera</button>
      </div>
      <div id="camStatus" class="dim">observer idle — using simulated redshift channel only</div>
      <canvas id="camView" width="280" height="90" style="margin-top:5px"></canvas>
      <label><input type="checkbox" id="useCam" checked> webcam as observer (uncheck = sim channel)</label>
    </div>
  </div>
  <div>
    <div class="panel">
      <h2>Causal relation (emitted vs received)</h2>
      <canvas id="corrCv" width="320" height="130"></canvas>
      <div class="stat"><span class="k">causal lag τ (frames)</span><span class="v mag" id="lag">—</span></div>
      <div class="stat"><span class="k">coupling ρ (max corr)</span><span class="v" id="rho">—</span></div>
      <div class="stat"><span class="k">global verdict</span><span class="v acc" id="gVerdict">—</span></div>
    </div>
    <div class="panel" style="margin-top:8px">
      <h2>Pixel color invariance (per channel)</h2>
      <canvas id="rgbCv" width="320" height="110"></canvas>
      <div class="stat"><span class="k">R invariance err</span><span class="v" id="eR">—</span></div>
      <div class="stat"><span class="k">G invariance err</span><span class="v" id="eG">—</span></div>
      <div class="stat"><span class="k">B invariance err</span><span class="v" id="eB">—</span></div>
      <div class="stat"><span class="k">hue rotation</span><span class="v" id="hue">—</span></div>
    </div>
  </div>
  <div>
    <div class="panel">
      <h2>Causality classes (per content type)</h2>
      <table>
        <tr><th>class</th><th>ρ</th><th>τ</th><th>Δcol</th><th>verdict</th></tr>
        <tbody id="clsTable"></tbody>
      </table>
      <div class="dim" style="font-size:9px;margin-top:6px">
        TIMELIKE: ρ high, stable τ — the class is causally readable by the observer.<br>
        NULL: ρ moderate, τ drifting — boundary case (marginal structure).<br>
        SPACELIKE: ρ low — no detectable causal link (observer sees no trace).
      </div>
      <canvas id="traceCv" width="300" height="120" style="margin-top:8px"></canvas>
      <div class="dim" style="font-size:9px">emitted (cyan) vs received (magenta) luminance, lag-aligned</div>
    </div>
    <div class="panel" style="margin-top:8px">
      <h2>Event log</h2>
      <div id="log"></div>
    </div>
  </div>
</div>
<div class="footer">Method: every frame, the emitted pattern's mean RGB is logged (screen = writer); the observer's mean RGB is logged (camera = reader, or the simulated redshift channel). Cross-correlation over a ±lag window gives τ and ρ; per-channel residuals give color invariance; per-class ρ is computed over frames where that class dominates the pattern. This is the horizontal version of the ledger check — correlation of hysteretic records across two channels that share an environment.</div>

<script>
const $=id=>document.getElementById(id);
const log=(m,c="")=>{const d=document.createElement("div");if(c)d.className=c;d.textContent=m;const L=$("log");L.prepend(d);if(L.children.length>150)L.lastChild.remove();};

// ---------- scrolling test pattern ----------
const CLASSES=[
  {name:"uniform-red",  draw:(ctx,y,h)=>{ctx.fillStyle="#c03030";ctx.fillRect(0,y,300,h);}},
  {name:"uniform-green",draw:(ctx,y,h)=>{ctx.fillStyle="#30c050";ctx.fillRect(0,y,300,h);}},
  {name:"uniform-blue", draw:(ctx,y,h)=>{ctx.fillStyle="#3050d0";ctx.fillRect(0,y,300,h);}},
  {name:"gradient",     draw:(ctx,y,h)=>{const g=ctx.createLinearGradient(0,y,0,y+h);g.addColorStop(0,"#e0e0e0");g.addColorStop(1,"#202020");ctx.fillStyle=g;ctx.fillRect(0,y,300,h);}},
  {name:"hard-edge",    draw:(ctx,y,h)=>{ctx.fillStyle="#f0f0f0";ctx.fillRect(0,y,300,h/2);ctx.fillStyle="#080808";ctx.fillRect(0,y+h/2,300,h/2);}},
  {name:"texture-bars", draw:(ctx,y,h)=>{for(let i=0;i<12;i++){ctx.fillStyle=i%2?"#d0d0d0":"#404040";ctx.fillRect(i*25,y,25,h);}}},
  {name:"noise",        draw:(ctx,y,h)=>{for(let i=0;i<8;i++){ctx.fillStyle=Math.random()>0.5?"#c8c8c8":"#383838";ctx.fillRect(Math.random()*300,y+h*Math.random(),10,4);}}},
  {name:"checker",      draw:(ctx,y,h)=>{const s=12;for(let yy=0;yy<h;yy+=s)for(let xx=0;xx<300;xx+=s){ctx.fillStyle=((xx/s+yy/s+(y/s|0))%2)?"#e0e0e0":"#181818";ctx.fillRect(xx,y+yy,s,Math.min(s,h-yy));}}}
];
const BAND_H=40;
const emitCv=$("emitCv"), ectx=emitCv.getContext("2d",{willReadFrequently:true});
let scrollY=0;

// ---------- time series buffers ----------
const BUF=360, LAGMAX=90;
let emitL=new Array(BUF).fill(0), emitR=new Array(BUF).fill(0), emitG=new Array(BUF).fill(0), emitB=new Array(BUF).fill(0);
let recvL=new Array(BUF).fill(0), recvR=new Array(BUF).fill(0), recvG=new Array(BUF).fill(0), recvB=new Array(BUF).fill(0);
let classAt=new Array(BUF).fill(-1); // dominant class index per frame
let head=0, nSamples=0;

// ---------- observer: webcam ----------
let camMode=false, video=$("camVideo"), stream=null;
$("camBtn").onclick=async()=>{
  if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){$("camStatus").className="bad";$("camStatus").textContent="getUserMedia unavailable — sim channel only";camMode=false;$("useCam").checked=false;return;}
  try{
    stream=await navigator.mediaDevices.getUserMedia({video:{width:{ideal:640},height:{ideal:480}}});
    video.srcObject=stream; video.muted=true;
    await video.play().catch(()=>{ $("camStatus").className="warn";$("camStatus").textContent="click page to start stream"; const k=()=>{video.play().catch(()=>{});window.removeEventListener("pointerdown",k);}; window.addEventListener("pointerdown",k); });
    camMode=true;
    $("camStatus").className="ok";$("camStatus").textContent="observer live: "+video.videoWidth+"×"+video.videoHeight;
    log("observer online — point the camera at the scrolling pattern","ok");
  }catch(e){$("camStatus").className="bad";$("camStatus").textContent="camera failed: "+e.name;$("useCam").checked=false;camMode=false;}
};
$("stopCam").onclick=()=>{ if(stream){stream.getTracks().forEach(t=>t.stop());stream=null;} video.srcObject=null; camMode=false; $("camStatus").className="dim";$("camStatus").textContent="observer stopped — sim channel only"; };
$("useCam").onchange=e=>{ if(!e.target.checked){camMode=false;log("observer switched to simulated redshift channel","dim");} else if(stream){camMode=true;} };

const camView=$("camView"), camCtx=camView.getContext("2d",{willReadFrequently:true});
const sampC=document.createElement("canvas"); sampC.width=24; sampC.height=24;
const sampCtx=sampC.getContext("2d",{willReadFrequently:true});

// ---------- simulated redshift channel (physics comparator) ----------
// received(t) = blur(delay(emitted(t-τ0))) with spectral tilt toward red + attenuation
function simChannel(ser,sg,sb){
  const z=parseFloat($("zParam").value);
  const tau0=Math.round(z*4);            // light travel delay grows with redshift
  const blur=Math.max(1,z*0.8);          // aperture smear
  const fade=1/(1+z*0.25);
  const W=Math.round(blur);
  let r=0,g=0,b=0,n=0;
  for(let k=0;k<=W;k++){
    const idx=(head-tau0-k+BUF*2)%BUF;
    if(idx<0||idx>=BUF||emitL[idx]===undefined)continue;
    const w=1/(1+k);
    r+=ser[idx]*w*1.06;  // spectral tilt: red survives
    g+=sg[idx]*w*0.92;
    b+=sb[idx]*w*0.80;   // blue attenuated (cosmological dimming)
    n+=w;
  }
  n=n||1;
  return [r/n*fade*255, g/n*fade*255, b/n*fade*255];
}

// ---------- per-frame capture ----------
function capture(){
  // 1. draw scrolling pattern
  ectx.fillStyle="#000";ectx.fillRect(0,0,300,300);
  const total=CLASSES.length*BAND_H;
  let y0=-((scrollY%total));
  let centerClass=-1;
  for(let b=-1;b<=Math.ceil(300/total)+1;b++){
    for(let i=0;i<CLASSES.length;i++){
      const y=y0+b*total+i*BAND_H;
      if(y+ BAND_H<0||y>300)continue;
      CLASSES[i].draw(ectx,y,BAND_H);
      if(y<=150&&y+BAND_H>150)centerClass=i;
    }
  }
  scrollY+=parseFloat($("vParam").value);
  // 2. emitted mean RGB
  const ed=ectx.getImageData(0,0,300,300).data;
  let eR=0,eG=0,eB=0; const nPx=300*300;
  for(let i=0;i<nPx;i++){eR+=ed[i*4];eG+=ed[i*4+1];eB+=ed[i*4+2];}
  eR/=nPx;eG/=nPx;eB/=nPx;
  const eL=0.299*eR+0.587*eG+0.114*eB;
  // 3. received mean RGB
  let rR,rG,rB;
  if(camMode&&video.readyState>=2){
    camCtx.drawImage(video,0,0,camView.width,camView.height);
    const rd=camCtx.getImageData(0,0,camView.width,camView.height).data;
    let sR=0,sG=0,sB=0; const m=camView.width*camView.height;
    for(let i=0;i<m;i++){sR+=rd[i*4];sG+=rd[i*4+1];sB+=rd[i*4+2];}
    rR=sR/m;rG=sG/m;rB=sB/m;
  }else{
    [rR,rG,rB]=simChannel(emitR,emitG,emitB);
  }
  const rL=0.299*rR+0.587*rG+0.114*rB;
  // 4. push into ring buffers
  head=(head+1)%BUF;
  emitR[head]=eR;emitG[head]=eG;emitB[head]=eB;emitL[head]=eL;
  recvR[head]=rR;recvG[head]=rG;recvB[head]=rB;recvL[head]=rL;
  classAt[head]=centerClass;
  nSamples++;
}

// ---------- cross-correlation ----------
function pearson(a,b){
  const n=a.length; let ma=0,mb=0;
  for(let i=0;i<n;i++){ma+=a[i];mb+=b[i];} ma/=n;mb/=n;
  let num=0,da=0,db=0;
  for(let i=0;i<n;i++){const x=a[i]-ma,y=b[i]-mb;num+=x*y;da+=x*x;db+=y*y;}
  return (da&&db)?num/Math.sqrt(da*db):0;
}
function bestLag(){
  const win=60; // usable window
  let best=0,bestR=-2;
  for(let lag=-LAGMAX;lag<=LAGMAX;lag++){
    const e=[],r=[];
    for(let k=0;k<win;k++){
      const ri=(head-k+BUF*2)%BUF;
      const ei=(head-k-lag+BUF*4)%BUF;
      if(emitL[ei]===undefined)continue;
      e.push(emitL[ei]);r.push(recvL[ri]);
    }
    if(e.length<30)continue;
    const c=pearson(e,r);
    if(c>bestR){bestR=c;best=lag;}
  }
  return {lag:best,rho:bestR};
}

// ---------- color invariance (lag-aligned) ----------
function colorInvariance(lag){
  const win=60; let sR=0,sG=0,sB=0,sE=0,sHue=0,n=0;
  for(let k=0;k<win;k++){
    const ri=(head-k+BUF*2)%BUF;
    const ei=(head-k-lag+BUF*4)%BUF;
    if(emitR[ei]===undefined)continue;
    const eLum=emitL[ei]||1, rLum=recvL[ri]||1;
    // normalized chromaticity error: compare hue independent of brightness
    const eH=Math.atan2(Math.sqrt(3)*(emitG[ei]-emitB[ei]),2*emitR[ei]-emitG[ei]-emitB[ei]);
    const rH=Math.atan2(Math.sqrt(3)*(recvG[ri]-recvB[ri]),2*recvR[ri]-recvG[ri]-recvB[ri]);
    let dh=Math.abs(eH-rH); if(dh>Math.PI)dh=2*Math.PI-dh;
    sHue+=dh;
    // per-channel gain: received channel / emitted channel (luma-normalized)
    if(eLum>20){
      sR+=Math.abs(recvR[ri]/rLum - emitR[ei]/eLum);
      sG+=Math.abs(recvG[ri]/rLum - emitG[ei]/eLum);
      sB+=Math.abs(recvB[ri]/rLum - emitB[ei]/eLum);
      n++;
    }
  }
  n=n||1;
  return {R:sR/n,G:sG/n,B:sB/n,hue:sHue/n};
}

// ---------- per-class analysis ----------
const CLS_KEYS=CLASSES.map(c=>c.name);
let clsAccum={}; CLS_KEYS.forEach(k=>clsAccum[k]={pairs:[]});
function perClass(lag){
  const win=60;
  for(let k=0;k<win;k++){
    const ri=(head-k+BUF*2)%BUF;
    const ei=(head-k-lag+BUF*4)%BUF;
    const ci=classAt[ei];
    if(ci<0||emitL[ei]===undefined)continue;
    const key=CLASSES[ci].name;
    // local structure amount (how much this frame differs from a flat mean) via buffer value spread is overkill:
    // store pairs for correlation
    if(clsAccum[key].pairs.length>240)clsAccum[key].pairs.shift();
    clsAccum[key].pairs.push([emitL[ei],recvL[ri]]);
    // color error for this class
    const eLum=emitL[ei]||1, rLum=recvL[ri]||1;
    if(eLum>20){
      const ce=(Math.abs(recvR[ri]/rLum-emitR[ei]/eLum)+Math.abs(recvG[ri]/rLum-emitG[ei]/eLum)+Math.abs(recvB[ri]/rLum-emitB[ei]/eLum))/3;
      clsAccum[key].colSum=(clsAccum[key].colSum||0)*0.98+ce*0.02;
    }
  }
}
function classify(rho){
  if(rho>0.6)return {t:"TIMELIKE",c:"v-tl"};
  if(rho>0.25)return {t:"NULL",c:"v-nl"};
  return {t:"SPACELIKE",c:"v-sl"};
}

// ---------- rendering ----------
function renderCorr(bl){
  const cv=$("corrCv"),ctx=cv.getContext("2d");
  ctx.fillStyle="#05080d";ctx.fillRect(0,0,cv.width,cv.height);
  ctx.strokeStyle="#1a2540";ctx.lineWidth=1;
  ctx.beginPath();ctx.moveTo(cv.width/2,0);ctx.lineTo(cv.width/2,cv.height);ctx.stroke();
  for(let i=0;i<=4;i++){ctx.beginPath();ctx.moveTo(0,cv.height*i/4);ctx.lineTo(cv.width,cv.height*i/4);ctx.stroke();}
  if(!bl)return;
  // plot correlation vs lag
  ctx.strokeStyle=bl.rho>0.6?"#4fd1a5":(bl.rho>0.25?"#f6ad55":"#fc8181");
  ctx.lineWidth=2;ctx.beginPath();
  for(let px=0;px<cv.width;px++){
    const lag=Math.round((px/cv.width)*2*LAGMAX-LAGMAX);
    const e=[],r=[];
    for(let k=0;k<50;k++){
      const ri=(head-k+BUF*2)%BUF, ei=(head-k-lag+BUF*4)%BUF;
      if(emitL[ei]===undefined)continue;
      e.push(emitL[ei]);r.push(recvL[ri]);
    }
    const c=e.length>25?pearson(e,r):0;
    const y=cv.height-(c+1)/2*cv.height;
    if(px===0)ctx.moveTo(px,y);else ctx.lineTo(px,y);
  }
  ctx.stroke();
  // peak marker
  const px=(bl.lag+LAGMAX)/(2*LAGMAX)*cv.width;
  ctx.fillStyle="#ffffff";ctx.beginPath();ctx.arc(px,cv.height-(bl.rho+1)/2*cv.height,4,0,7);ctx.fill();
  ctx.fillStyle="#8b94a7";ctx.font="9px monospace";
  ctx.fillText("−τ",4,12);ctx.fillText("+τ",cv.width-18,12);
  ctx.fillText("ρ vs lag — peak = causal relation",cv.width/2-60,12);
}
function renderRGB(inv){
  const cv=$("rgbCv"),ctx=cv.getContext("2d");
  ctx.fillStyle="#05080d";ctx.fillRect(0,0,cv.width,cv.height);
  const chans=[["R",inv.R,"#fc8181"],["G",inv.G,"#4fd1a5"],["B",inv.B,"#60a5fa"]];
  chans.forEach((c,i)=>{
    const y=25+i*28;
    ctx.fillStyle="#8b94a7";ctx.font="10px monospace";ctx.fillText(c[0],8,y+10);
    ctx.fillStyle="#111";ctx.fillRect(24,y,cv.width-40,14);
    ctx.fillStyle=c[2];ctx.fillRect(24,y,Math.min(1,c[1]*3)*(cv.width-40),14);
    ctx.fillStyle="#dce2ee";ctx.fillText(c[1].toFixed(3),cv.width-14,y+10);
  });
  ctx.fillStyle="#8b94a7";ctx.font="9px monospace";
  ctx.fillText("chromatic gain error per channel (0 = color-invariant observer)",8,12);
}
function renderTrace(lag){
  const cv=$("traceCv"),ctx=cv.getContext("2d");
  ctx.fillStyle="#05080d";ctx.fillRect(0,0,cv.width,cv.height);
  const win=150;
  ctx.lineWidth=1.5;
  // emitted (cyan) and received shifted by lag (magenta)
  [[emitL,"#22d3ee"],[recvL,"#e879f9"]].forEach(([arr,col],ch)=>{
    ctx.strokeStyle=col;ctx.beginPath();
    for(let k=0;k<win;k++){
      const ei=(head-k-(ch===0?0:lag)+BUF*4)%BUF;
      const v=arr[ei]||0;
      const x=cv.width-(k/win)*cv.width;
      const y=cv.height-(v/255)*cv.height;
      if(k===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);
    }
    ctx.stroke();
  });
  ctx.fillStyle="#8b94a7";ctx.font="9px monospace";
  ctx.fillText("cyan: emitted(t)   magenta: received(t−τ) — overlap = invariance",6,12);
}
function renderClassTable(lag,rho){
  const tb=$("clsTable"); let html="";
  CLS_KEYS.forEach(k=>{
    const a=clsAccum[k];
    let r=0;
    if(a.pairs.length>20){
      const es=a.pairs.map(p=>p[0]),rs=a.pairs.map(p=>p[1]);
      r=pearson(es,rs);
    }
    const v=classify(r);
    const col=(a.colSum||0);
    html+=`<tr><td class="cl">${k}</td><td>${r.toFixed(2)}</td><td>${lag}</td><td>${col.toFixed(3)}</td><td><span class="${v.c}">${v.t}</span></td></tr>`;
  });
  tb.innerHTML=html;
}

// ---------- main loop ----------
let lastLog=0, frameN=0;
function tick(){
  capture();
  const bl=bestLag();
  const inv=colorInvariance(bl.lag);
  perClass(bl.lag);
  $("lag").textContent=bl.lag+" frames";
  $("rho").textContent=bl.rho.toFixed(3);
  $("rho").className= bl.rho>0.6?"v acc":(bl.rho>0.25?"v warn":"v bad");
  const gv=classify(bl.rho);
  const gV=$("gVerdict");
  gV.textContent=gv.t; gV.className="v "+(gv.t==="TIMELIKE"?"acc":(gv.t==="NULL"?"warn":"bad"));
  $("eR").textContent=inv.R.toFixed(3); $("eG").textContent=inv.G.toFixed(3); $("eB").textContent=inv.B.toFixed(3);
  $("hue").textContent=(inv.hue*180/Math.PI).toFixed(1)+"°";
  renderCorr(bl); renderRGB(inv); renderTrace(bl.lag);
  if(frameN%20===0)renderClassTable(bl.lag,bl.rho);
  // periodic log
  if(frameN-lastLog>180&&nSamples>BUF*0.5){
    lastLog=frameN;
    log(`ρ=${bl.rho.toFixed(3)} τ=${bl.lag}f · hue Δ=${(inv.hue*180/Math.PI).toFixed(1)}° · ${camMode?"webcam observer":"sim channel z="+$("zParam").value}`, bl.rho>0.5?"ok":"warn");
  }
  frameN++;
  requestAnimationFrame(tick);
}
log("bench armed: screen writes, observer reads — correlation is the causal check","dim");
log("point a camera at the scrolling pattern for the real observer; sim channel runs otherwise","dim");
tick();
</script>
</body>
</html>