Spaces:
Running
Running
File size: 45,410 Bytes
9a05ab0 0028e15 | 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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 | <!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>ANTTI'S BRAIN — DESCENT · infinite procedural key-hunt</title>
<style>
:root{
--void:#04060b; --ink:#c9d4e0; --amber:#e8b13a; --amber-dim:#8a6d2c;
--cyan:#54d2e2; --line:#1b2436; --dim:#67788d; --green:#4ec98f; --red:#e06060;
--gold:#ffd76a;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--void);overflow:hidden;
font-family:ui-monospace,"SF Mono",Menlo,Consolas,monospace;color:var(--ink)}
#gl{position:fixed;inset:0;width:100%;height:100%;display:block;cursor:grab}
#gl.drag{cursor:grabbing}
.panel{position:fixed;background:rgba(6,9,16,.74);border:1px solid var(--line);
backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
#hud{top:14px;left:14px;padding:12px 14px;min-width:270px;font-size:11px;line-height:1.7}
#hud .ttl{color:var(--amber);letter-spacing:.16em;font-size:10px;
text-transform:uppercase;margin-bottom:8px;display:flex;justify-content:space-between;gap:18px}
#hud .ttl b{color:var(--amber-dim);font-weight:400}
#hud .row{display:flex;justify-content:space-between;color:#8494a8;gap:14px}
#hud .row span{color:var(--ink)}
#hud .row .k{color:var(--dim)}
#hud .row .room{color:var(--cyan);letter-spacing:.08em}
#hud .row .lvl{color:var(--gold);letter-spacing:.12em}
#hud .row .keyok{color:var(--green)}
#hud .row .keyno{color:var(--gold)}
#resWrap{margin-top:6px}
#resWrap label{display:flex;justify-content:space-between;color:var(--dim);font-size:10px;margin-bottom:3px}
#resWrap label span{color:var(--gold)}
#resBar{height:4px;background:var(--line);position:relative;overflow:hidden}
#resFill{position:absolute;inset:0;width:0%;background:linear-gradient(90deg,#8a6d2c,var(--gold));
transition:width .25s}
#hud .note{margin-top:7px;border-top:1px solid var(--line);padding-top:6px;
color:var(--dim);font-size:10px;line-height:1.6;max-width:300px}
#ctl{bottom:14px;left:14px;padding:12px 14px;width:288px;font-size:11px}
#ctl h2{margin:0 0 9px;font-size:10px;letter-spacing:.16em;text-transform:uppercase;
color:var(--cyan);font-weight:600}
.modes{display:flex;gap:6px;margin-bottom:11px}
.modes button{flex:1}
.field{margin:8px 0}
.field label{display:flex;justify-content:space-between;color:#8494a8;margin-bottom:4px}
.field label var{color:var(--ink);font-style:normal}
input[type=range]{width:100%;height:2px;-webkit-appearance:none;appearance:none;
background:var(--line);outline:none;margin:6px 0}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:12px;height:12px;
border-radius:50%;background:var(--amber);cursor:pointer;border:2px solid var(--void)}
input[type=range]::-moz-range-thumb{width:12px;height:12px;border-radius:50%;
background:var(--amber);cursor:pointer;border:2px solid var(--void)}
.btns{display:flex;gap:6px;margin-top:9px;flex-wrap:wrap}
button{flex:1;min-width:56px;padding:7px 4px;background:transparent;color:var(--ink);
border:1px solid var(--line);font:inherit;font-size:10px;letter-spacing:.05em;
cursor:pointer;transition:.15s;text-transform:uppercase}
button:hover{border-color:var(--amber-dim);color:var(--amber)}
button.on{border-color:var(--cyan);color:var(--cyan)}
button:focus-visible{outline:2px solid var(--cyan);outline-offset:2px}
#stat{margin-top:7px;font-size:10px;color:var(--dim);min-height:13px;word-break:break-all}
#help{bottom:14px;right:14px;padding:11px 13px;font-size:10.5px;line-height:1.85;
color:#73859a;text-align:right}
#help b{color:var(--amber)}
#banner{position:fixed;top:38%;left:0;right:0;text-align:center;pointer-events:none;
opacity:0;transition:opacity .5s;z-index:8}
#banner .b1{font-size:22px;letter-spacing:.4em;color:var(--gold);text-transform:uppercase;
text-shadow:0 0 24px rgba(255,215,106,.55)}
#banner .b2{font-size:11px;color:var(--dim);margin-top:8px;letter-spacing:.14em}
#banner.show{opacity:1}
#boot{position:fixed;inset:0;display:flex;flex-direction:column;gap:10px;
align-items:center;justify-content:center;background:rgba(4,6,11,.92);z-index:9;
transition:opacity .8s;text-align:center;padding:20px}
#boot.gone{opacity:0;pointer-events:none}
#boot .big{font-size:15px;letter-spacing:.28em;color:var(--amber)}
#boot .sub{font-size:11px;color:var(--dim);line-height:1.9;max-width:520px}
#boot .sub em{color:var(--gold);font-style:normal}
#bootStat{font-size:11px;color:var(--cyan);letter-spacing:.12em;min-height:14px}
#boot.err .big{color:var(--red)}
#boot.err .sub{color:#c99;word-break:break-all;text-align:left}
</style>
<canvas id="gl"></canvas>
<div id="boot">
<div class="big">ANTTI'S BRAIN — DESCENT</div>
<div class="sub">an endless chain of chambers, hallucinated from one seed.<br>
each level is a run of rooms. somewhere in it, one crystal is not like the others:<br>
it pulses <em>gold</em>. touch it, and the red seal on the far gate dissolves.<br>
pass the gate: next level. rooms grow heavier, more twisted, stranger in shape.<br><br>
the <em>resonance</em> meter runs hot as you near the key. no enemies, no clocks —<br>
only geometry, depth, and the hash. nothing is stored; walk back and every<br>
room is re-dreamed identically. click / drag to enter · mouse look is inverted.</div>
<div id="bootStat">waking up…</div>
</div>
<div id="banner"><div class="b1" id="bn1"></div><div class="b2" id="bn2"></div></div>
<div id="hud" class="panel">
<div class="ttl">Brain — Descent <b id="fps">— fps</b></div>
<div class="row"><span class="k">level</span><span class="lvl" id="lvlV">1</span></div>
<div class="row"><span class="k">room in level</span><span id="progV">—</span></div>
<div class="row"><span class="k">chamber</span><span class="room" id="roomV">—</span></div>
<div class="row"><span class="k">index / shape</span><span id="roomI">—</span></div>
<div class="row"><span class="k">mass · twist</span><span id="massV">—</span></div>
<div class="row"><span class="k">key crystal</span><span id="keyV" class="keyno">not found</span></div>
<div id="resWrap"><label>resonance <span id="resT">—</span></label>
<div id="resBar"><div id="resFill"></div></div></div>
<div class="row" style="margin-top:6px"><span class="k">mode</span><span id="modeV">Boundary</span></div>
<div class="row"><span class="k">boundary</span><span id="src">—</span></div>
<div class="row"><span class="k">music</span><span id="musV">—</span></div>
<div class="row"><span class="k">position</span><span id="pos">—</span></div>
<div class="note" id="modeNote">—</div>
</div>
<div id="ctl" class="panel">
<h2>The descent</h2>
<div class="modes">
<button id="m0" class="on">Boundary</button>
<button id="m1">Projection</button>
<button id="m2">Cascade</button>
</div>
<div class="field"><label>Mass gain <var id="m_l">1.0</var></label>
<input id="m" type="range" min="0.2" max="2.2" step="0.05" value="1.0"></div>
<div class="field"><label>Lensing <var id="g_l">1.0</var></label>
<input id="g" type="range" min="0" max="3" step="0.05" value="1.0"></div>
<div class="field"><label>Music volume <var id="v_l">0.5</var></label>
<input id="v" type="range" min="0" max="1" step="0.05" value="0.5"></div>
<div class="btns">
<button id="bSave">Save</button>
<button id="bLoad">Load</button>
<button id="bCode">Save code</button>
</div>
<div class="btns">
<button id="bMus" class="on">Music: on</button>
<button id="bSrc">Test pattern</button>
</div>
<div class="btns">
<button id="bSeed">New brain</button>
<button id="bIdle" class="on">Idle spin: on</button>
</div>
<div id="stat"></div>
</div>
<div id="help" class="panel">
<b>W A S D</b> move · <b>Q E</b> down/up<br>
drag to look (inverted) · <b>shift</b> boost<br>
gold pulse = the key · red membrane = the seal<br>
the amber thread lives in the gates
</div>
<video id="vid" style="display:none" playsinline muted></video>
<script>
'use strict';
/* Do not hype. Do not lie. Just show. */
const $=id=>document.getElementById(id);
const cvs=$('gl'), boot=$('boot');
/* any failure paints itself on the boot screen instead of dying silently */
function bootErr(t){
boot.classList.add('err');boot.classList.remove('gone');
boot.innerHTML='<div class="big">It broke — here is why</div><div class="sub">'
+String(t).replace(/[<>&]/g,c=>({'<':'<','>':'>','&':'&'}[c])).slice(0,600)+'</div>';
}
window.onerror=(m,s,l,c,e)=>{bootErr((e&&e.stack)||m+' @ line '+l);};
window.addEventListener('unhandledrejection',e=>bootErr(e.reason));
let gl=cvs.getContext('webgl2',{antialias:false,powerPreference:'high-performance'});
if(!gl)gl=cvs.getContext('webgl2');
if(!gl){bootErr('No WebGL2 — this brain needs a WebGL2 browser.');throw new Error('no webgl2');}
const MAXW=15; /* up to 5 moons x 3 live rooms */
const VERT=`#version 300 es
void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);gl_Position=vec4(p*2.0-1.0,0.0,1.0);}`;
const FRAG=`#version 300 es
precision highp float;
out vec4 O;
uniform vec2 iRes;
uniform float iTime;
uniform vec3 camP,camR,camU,camF;
uniform int nWell,mode,keyWell;
uniform vec4 wells[${MAXW}]; /* xyz pos · w size */
uniform vec3 wellCol[${MAXW}];
uniform vec4 wellPar[${MAXW}]; /* x shape · y angA · z angB · w star-n */
uniform vec3 roomPos[3]; /* prev · current · next */
uniform vec4 roomPar[3]; /* x shape · y size · z half-height · w star-n */
uniform vec4 roomMod[3]; /* x twist · y ripple amp · z ripple freq · w mass */
uniform vec3 roomTintU[3];
uniform vec4 seal; /* xyz pos · w radius (<0 = open) */
uniform float mGain,lensK;
uniform sampler2D camTex;
/* ---------- primitives ---------- */
vec2 rot2(vec2 v,float a){float c=cos(a),s=sin(a);return vec2(c*v.x-s*v.y,s*v.x+c*v.y);}
float sdBox3(vec3 p,vec3 b){vec3 q=abs(p)-b;return length(max(q,0.))+min(max(q.x,max(q.y,q.z)),0.);}
float sdHexP(vec3 p,vec2 h){ /* cross-section xy · half-height z */
const vec3 k=vec3(-0.8660254,0.5,0.57735);
p=abs(p);
p.xy-=2.0*min(dot(k.xy,p.xy),0.0)*k.xy;
vec2 d=vec2(length(p.xy-vec2(clamp(p.x,-k.z*h.x,k.z*h.x),h.x))*sign(p.y-h.x),p.z-h.y);
return min(max(d.x,d.y),0.0)+length(max(d,0.0));}
float sdStarN(vec2 p,float r,float n,float m){ /* n-pointed star, m in (2,n) */
float an=3.1415927/n, en=3.1415927/m;
vec2 acs=vec2(cos(an),sin(an)), ecs=vec2(cos(en),sin(en));
float bn=mod(atan(p.x,p.y),2.0*an)-an;
p=length(p)*vec2(cos(bn),abs(sin(bn)));
p-=r*acs;
p+=ecs*clamp(-dot(p,ecs),0.0,r*acs.y/ecs.y);
return length(p)*sign(p.x);}
float sdOcta(vec3 p,float s){p=abs(p);return (p.x+p.y+p.z-s)*0.57735;}
float opExtr(float d2,float z,float h){vec2 w=vec2(d2,abs(z)-h);
return min(max(w.x,w.y),0.0)+length(max(w,0.0));}
float sdSeg(vec3 p,vec3 a,vec3 b){vec3 pa=p-a,ba=b-a;
float h=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-ba*h);}
/* ---------- the twelve shapes. rooms and moons share this ONE chain ----------
signed, negative inside. s = radius-ish, h = half-height, n = star points */
float shapeSD(vec3 q,float sh,float s,float h,float n){
int i=int(sh+0.5);
if(i==0) return sdBox3(q,vec3(s,h,s));
if(i==1) return length(q)-s;
if(i==2) return sdHexP(vec3(q.x,q.z,q.y),vec2(s,h));
if(i==3){float m=2.0+(n-2.0)*0.45;
return opExtr(sdStarN(q.xz,s*1.15,n,m),q.y,h);}
if(i==4) return sdOcta(q,s*1.5);
if(i==5) return max(length(q.xz)-s,abs(q.y)-h); /* cylinder */
if(i==6){vec3 c=q; c.y-=clamp(c.y,-h*0.55,h*0.55); /* capsule vault */
return length(c)-s*0.90;}
if(i==7) return max(sdBox3(q,vec3(s*0.95)),sdOcta(q,s*1.45)); /* cut crystal */
if(i==8) return (length(vec3(q.x,q.y*1.35,q.z))-s*1.08)*0.72; /* ellipsoid dome */
if(i==9) return min(sdBox3(q,vec3(s,h*0.55,s*0.38)), /* cross cathedral */
min(sdBox3(q,vec3(s*0.38,h*0.55,s)),
sdBox3(q,vec3(s*0.45,h,s*0.45))));
if(i==10){float a=atan(q.z,q.x); /* gear */
float rr=s*(0.88+0.11*cos(a*n*2.0));
return max(length(q.xz)-rr,abs(q.y)-h)*0.68;}
/* 11 = wheel: torus + hub + four spokes, all walkable */
float tor=length(vec2(length(q.xz)-s*0.72,q.y))-s*0.40;
float hub=length(q)-s*0.40;
float sp=min(min(sdSeg(q,vec3(0.),vec3(s*0.72,0.,0.)),
sdSeg(q,vec3(0.),vec3(-s*0.72,0.,0.))),
min(sdSeg(q,vec3(0.),vec3(0.,0.,s*0.72)),
sdSeg(q,vec3(0.),vec3(0.,0.,-s*0.72))))-s*0.17;
return min(tor,min(hub,sp));
}
float roomSD(vec3 p,int r){
vec3 q=p-roomPos[r];
float tw=roomMod[r].x;
if(abs(tw)>0.0005) q.xz=rot2(q.xz,q.y*tw);
float d=shapeSD(q,roomPar[r].x,roomPar[r].y,roomPar[r].z,roomPar[r].w);
float ra=roomMod[r].y;
if(ra>0.001) d+=ra*sin(q.x*roomMod[r].z)*sin(q.y*roomMod[r].z)*sin(q.z*roomMod[r].z);
return d/(1.0+abs(tw)*roomPar[r].y*0.6+ra*roomMod[r].z); /* Lipschitz guard */
}
float worldSD(vec3 p){
float d=min(roomSD(p,0),min(roomSD(p,1),roomSD(p,2)));
d=min(d,sdSeg(p,roomPos[0],roomPos[1])-1.7);
d=min(d,sdSeg(p,roomPos[1],roomPos[2])-1.7);
return d;}
int nearestRoom(vec3 p){
float d0=roomSD(p,0),d1=roomSD(p,1),d2=roomSD(p,2);
return d0<d1?(d0<d2?0:2):(d1<d2?1:2);}
vec3 wallNormal(vec3 p){ /* inward-facing */
const vec2 e=vec2(0.02,-0.02);
return -normalize(
e.xyy*worldSD(p+e.xyy)+e.yyx*worldSD(p+e.yyx)+
e.yxy*worldSD(p+e.yxy)+e.xxx*worldSD(p+e.xxx));}
/* ---------- moons: the same twelve shapes, shrunk and rounded into glass.
core-scale, height-scale and rounding radius per shape, from const tables —
this keeps the shader small enough for slow driver compilers ---------- */
const float CS[12]=float[12](0.50,1.00,0.60,0.765,0.613,0.52,0.644,0.590,0.740,0.600,0.568,0.55);
const float CH[12]=float[12](0.50,1.00,0.34,0.180,0.613,0.42,0.545,0.590,0.740,0.470,0.280,0.55);
const float CR[12]=float[12](0.26,0.00,0.22,0.16,0.24,0.20,0.00,0.18,0.06,0.14,0.12,0.10);
float moonSD(vec3 p,int k){
vec3 q=p-wells[k].xyz;
float s=wells[k].w;
float bs=length(q)-s*2.2;
if(bs>0.6) return bs;
q.xz=rot2(q.xz,wellPar[k].y);
q.xy=rot2(q.xy,wellPar[k].z);
int i=int(wellPar[k].x+0.5);
return shapeSD(q,wellPar[k].x,s*CS[i],s*CH[i],wellPar[k].w)-s*CR[i];
}
vec3 moonNormal(vec3 p,int k){
const vec2 e=vec2(0.012,-0.012);
return normalize(
e.xyy*moonSD(p+e.xyy,k)+e.yyx*moonSD(p+e.yyx,k)+
e.yxy*moonSD(p+e.yxy,k)+e.xxx*moonSD(p+e.xxx,k));}
/* ---------- boundary images ---------- */
vec3 eqSample(vec3 n){
float u=0.5+atan(n.z,n.x)*0.159155;
float v=0.5-asin(clamp(n.y,-1.0,1.0))*0.318310;
return texture(camTex,vec2(1.0-u,v)).rgb;}
vec3 wallImg(vec3 p){
int r=nearestRoom(p);
return eqSample(normalize(p-roomPos[r]))*roomTintU[r];}
void main(){
vec2 uv0=(gl_FragCoord.xy-0.5*iRes)/iRes.y;
vec3 x=camP;
vec3 rd=normalize(uv0.x*camR+uv0.y*camU+1.5*camF);
vec3 glow=vec3(0.0), tint=vec3(1.0), accum=vec3(0.0), col=vec3(0.0);
float trav=0.0, stp=0.05;
int bnc=0; bool done=false;
const int MAXB=12;
/* the amber thread lives only in the corridors, not in the rooms */
vec3 gA0=mix(roomPos[0],roomPos[1],0.28), gB0=mix(roomPos[0],roomPos[1],0.72);
vec3 gA1=mix(roomPos[1],roomPos[2],0.28), gB1=mix(roomPos[1],roomPos[2],0.72);
for(int i=0;i<180;i++){
/* lensing: deflection per path length, dtheta ~ gradPhi * ds */
if(lensK>0.001){
vec3 pull=vec3(0.0);
for(int k=0;k<nWell;k++){
vec3 dv=wells[k].xyz-x; float r2=dot(dv,dv)+0.4;
pull+=dv*inversesqrt(r2)*(wells[k].w*mGain/r2); }
rd=normalize(rd+pull*stp*0.055*lensK);
}
float dm=1e9; int hb=-1;
for(int k=0;k<nWell;k++){
float sd=moonSD(x,k);
float r=length(x-wells[k].xyz);
float e=wells[k].w*mGain/(r+1.0);
glow+=wellCol[k]*e*e*0.03*stp;
if(k==keyWell) /* the key crystal breathes gold */
glow+=vec3(1.0,0.80,0.30)*e*e*(0.05+0.045*sin(iTime*4.0))*stp;
if(sd<dm){dm=sd;hb=k;} }
float dw=-worldSD(x);
{
float dg=min(sdSeg(x,gA0,gB0),sdSeg(x,gA1,gB1));
glow+=vec3(0.91,0.69,0.23)*(0.010*stp/(dg*dg+0.15))*smoothstep(4.0,1.0,dg);
}
float dsl=1e9;
if(seal.w>0.0){
dsl=length(x-seal.xyz)-seal.w;
glow+=vec3(0.95,0.22,0.18)*(0.012*stp/(dsl*dsl+0.22))*smoothstep(6.0,1.5,dsl);
if(dsl<0.04){ /* the red membrane: sealed exit */
float pl=0.5+0.5*sin(iTime*3.0+x.y*2.2+x.x*1.3);
col=(vec3(0.72,0.10,0.09)+vec3(0.35,0.06,0.05)*pl)*tint;
done=true; break;
}
}
if(dm<0.03 && hb>=0){
vec3 n=moonNormal(x,hb);
float F=0.04+0.96*pow(1.0-max(dot(-rd,n),0.0),5.0); /* Schlick, glass F0 */
if(mode==1){ /* PROJECTION: moons carry the image (opaque) */
float L=0.0; for(int k=0;k<nWell;k++){
L+=wells[k].w*mGain/(length(x-wells[k].xyz)+1.0);}
col=tint*eqSample(n)*(0.55+0.7*min(L,1.4)); done=true; break;
}
/* BOUNDARY & CASCADE: heavy optical crystal.
Fresnel glints off the surface; the ray itself REFRACTS (Snell),
marches the negative-distance chord inside, exits the far side,
and keeps flying — you see the world warped through the glass. */
glow+=tint*eqSample(reflect(rd,n))*F*0.55; /* mirror glint, Fresnel-weighted */
if(mode==2) accum+=tint*eqSample(n)*F*1.1; /* cascade: crystal wears the face at the rims */
bnc++; if(bnc>MAXB){col=(mode==2)?accum:vec3(0.0);done=true;break;}
const float IOR=1.45;
vec3 d=refract(rd,n,1.0/IOR);
if(dot(d,d)<1e-4) d=reflect(rd,n); /* entry-grazing guard */
x-=n*0.04; /* step inside the glass */
float chord=0.0;
for(int j=0;j<26;j++){
float sd=moonSD(x,hb);
if(sd>-0.006){ /* reached the far surface */
vec3 ne=moonNormal(x,hb);
vec3 ro=refract(d,-ne,IOR);
if(dot(ro,ro)<1e-4){ d=reflect(d,-ne); x+=d*0.03; chord+=0.03; continue; } /* TIR: bounce inside */
d=ro; break; /* refract out */
}
float st=max(-sd*0.8,0.025);
x+=d*st; chord+=st;
}
/* Beer-Lambert: the crystal's colour tints what passes through, by chord length */
tint*=exp(-(vec3(1.0)-wellCol[hb])*chord*0.35)*0.96;
rd=d;
vec3 ne2=moonNormal(x,hb);
for(int j=0;j<10;j++){ if(moonSD(x,hb)>0.05)break; x+=ne2*0.05; }
x+=rd*0.04; trav+=chord+0.08; stp=0.05; continue;
}
if(dw<0.03){
if(mode==0){ /* BOUNDARY: walls are the image */
vec3 wc=wallImg(x);
float L=0.0; for(int k=0;k<nWell;k++){
L+=wells[k].w*mGain/(length(x-wells[k].xyz)+1.0);}
float fog=exp(-trav*0.010);
col=wc*tint*(0.30+1.1*min(L,1.6))*fog; done=true; break;
} else { /* PROJECTION / CASCADE: walls mirror */
vec3 n=wallNormal(x);
rd=reflect(rd,n); tint*=0.85; bnc++;
if(bnc>MAXB){ col=(mode==2)?accum:vec3(0.0); done=true; break; }
for(int j=0;j<10;j++){ if(-worldSD(x)>0.05)break; x+=n*0.05; }
x+=rd*0.04; stp=0.05; continue;
}
}
stp=clamp(min(min(dm,dw),dsl)*0.9,0.03,3.0);
x+=rd*stp; trav+=stp;
if(trav>260.0)break;
}
if(!done) col=(mode==2)?accum:vec3(0.0);
col+=glow;
col=col/(col+1.0);
col=pow(col,vec3(0.4545));
float vig=1.0-0.35*dot(uv0,uv0);
O=vec4(col*vig,1.0);
}`;
/* ---------------- boundary texture (webcam + fallback) ---------------- */
const vid=$('vid');
let camOK=false, useCam=true;
const camTex=gl.createTexture();
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D,camTex);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){
navigator.mediaDevices.getUserMedia({video:{width:640,height:480,facingMode:'user'}})
.then(st=>{vid.srcObject=st;vid.play();camOK=true;setSrcLabel();})
.catch(()=>{useCam=false;camOK=false;setSrcLabel();});
}else{useCam=false;setSrcLabel();}
const pat=document.createElement('canvas');pat.width=256;pat.height=256;
const pctx=pat.getContext('2d');
function drawPattern(t){
const g=pctx.createLinearGradient(0,0,0,256);
g.addColorStop(0,'#2a3550');g.addColorStop(1,'#6a4a70');
pctx.fillStyle=g;pctx.fillRect(0,0,256,256);
const cx=128+64*Math.cos(0.6*t),cy=128+48*Math.sin(0.9*t);
for(let s=0;s<24;s++){
pctx.fillStyle=s%2?'#d8c890':'#705838';
pctx.beginPath();pctx.arc(cx,cy,46-s*1.9,0,7);pctx.fill();
}
pctx.fillStyle='#101018';pctx.fillRect(176,56,40,40);
pctx.fillStyle='#c9d4e0';pctx.font='14px monospace';
pctx.fillText('no camera — pattern',56,240);
}
function setSrcLabel(){
$('src').textContent=useCam&&camOK?'webcam live':'test pattern';
$('bSrc').textContent=useCam?'Test pattern':'Use camera';
}
function uploadBoundary(t){
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D,camTex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);
if(useCam&&camOK&&vid.readyState>=2){
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,vid);
}else{
drawPattern(t);
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,pat);
}
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,false);
}
/* =====================================================================
THE PROCEDURAL BRAIN — now with LEVELS
Every chamber is a pure function of (SEED, index). Nothing is stored.
Level L is a run of depth(L) rooms. One room hides the KEY CRYSTAL
(moon 0, gold, pulsing). The far gate of the level is SEALED until
the key is touched. Room mass, twist, ripple and the shape pool all
deepen with the level. Save = 6 numbers. Everything else is hash.
===================================================================== */
let SEED=(Math.random()*4294967296)>>>0;
function rng(i,salt){
let t=(SEED ^ Math.imul(i|0,2654435761) ^ Math.imul(salt|0,40503))>>>0;
t=Math.imul(t^(t>>>15),t|1);
t^=t+Math.imul(t^(t>>>7),t|61);
return ((t^(t>>>14))>>>0)/4294967296;
}
const SHAPENAMES=['CUBE','SPHERE','HEX PRISM','STAR','OCTAHEDRON','CYLINDER',
'CAPSULE VAULT','CUT CRYSTAL','DOME','CROSS CATHEDRAL','GEAR','WHEEL'];
const SYL=['KA','RA','JA','PIN','TA','VUO','LU','MI','SA','TÄH','TI','KI','VI','HEL','ME','NU','SO','LO'];
/* ------- level geometry: depth(L) rooms per level, cumulative starts ------- */
function depthOf(L){return Math.min(3+L,10);} /* L1: 4 rooms … caps at 10 */
function levelStartOf(L){let s=0;for(let k=1;k<L;k++)s+=depthOf(k);return s;}
function levelOfRoom(i){
if(i<0)return 1; /* the ante-brain: level 1 rules */
let L=1,s=0;
while(s+depthOf(L)<=i){s+=depthOf(L);L++;}
return L;
}
function rngL(L,salt){return rng(0x5EED+Math.imul(L,131),7000+salt);}
function keyRoomOf(L){const d=depthOf(L);
return levelStartOf(L)+1+Math.floor(rngL(L,1)*(d-1));}
function exitRoomOf(L){return levelStartOf(L)+depthOf(L)-1;}
function nMoonsOf(L){return Math.min(3+((L-1)>>1),5);}
function roomDef(i){
const L=levelOfRoom(i);
const pool=Math.min(6+Math.max(L-1,0),12); /* shapes unlock with depth */
const shape=Math.floor(rng(i,1)*pool);
const size=7.0+rng(i,2)*4.0+Math.min(L*0.15,3.0);
const height=4.5+rng(i,3)*2.5;
const starN=5+Math.floor(rng(i,4)*3); /* 5, 6 or 7 points */
const hue=rng(i,5);
const turn=(rng(i,6)-0.5)*2.4; /* gate heading vs. entry, +-69 deg */
const twist=(rng(i,8)-0.5)*2.0*Math.min(0.015+L*0.011,0.13);
const ripA=Math.min(Math.max(L-2,0)*0.06,0.45)*rng(i,9);
const ripF=0.5+rng(i,10)*1.2;
const massK=Math.min(0.7+rng(i,11)*0.9+L*0.04,2.8);
let name='';const nc=2+Math.floor(rng(i,7)*2);
for(let k=0;k<nc;k++)name+=SYL[Math.floor(rng(i,20+k)*SYL.length)];
const tint=[0.86+0.14*Math.cos(6.283*hue),
0.86+0.14*Math.cos(6.283*(hue+0.33)),
0.86+0.14*Math.cos(6.283*(hue+0.66))];
return {shape,size,height,starN,hue,turn,name,tint,twist,ripA,ripF,massK,level:L};
}
function moonDef(i,m){ /* moon m of room i — re-dreamed identically every visit */
const s=100+m*13;
const mass=-Math.log(1e-6+rng(i,s+1));
return {mass,
fx:0.05+rng(i,s+2)*0.20, fy:0.05+rng(i,s+3)*0.20, fz:0.05+rng(i,s+4)*0.20,
px:rng(i,s+5)*6.283, py:rng(i,s+6)*6.283, pz:rng(i,s+7)*6.283,
ax:0.28+rng(i,s+8)*0.22, ay:0.25+rng(i,s+9)*0.22, az:0.28+rng(i,s+10)*0.22,
ra:(rng(i,s+11)-0.5)*1.2, rb:(rng(i,s+12)-0.5)*1.2,
pa:rng(i,s+13)*6.283, pb:rng(i,s+14)*6.283,
hue:rng(i,s+15)};
}
/* ------- game state ------- */
let LEVEL=1, keyFound=false, maxReached=1;
let CI=0, dirIn=[Math.sin(rng(0,99)*6.283),Math.cos(rng(0,99)*6.283)];
let R={}; /* the three live rooms: def, center, index */
function rotXZ(v,a){const c=Math.cos(a),s=Math.sin(a);return [c*v[0]-s*v[1],s*v[0]+c*v[1]];}
function computeDirIn(N){ /* dirIn is a pure function of SEED and N */
let d=[Math.sin(rng(0,99)*6.283),Math.cos(rng(0,99)*6.283)];
if(N>0){for(let j=0;j<N;j++)d=rotXZ(d,roomDef(j).turn);}
else if(N<0){for(let j=-1;j>=N;j--)d=rotXZ(d,-roomDef(j).turn);}
return d;
}
function rebuildChain(){
const dPrev=roomDef(CI-1), dCur=roomDef(CI), dNext=roomDef(CI+1);
const dirOut=rotXZ(dirIn,dCur.turn);
const Dn=dCur.size+dNext.size+12.0, Dp=dPrev.size+dCur.size+12.0;
R={
idx:[CI-1,CI,CI+1],
def:[dPrev,dCur,dNext],
pos:[[-dirIn[0]*Dp,0,-dirIn[1]*Dp],[0,0,0],[dirOut[0]*Dn,0,dirOut[1]*Dn]],
dirOut
};
$('roomV').textContent=dCur.name;
$('roomI').textContent='#'+CI+' · '+(dCur.shape===3?'STAR-'+dCur.starN:SHAPENAMES[dCur.shape]);
$('massV').textContent=dCur.massK.toFixed(2)+' · '+(dCur.twist>=0?'+':'')+dCur.twist.toFixed(3);
updateLevelHud();
}
function banner(a,b){
$('bn1').textContent=a;$('bn2').textContent=b||'';
const el=$('banner');el.classList.add('show');
clearTimeout(banner.t);banner.t=setTimeout(()=>el.classList.remove('show'),2600);
}
function updateLevelHud(){
$('lvlV').textContent=LEVEL;
const rIn=CI-levelStartOf(LEVEL);
$('progV').textContent=(CI<0?'—':(rIn+1)+' / '+depthOf(LEVEL));
$('keyV').textContent=keyFound?'found — seal open':'not found';
$('keyV').className=keyFound?'keyok':'keyno';
}
function onRoomChanged(){
const newL=levelOfRoom(CI);
if(newL>LEVEL){
LEVEL=newL;
keyFound=(LEVEL+1<=maxReached); /* re-visiting a beaten level? seal stays open */
if(LEVEL>maxReached){maxReached=LEVEL;keyFound=false;
banner('LEVEL '+LEVEL,depthOf(LEVEL)+' rooms · find the gold crystal');
autoSave();}
}else if(newL<LEVEL){
LEVEL=newL;
keyFound=(LEVEL+1<=maxReached); /* walked back: that seal was already opened */
}
updateLevelHud();
}
function advance(){ /* stepped through the forward gate */
const shift=R.pos[2];
camP=[camP[0]-shift[0],camP[1]-shift[1],camP[2]-shift[2]];
dirIn=R.dirOut; CI++; rebuildChain(); onRoomChanged();
}
function retreat(){ /* stepped back — re-dream the past */
const shift=R.pos[0];
camP=[camP[0]-shift[0],camP[1]-shift[1],camP[2]-shift[2]];
const dPrev=roomDef(CI-1);
dirIn=rotXZ(dirIn,-dPrev.turn); CI--; rebuildChain(); onRoomChanged();
}
/* ---------------- JS twins of the SDFs (collision + transitions) ---------- */
function sdBoxJ(px,py,pz,bx,by,bz){
const qx=Math.abs(px)-bx,qy=Math.abs(py)-by,qz=Math.abs(pz)-bz;
return Math.hypot(Math.max(qx,0),Math.max(qy,0),Math.max(qz,0))
+Math.min(Math.max(qx,Math.max(qy,qz)),0);}
function sdHexJ(px,py,pz,h1,h2){
const kx=-0.8660254,ky=0.5,kz=0.57735;
px=Math.abs(px);py=Math.abs(py);pz=Math.abs(pz);
const d0=Math.min(kx*px+ky*py,0)*2;
px-=d0*kx;py-=d0*ky;
const cl=Math.min(Math.max(px,-kz*h1),kz*h1);
const dx=Math.hypot(px-cl,py-h1)*Math.sign(py-h1);
const dy=pz-h2;
return Math.min(Math.max(dx,dy),0)+Math.hypot(Math.max(dx,0),Math.max(dy,0));}
function sdStarNJ(px,py,r,n,m){
const an=Math.PI/n,en=Math.PI/m;
const ax=Math.cos(an),ay=Math.sin(an),ex=Math.cos(en),ey=Math.sin(en);
let bn=Math.atan2(px,py)%(2*an); if(bn<0)bn+=2*an; bn-=an;
const l=Math.hypot(px,py);
px=l*Math.cos(bn); py=l*Math.abs(Math.sin(bn));
px-=r*ax; py-=r*ay;
const cl=Math.min(Math.max(-(px*ex+py*ey),0),r*ay/ey);
px+=ex*cl; py+=ey*cl;
return Math.hypot(px,py)*Math.sign(px);}
function opExtrJ(d2,z,h){const wy=Math.abs(z)-h;
return Math.min(Math.max(d2,wy),0)+Math.hypot(Math.max(d2,0),Math.max(wy,0));}
function sdSegJ(px,py,pz,a,b){
const bax=b[0]-a[0],bay=b[1]-a[1],baz=b[2]-a[2];
const pax=px-a[0],pay=py-a[1],paz=pz-a[2];
const h=Math.min(Math.max((pax*bax+pay*bay+paz*baz)/(bax*bax+bay*bay+baz*baz),0),1);
return Math.hypot(pax-bax*h,pay-bay*h,paz-baz*h);}
function sdSegOJ(px,py,pz,ax,ay,az,bx,by,bz){
const bax=bx-ax,bay=by-ay,baz=bz-az;
const pax=px-ax,pay=py-ay,paz=pz-az;
const h=Math.min(Math.max((pax*bax+pay*bay+paz*baz)/(bax*bax+bay*bay+baz*baz),0),1);
return Math.hypot(pax-bax*h,pay-bay*h,paz-baz*h);}
function shapeSDJ(x,y,z,d){
const s=d.size,h=d.height;
switch(d.shape){
case 0:return sdBoxJ(x,y,z,s,h,s);
case 1:return Math.hypot(x,y,z)-s;
case 2:return sdHexJ(x,z,y,s,h);
case 3:{const m=2.0+(d.starN-2.0)*0.45;
return opExtrJ(sdStarNJ(x,z,s*1.15,d.starN,m),y,h);}
case 4:return (Math.abs(x)+Math.abs(y)+Math.abs(z)-s*1.5)*0.57735;
case 5:return Math.max(Math.hypot(x,z)-s,Math.abs(y)-h);
case 6:{const cy=y-Math.min(Math.max(y,-h*0.55),h*0.55);
return Math.hypot(x,cy,z)-s*0.90;}
case 7:return Math.max(sdBoxJ(x,y,z,s*0.95,s*0.95,s*0.95),
(Math.abs(x)+Math.abs(y)+Math.abs(z)-s*1.45)*0.57735);
case 8:return (Math.hypot(x,y*1.35,z)-s*1.08)*0.72;
case 9:return Math.min(sdBoxJ(x,y,z,s,h*0.55,s*0.38),
Math.min(sdBoxJ(x,y,z,s*0.38,h*0.55,s),
sdBoxJ(x,y,z,s*0.45,h,s*0.45)));
case 10:{const a=Math.atan2(z,x);
const rr=s*(0.88+0.11*Math.cos(a*d.starN*2.0));
return Math.max(Math.hypot(x,z)-rr,Math.abs(y)-h)*0.68;}
default:{const tor=Math.hypot(Math.hypot(x,z)-s*0.72,y)-s*0.40;
const hub=Math.hypot(x,y,z)-s*0.40;
let sp=Math.min(sdSegOJ(x,y,z,0,0,0,s*0.72,0,0),
sdSegOJ(x,y,z,0,0,0,-s*0.72,0,0));
sp=Math.min(sp,Math.min(sdSegOJ(x,y,z,0,0,0,0,0,s*0.72),
sdSegOJ(x,y,z,0,0,0,0,0,-s*0.72)))-s*0.17;
return Math.min(tor,Math.min(hub,sp));}
}
}
function roomSDJ(px,py,pz,r){
const d=R.def[r],c=R.pos[r];
let x=px-c[0],y=py-c[1],z=pz-c[2];
if(Math.abs(d.twist)>0.0005){
const ca=Math.cos(y*d.twist),sa=Math.sin(y*d.twist);
const nx=ca*x-sa*z, nz=sa*x+ca*z; x=nx; z=nz;
}
let sd=shapeSDJ(x,y,z,d);
if(d.ripA>0.001)
sd+=d.ripA*Math.sin(x*d.ripF)*Math.sin(y*d.ripF)*Math.sin(z*d.ripF);
return sd/(1.0+Math.abs(d.twist)*d.size*0.6+d.ripA*d.ripF);
}
function worldSDJ(px,py,pz){
let d=Math.min(roomSDJ(px,py,pz,0),Math.min(roomSDJ(px,py,pz,1),roomSDJ(px,py,pz,2)));
d=Math.min(d,sdSegJ(px,py,pz,R.pos[0],R.pos[1])-1.7);
d=Math.min(d,sdSegJ(px,py,pz,R.pos[1],R.pos[2])-1.7);
return d;}
/* ---------------- moons + key + seal upload ---------------- */
let P={mGain:1.0,lensK:1.0},mode=0,idle=1;
const wellsF=new Float32Array(MAXW*4), colsF=new Float32Array(MAXW*3),
parF=new Float32Array(MAXW*4),
roomPosF=new Float32Array(9), roomParF=new Float32Array(12),
roomModF=new Float32Array(12), roomTintF=new Float32Array(9);
function moonCol(h){
return[0.55+0.45*Math.cos(6.283*h),0.55+0.45*Math.cos(6.283*(h+0.33)),0.55+0.45*Math.cos(6.283*(h+0.66))];}
let keyWell=-1, keyPos=null, keyR=0;
let sealV=[0,0,0,-1];
function packWorld(t){
let w=0; keyWell=-1; keyPos=null;
const nM=nMoonsOf(LEVEL), kRoom=keyRoomOf(LEVEL);
for(let r=0;r<3;r++){
const d=R.def[r],c=R.pos[r];
roomPosF[r*3]=c[0];roomPosF[r*3+1]=c[1];roomPosF[r*3+2]=c[2];
roomParF[r*4]=d.shape;roomParF[r*4+1]=d.size;roomParF[r*4+2]=d.height;roomParF[r*4+3]=d.starN;
roomModF[r*4]=d.twist;roomModF[r*4+1]=d.ripA;roomModF[r*4+2]=d.ripF;roomModF[r*4+3]=d.massK;
roomTintF[r*3]=d.tint[0];roomTintF[r*3+1]=d.tint[1];roomTintF[r*3+2]=d.tint[2];
const A=d.size*0.62, Ay=d.height*0.55;
for(let m=0;m<nM && w<MAXW;m++,w++){
const md=moonDef(R.idx[r],m);
const isKey=(!keyFound && R.idx[r]===kRoom && m===0);
let size=(0.45+(md.mass/3.0)*0.75)*P.mGain*d.massK;
size=Math.min(size,1.6); if(isKey)size=Math.min(size*1.25,1.8);
/* the key swings wide, off the walking line — you must go to it */
const ax=isKey?Math.min(md.ax*1.6,0.55):md.ax,
ay=isKey?Math.min(md.ay*1.5,0.50):md.ay,
az=isKey?Math.min(md.az*1.6,0.55):md.az;
wellsF[w*4+0]=c[0]+A*ax*Math.sin(md.fx*t+md.px);
wellsF[w*4+1]=c[1]+Ay*ay*Math.sin(md.fy*t+md.py);
wellsF[w*4+2]=c[2]+A*az*Math.sin(md.fz*t+md.pz);
wellsF[w*4+3]=size;
const cc=isKey?[1.0,0.84,0.36]:moonCol(md.hue);
colsF[w*3]=cc[0];colsF[w*3+1]=cc[1];colsF[w*3+2]=cc[2];
parF[w*4]=d.shape;parF[w*4+1]=md.ra*t+md.pa;parF[w*4+2]=md.rb*t+md.pb;parF[w*4+3]=d.starN;
if(isKey){keyWell=w;keyPos=[wellsF[w*4],wellsF[w*4+1],wellsF[w*4+2]];keyR=size;}
}
}
/* the seal: a red membrane in the corridor after the level's last room */
const eRoom=exitRoomOf(LEVEL);
if(!keyFound && CI===eRoom){
sealV=[(R.pos[1][0]+R.pos[2][0])*0.5,(R.pos[1][1]+R.pos[2][1])*0.5,
(R.pos[1][2]+R.pos[2][2])*0.5,2.6];
}else sealV=[0,0,0,-1];
return w;
}
/* ---------------- camera & input (mouse INVERTED, as requested) ------------ */
let camP=[0,0,0], yaw=0, pitch=0;
function faceForwardGate(){yaw=Math.atan2(R.dirOut[0],R.dirOut[1]);pitch=0;}
rebuildChain();faceForwardGate();
const keys={};
addEventListener('keydown',e=>{keys[e.code]=1;
if(['KeyW','KeyA','KeyS','KeyD','KeyQ','KeyE'].includes(e.code))e.preventDefault();});
addEventListener('keyup',e=>{keys[e.code]=0;});
let dragging=false,lx=0,ly=0;
cvs.addEventListener('pointerdown',e=>{dragging=true;lx=e.clientX;ly=e.clientY;
cvs.classList.add('drag');cvs.setPointerCapture(e.pointerId);
boot.classList.add('gone');startMusic();});
cvs.addEventListener('pointerup',()=>{dragging=false;cvs.classList.remove('drag');});
cvs.addEventListener('pointermove',e=>{
if(!dragging)return;
yaw+=(e.clientX-lx)*0.0032;pitch-=(e.clientY-ly)*0.0032; /* horiz inverted · vert natural */
pitch=Math.max(-1.5,Math.min(1.5,pitch));
lx=e.clientX;ly=e.clientY;
});
boot.addEventListener('click',()=>{boot.classList.add('gone');startMusic();});
function insideVal(px,py,pz){
let v=-worldSDJ(px,py,pz);
if(sealV[3]>0)
v=Math.min(v,Math.hypot(px-sealV[0],py-sealV[1],pz-sealV[2])-sealV[3]);
return v;
}
function tryMove(nx,ny,nz){
if(insideVal(nx,ny,nz)>0.35){camP=[nx,ny,nz];return;}
if(insideVal(nx,camP[1],camP[2])>0.35)camP[0]=nx;
if(insideVal(camP[0],ny,camP[2])>0.35)camP[1]=ny;
if(insideVal(camP[0],camP[1],nz)>0.35)camP[2]=nz;
}
/* ---------------- music: game1..4.mp3 next to this file, endless ---------- */
const TRACKS=['game1.mp3','game2.mp3','game3.mp3','game4.mp3','game5.mp3',
'game6.mp3','game7.mp3','game8.mp3','game9.mp3','game10.mp3'];
let musicOn=true, musicStarted=false, mIdx=Math.floor(Math.random()*TRACKS.length), mFails=0;
const audio=(typeof Audio!=='undefined')?new Audio():null;
if(audio){
audio.preload='auto'; audio.volume=0.5;
audio.addEventListener('ended',()=>{mFails=0;playTrack(mIdx+1);});
audio.addEventListener('error',()=>{
if(++mFails<TRACKS.length)playTrack(mIdx+1);
else $('musV').textContent='no mp3s found';
});
audio.addEventListener('playing',()=>{mFails=0;$('musV').textContent=TRACKS[mIdx];});
}
function playTrack(i){
if(!audio||!musicOn)return;
mIdx=((i%TRACKS.length)+TRACKS.length)%TRACKS.length;
audio.src=TRACKS[mIdx];
audio.play().catch(()=>{/* autoplay policy: waits for a click */});
}
function startMusic(){
if(musicStarted||!musicOn||!audio)return;
musicStarted=true; playTrack(mIdx);
}
$('bMus').onclick=e=>{
musicOn=!musicOn;
e.target.classList.toggle('on',musicOn);
e.target.textContent='Music: '+(musicOn?'on':'off');
if(!audio)return;
if(musicOn){musicStarted=false;startMusic();}
else {audio.pause();$('musV').textContent='off';}
};
$('musV').textContent='starts on first click';
/* ---------------- save / load ----------------
the whole game is 6 numbers. everything else is the hash. */
function saveObj(){return {v:1,s:SEED,l:LEVEL,c:CI,k:keyFound?1:0,m:maxReached};}
function saveCode(){return btoa(JSON.stringify(saveObj()));}
function applySave(o){
if(!o||o.v!==1||typeof o.s!=='number')throw new Error('bad save');
SEED=o.s>>>0; LEVEL=Math.max(1,o.l|0); CI=o.c|0;
keyFound=!!o.k; maxReached=Math.max(LEVEL,o.m|0);
dirIn=computeDirIn(CI); camP=[0,0,0];
rebuildChain(); faceForwardGate(); updateLevelHud();
}
function autoSave(){
try{localStorage.setItem('brainDescentSave',saveCode());}catch(e){/* fine: file:// or sandbox */}
}
$('bSave').onclick=()=>{
autoSave();
$('stat').textContent='saved · level '+LEVEL+' room #'+CI+' (Save code gives a portable copy)';
};
$('bCode').onclick=()=>{
const c=saveCode();
$('stat').textContent='code: '+c;
if(navigator.clipboard)navigator.clipboard.writeText(c).catch(()=>{});
};
$('bLoad').onclick=()=>{
let code='';
try{code=localStorage.getItem('brainDescentSave')||'';}catch(e){}
const inp=prompt('Paste a save code (leave as-is to load the local save):',code);
if(inp===null)return;
try{applySave(JSON.parse(atob(inp.trim())));
$('stat').textContent='loaded · level '+LEVEL+' room #'+CI+' · seed '+SEED.toString(16);
banner('LEVEL '+LEVEL,'re-dreamed from the hash');
}catch(e){$('stat').textContent='could not read that save code';}
};
/* ---------------- controls ---------------- */
const MODES=[
{name:'Boundary', note:'the walls are your camera. the moons are optical crystals — the room bends and refocuses through every one of them.'},
{name:'Projection', note:'the moons carry your face; every wall is a mirror. the image emanates from the bulk — the holographic swap.'},
{name:'Cascade', note:'heavy glass: Fresnel rims wear your face, the ray refracts through and keeps going, tinted by each crystal it crosses.'},
];
function setMode(mi){
mode=mi;
['m0','m1','m2'].forEach((id,i)=>$(id).classList.toggle('on',i===mi));
$('modeV').textContent=MODES[mi].name;
$('modeNote').textContent=MODES[mi].note;
}
setMode(0);
function bind(id,lab,fn){const el=$(id);el.addEventListener('input',()=>{fn(parseFloat(el.value));$(lab).textContent=el.value;});}
bind('m','m_l',v=>{P.mGain=v;});
bind('g','g_l',v=>{P.lensK=v;});
bind('v','v_l',v=>{if(audio)audio.volume=v;});
$('m0').onclick=()=>setMode(0);
$('m1').onclick=()=>setMode(1);
$('m2').onclick=()=>setMode(2);
$('bSrc').onclick=()=>{useCam=!useCam;setSrcLabel();};
$('bSeed').onclick=()=>{ SEED=(Math.random()*4294967296)>>>0;
LEVEL=1;maxReached=1;keyFound=false;CI=0;
dirIn=[Math.sin(rng(0,99)*6.283),Math.cos(rng(0,99)*6.283)];
camP=[0,0,0]; rebuildChain(); faceForwardGate(); updateLevelHud();
banner('LEVEL 1','a new brain · seed '+SEED.toString(16));
$('stat').textContent='new brain · seed '+SEED.toString(16); };
$('bIdle').onclick=e=>{idle^=1;e.target.classList.toggle('on',!!idle);
e.target.textContent='Idle spin: '+(idle?'on':'off');};
if(matchMedia('(prefers-reduced-motion: reduce)').matches){
idle=0;$('bIdle').classList.remove('on');$('bIdle').textContent='Idle spin: off';
}
/* try to resume a local autosave silently */
try{const c=localStorage.getItem('brainDescentSave');
if(c){applySave(JSON.parse(atob(c)));
$('stat').textContent='resumed · level '+LEVEL+' room #'+CI;}
}catch(e){/* fresh brain */}
updateLevelHud();
/* ---------------- resize ---------------- */
function resize(){
const dpr=Math.min(devicePixelRatio||1,1.35);
cvs.width=Math.floor(innerWidth*dpr);
cvs.height=Math.floor(innerHeight*dpr);
gl.viewport(0,0,cvs.width,cvs.height);
}
addEventListener('resize',resize);resize();
/* ---------------- resonance: hot / cold toward the key ---------------- */
function updateResonance(){
if(keyFound){$('resT').textContent='key held';$('resFill').style.width='100%';return;}
const kRoom=keyRoomOf(LEVEL);
let res,txt;
if(keyPos){
const d=Math.hypot(camP[0]-keyPos[0],camP[1]-keyPos[1],camP[2]-keyPos[2]);
res=Math.max(0.35,Math.min(1,1-(d-2)/42));
txt='very close — '+d.toFixed(0)+' m';
}else{
const away=kRoom-CI;
res=Math.max(0.04,0.34/(1+Math.abs(away)));
txt=Math.abs(away)+' room'+(Math.abs(away)===1?'':'s')+(away>0?' ahead':' behind');
}
$('resT').textContent=txt;
$('resFill').style.width=(res*100).toFixed(0)+'%';
}
/* ---------------- shader compile: DEFERRED so the boot screen paints first,
PARALLEL where the driver allows it, and any failure shows its log -------- */
let prog=null,U={};
function sh(type,src){const s=gl.createShader(type);gl.shaderSource(s,src);
gl.compileShader(s);return s;}
function compileAndStart(){
const vs=sh(gl.VERTEX_SHADER,VERT), fs=sh(gl.FRAGMENT_SHADER,FRAG);
prog=gl.createProgram();
gl.attachShader(prog,vs);gl.attachShader(prog,fs);
gl.linkProgram(prog);
const ext=gl.getExtension('KHR_parallel_shader_compile');
function finish(){
if(!gl.getProgramParameter(prog,gl.LINK_STATUS)){
const log=(gl.getShaderInfoLog(fs)||'')+' '+(gl.getShaderInfoLog(vs)||'')
+' '+(gl.getProgramInfoLog(prog)||'');
bootErr('Shader failed: '+log.trim());
return;
}
gl.useProgram(prog);
['iRes','iTime','camP','camR','camU','camF','nWell','mode','keyWell','mGain','lensK','camTex',
'wells','wellCol','wellPar','roomPos','roomPar','roomMod','roomTintU','seal']
.forEach(k=>U[k]=gl.getUniformLocation(prog,k));
gl.uniform1i(U.camTex,0);
$('bootStat').textContent='ready — click to enter';
requestAnimationFrame(loop);
}
if(ext){
(function poll(){
if(gl.getProgramParameter(prog,ext.COMPLETION_STATUS_KHR))finish();
else requestAnimationFrame(poll);
})();
}else finish();
}
/* ---------------- loop ---------------- */
let t0=performance.now(),simT=0,frames=0,fpsT=t0;
function loop(now){
const dt=Math.min((now-t0)/1000,0.05);t0=now;
if(idle)simT+=dt; else simT+=dt*0.06;
const cp=Math.cos(pitch),sp=Math.sin(pitch),cy=Math.cos(yaw),sy=Math.sin(yaw);
const F=[sy*cp,sp,cy*cp], Rv=[cy,0,-sy], Uv=[-sy*sp,cp,-cy*sp];
const spd=(keys.ShiftLeft||keys.ShiftRight?14:6)*dt;
let mx=0,my=0,mz=0;
if(keys.KeyW){mx+=F[0]*spd;my+=F[1]*spd;mz+=F[2]*spd;}
if(keys.KeyS){mx-=F[0]*spd;my-=F[1]*spd;mz-=F[2]*spd;}
if(keys.KeyD){mx+=Rv[0]*spd;mz+=Rv[2]*spd;}
if(keys.KeyA){mx-=Rv[0]*spd;mz-=Rv[2]*spd;}
if(keys.KeyE)my+=spd;
if(keys.KeyQ)my-=spd;
if(mx||my||mz)tryMove(camP[0]+mx,camP[1]+my,camP[2]+mz);
/* room transition: deep inside next -> dream forward; inside prev -> re-dream back */
if(roomSDJ(camP[0],camP[1],camP[2],2)<-1.0)advance();
else if(roomSDJ(camP[0],camP[1],camP[2],0)<-1.0)retreat();
uploadBoundary(simT);
const nW=packWorld(simT);
/* key pickup: touch the gold crystal */
if(!keyFound && keyPos){
const d=Math.hypot(camP[0]-keyPos[0],camP[1]-keyPos[1],camP[2]-keyPos[2]);
if(d<keyR+1.0){
keyFound=true; keyWell=-1; sealV=[0,0,0,-1];
banner('KEY CRYSTAL','the seal dissolves — find the far gate');
updateLevelHud(); autoSave();
}
}
gl.useProgram(prog);
gl.uniform2f(U.iRes,cvs.width,cvs.height);
gl.uniform1f(U.iTime,simT);
gl.uniform3f(U.camP,camP[0],camP[1],camP[2]);
gl.uniform3f(U.camR,Rv[0],Rv[1],Rv[2]);
gl.uniform3f(U.camU,Uv[0],Uv[1],Uv[2]);
gl.uniform3f(U.camF,F[0],F[1],F[2]);
gl.uniform1i(U.nWell,nW);
gl.uniform1i(U.mode,mode);
gl.uniform1i(U.keyWell,keyWell);
gl.uniform1f(U.mGain,P.mGain);
gl.uniform1f(U.lensK,P.lensK);
gl.uniform4fv(U.wells,wellsF);
gl.uniform3fv(U.wellCol,colsF);
gl.uniform4fv(U.wellPar,parF);
gl.uniform3fv(U.roomPos,roomPosF);
gl.uniform4fv(U.roomPar,roomParF);
gl.uniform4fv(U.roomMod,roomModF);
gl.uniform3fv(U.roomTintU,roomTintF);
gl.uniform4f(U.seal,sealV[0],sealV[1],sealV[2],sealV[3]);
gl.drawArrays(gl.TRIANGLES,0,3);
frames++;
if(now-fpsT>400){
$('fps').textContent=Math.round(frames*1000/(now-fpsT))+' fps';
frames=0;fpsT=now;
$('pos').textContent=camP.map(v=>v.toFixed(1)).join(', ');
updateResonance();
}
requestAnimationFrame(loop);
}
/* let the boot screen paint before the driver chews on the shader */
$('bootStat').textContent='dreaming the shader…';
requestAnimationFrame(()=>{try{compileAndStart();}catch(e){bootErr(e&&e.stack||e);}});
</script>
|