Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
executable file
·1015 lines (849 loc) · 34.8 KB
/
Copy pathmain.js
File metadata and controls
executable file
·1015 lines (849 loc) · 34.8 KB
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
996
997
998
999
1000
// =============================================
// FULL FIXED main.js (copy-paste replace)
// =============================================
import GUI from "https://cdn.skypack.dev/lil-gui@0.18.0";
import { PointerLockControls } from "./PointerLockControls.js";
import { EffectComposer } from 'https://cdn.skypack.dev/three@0.149.0/examples/jsm/postprocessing/EffectComposer';
import { RenderPass } from 'https://cdn.skypack.dev/three@0.149.0/examples/jsm/postprocessing/RenderPass';
import { ShaderPass } from 'https://cdn.skypack.dev/three@0.149.0/examples/jsm/postprocessing/ShaderPass';
import { RGBShiftShader } from './shader/RGBShiftShader.js';
import { StaticShader } from './shader/StaticShader.js';
import Stats from 'https://cdn.skypack.dev/stats.js';
import { VignetteShader } from './shader/VignetteShader.js';
import * as THREE from 'https://unpkg.com/three@0.149.0/build/three.module.js';
import { OBJLoader } from 'https://unpkg.com/three@0.149.0/examples/jsm/loaders/OBJLoader.js';
// ============== CONFIG ==============
const MAZE_SIZE = 10; // width = height
const MAZE_DEPTH = 7; // W layers (0-6)
let currentW = 0;
let tolerance = MAZE_SIZE; // generation distance
let acceleration = 0.15;
const damping = 0.9;
var stats = new Stats();
let jumpProgress = 0; // 0 → 1
let isJumping = false;
const jumpDuration = 0.6; // seconds
const jumpHeight = .25;
const startPos = new THREE.Vector3();
let showAllLayers = false;
const allLayerMaterials = [];
//
let audioCtx = null;
let droneOsc, buzzOsc, noiseSource, noiseGain, noiseFilter;
let masterGain, lowpassFilter, distortionNode, delayNode, feedbackGain;
let glitchPhase = 0; // For timed glitches
let lastDistUpdate = 0; // Throttle distortion curve updates
//
let wpps = [
"./public/wallpaper0.png", // yellow backroom
"./public/wallpaper1.png", // grey backroom
"./public/wallpaper3.png", // concrete
"./public/wallpaper4.png", // brick
"./public/wallpaper5.png", // construction metal with alpha
"./public/wallpaper6.png", // geoskeleton
"./public/wallpaper7.png" // literal nothing / placeholder image
];
let texts = [
"exit to the left.\n NOT THIS LEFT ",
"what? where i am?",
"feed the cat \n - dad",
"-bread\n-milk\n-cheese\n-... have i forgot something?",
"come back yesterday for a bonus",
"console.log('bug is here!');",
"...",
"(empty)"
];
const layerConfigs = {
0: {
wpp: wpps[0],
fog: 0xd9a336,
light: 0xfeffd9,
transparent: false
},
1: {
wpp: wpps[1],
fog: 0xe8e4ca,
light: 0xeeeeee,
transparent: false
},
2: {
wpp: wpps[2],
fog: 0x777777,
light: 0x777777,
transparent: true
},
3: {
wpp: wpps[3],
fog: 0x662211,
light: 0x662211,
transparent: true
},
4: {
wpp: wpps[4],
fog: 0x000000,
light: 0x000000,
transparent: true
},
5: {
wpp: wpps[5],
fog: 0x000000,
light: 0x000000,
transparent: true
},
6: {
wpp: wpps[6],
fog: 0x000000,
light: 0x000000,
transparent: true
}
};
let current_wpp = wpps[0];
stats.showPanel(0);
document.body.appendChild( stats.dom );
const coordinates = document.getElementById('coordinates');
// ============== THREE SETUP ==============
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, MAZE_SIZE + 10);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio * 0.5);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const textureLoader = new THREE.TextureLoader();
// Post-processing (kept exactly as you wanted)
const renderTarget = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight);
const composer = new EffectComposer(renderer, renderTarget);
composer.addPass(new RenderPass(scene, camera));
const staticPass = new ShaderPass(StaticShader);
staticPass.uniforms.amount.value = 0.04;
staticPass.uniforms.size.value = 4.0;
composer.addPass(staticPass);
const rgbShift = new ShaderPass(RGBShiftShader);
rgbShift.uniforms.amount.value = 0.001;
rgbShift.renderToScreen = true;
composer.addPass(rgbShift);
const vignette = new ShaderPass(VignetteShader);
vignette.uniforms.offset.value = 0.81;
vignette.uniforms.darkness.value = 1.0;
vignette.renderToScreen = true;
composer.addPass(vignette);
// Lights & fog
scene.add(new THREE.AmbientLight(0xe8e4ca, 0.7));
const dirLight = new THREE.DirectionalLight(0xfeffd9, 0.9);
dirLight.position.set(0, 10, 0);
scene.add(dirLight);
scene.fog = new THREE.FogExp2(0xd9a336, 0.17);
renderer.setClearColor(0xd9a336);
function loadTexture(path, options = {}) {
const texture = textureLoader.load(path, function (texture) {
texture.generateMipmaps = options.generateMipmaps || true;
texture.minFilter = options.minFilter || THREE.LinearMipmapLinearFilter;
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(options.repeatX || 1, options.repeatY || 1);
if (options.anisotropy) texture.anisotropy = options.anisotropy;
if (options.offset) texture.offset.set(options.offset.x, options.offset.y);
});
return texture;
}
// ============== TEXTURES ==============
const wallTex = loadTexture(current_wpp, { repeatX: 9, repeatY: 3, offset: {x: Math.random(), y: Math.random()} }); //textureLoader.load('./public/wallpaper.png');
//wallTex.wrapS = wallTex.wrapT = THREE.RepeatWrapping;
const floorTex = loadTexture('./public/floor.png', { repeatX: 60, repeatY: 60 }); //textureLoader.load('./public/floor.png');
//floorTex.wrapS = floorTex.wrapT = THREE.RepeatWrapping;
//floorTex.repeat.set(60, 60);
const baseboardTex = loadTexture('./public/baseboard.jpg', { repeatX: 20, repeatY: 20, anisotropy: 16 });
const floorBump = loadTexture('./public/heightmap.png', { repeatX: 60, repeatY: 60 }); //textureLoader.load('./public/heightmap.png');
//floorBump.wrapS = floorBump.wrapT = THREE.RepeatWrapping;
const ceilTex = loadTexture('./public/ceiling_tile.jpg', { repeatX: 60, repeatY: 40, minFilter: THREE.LinearMipmapLinearFilter }); //textureLoader.load('./public/ceiling_tile.jpg');
//ceilTex.wrapS = ceilTex.wrapT = THREE.RepeatWrapping;
const ceilBump = loadTexture('./public/ceiling_tile_heightmap.png', { repeatX: 60, repeatY: 40, minFilter: THREE.LinearMipmapLinearFilter }); //textureLoader.load('./public/ceiling_tile_heightmap.png');
// ============== GEOMETRIES ==============
const wallGeo = new THREE.BoxGeometry(1.0001, 1, 1.0001);
const wallMat = new THREE.MeshPhongMaterial({
map: wallTex ,
transparent: true, // Allows transparency
alphaTest: 0.5, // Prevents "invisible" walls from blocking the view of things behind them
side: THREE.DoubleSide
});
for (let i = 0; i < MAZE_DEPTH; i++) {
const mat = wallMat.clone();
mat.transparent = true;
mat.opacity = 0.18 + i * 0.1;
mat.color.setHSL(i / MAZE_DEPTH, 0.6, 0.55);
allLayerMaterials.push(mat);
}
const floorGeo = new THREE.PlaneGeometry(MAZE_SIZE, MAZE_SIZE);
const floorMat = new THREE.MeshPhongMaterial({
map: floorTex,
bumpMap: floorBump,
bumpScale: 0.005,
shininess: 0,
reflectivity: 0,
roughness: 1,
receiveShadow: true,
color: 0x777777,
metalness: 0
});
const ceilGeo = new THREE.PlaneGeometry(MAZE_SIZE, MAZE_SIZE);
const ceilMat = new THREE.MeshPhongMaterial({
map: ceilTex,
bumpMap: ceilBump,
bumpScale: 0.0015,
shininess: 0,
reflectivity: 0,
roughness: 1,
receiveShadow: true,
color: 0x777777
});
const baseboardGeo = new THREE.BoxGeometry(1.01, 0.065, 1.01);
const baseboardMat = new THREE.MeshPhongMaterial({ map: baseboardTex, reflectivity: 0, shininess: 0, roughness: 1 });
const lightGeo = new THREE.BoxGeometry(0.15, 0.01, 0.15);
const lightMat = new THREE.MeshBasicMaterial({ color: 0xfeffe8 });
const outlineGeo = new THREE.BoxGeometry(0.17, 0.01, 0.17);
const outlineMat = new THREE.MeshBasicMaterial({ color: 0x333333 });
// ============== POINTER LOCK ==============
const controls = new PointerLockControls(camera, renderer.domElement);
scene.add(controls.getObject());
const startBtn = document.getElementById('startButton');
const menu = document.getElementById('menuPanel');
// function togAu()[
//
// ]
let timeGlitch = 0;
startBtn.addEventListener('click', () => {
initAudio();
if (!timeGlitch){
timeGlitch = 1;
startTime();
}
controls.lock();
});
controls.addEventListener('lock', () => {
startBtn.style.display = 'none';
menu.style.display = 'none';
paused = false;
});
controls.addEventListener('unlock', () => {
startBtn.style.display = 'block';
menu.style.display = 'block';
paused = true;
});
// ============== GUI ==============
const gui = new GUI();
const gfx = gui.addFolder("Graphics");
const guiData = { pixelratio: 50, genDist: MAZE_SIZE };
gfx.add(guiData, "pixelratio", 20, 100, 5).onChange(v => {
renderer.setPixelRatio(window.devicePixelRatio * v / 100);
}).name("Pixel Ratio (%)");
gfx.add(guiData, "genDist", 1, MAZE_SIZE, 1).onChange(v => tolerance = v).name("Generation Distance");
gfx.close();
// ============== MAZE DATA ==============
const worldData = new Map(); // chunkKey → 3D maze array [W][Y][X]
const visited = new Set(); // "x,z"
const chunkObjects = new Map();
function findSafeSpawn(maze) {
// 1. Scan all W layers (dimensions)
for (let w = 0; w < MAZE_DEPTH; w++) {
// 2. Scan rows and columns
// We start at 1 and end at SIZE-1 to avoid boundary walls
for (let y = 1; y < MAZE_SIZE /*- 1*/; y++) {
for (let x = 1; x < MAZE_SIZE /*- 1*/; x++) {
if (maze[w][y][x] === 0) {
return {
x: (x - MAZE_SIZE / 2 + 0.5),
z: (y - MAZE_SIZE / 2 + 0.5),
w: w // Return which dimension we found the space in
};
}
}
}
}
// Final fallback if the maze is somehow 100% solid
return { x: 0.5, z: 0.5, w: 0 };
}
let timeRate = 0;
function startTime() {
const today = new Date();
today.setSeconds(today.getSeconds()+((currentW+1)*timeRate/8));
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
timer.innerHTML = String(Math.round(h)).padStart(2, '0') + ":" + String(Math.round(m)).padStart(2, '0') + ":" + String(Math.round(s)).padStart(2, '0') + " }";
timeRate += 0.1;
setTimeout(startTime, 1000);
}
// until next empty comment total vibecodes
function createNoiseBuffer() {
const bufferSize = audioCtx.sampleRate * 2;
const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = Math.random() * 2 - 1;
}
return buffer;
}
// Distortion curve (from Web Audio tutorials)
function makeDistortionCurve(amount) {
const k = typeof amount === 'number' ? amount : 50;
const nSamples = 256;
const curve = new Float32Array(nSamples);
const deg = Math.PI / 180;
for (let i = 0; i < nSamples; ++i) {
const x = (i * 2) / nSamples - 1;
curve[i] = ((3 + k) * x * 20 * deg) / (Math.PI + k * Math.abs(x));
}
return curve;
}
// Initialize audio on user gesture (call this in your "Click to Start" handler)
function initAudio() {
if (audioCtx) return;
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// Master gain
masterGain = audioCtx.createGain();
masterGain.gain.value = 0.2;
masterGain.connect(audioCtx.destination);
// Lowpass filter for muffled Backrooms vibe
lowpassFilter = audioCtx.createBiquadFilter();
lowpassFilter.type = 'lowpass';
lowpassFilter.frequency.value = 350;
lowpassFilter.Q.value = 0.5;
// Distortion for glitches
distortionNode = audioCtx.createWaveShaper();
distortionNode.curve = makeDistortionCurve(0); // Start clean
// Delay for endless echo/reverb
delayNode = audioCtx.createDelay(0.5);
delayNode.delayTime.value = 0.25;
feedbackGain = audioCtx.createGain();
feedbackGain.gain.value = 0.35;
// Chain: filters -> distortion -> delay -> master
lowpassFilter.connect(distortionNode);
distortionNode.connect(delayNode);
delayNode.connect(feedbackGain);
feedbackGain.connect(delayNode); // Feedback loop
delayNode.connect(masterGain);
// Main drone osc (deep hum ~35-50Hz)
droneOsc = audioCtx.createOscillator();
droneOsc.type = 'sine';
droneOsc.frequency.value = 40;
const droneGain = audioCtx.createGain();
droneGain.gain.value = 0.15;
droneOsc.connect(droneGain);
droneGain.connect(lowpassFilter);
// Buzz osc (fluorescent light ~100-150Hz harmonic)
buzzOsc = audioCtx.createOscillator();
buzzOsc.type = 'square';
buzzOsc.frequency.value = 120;
const buzzGain = audioCtx.createGain();
buzzGain.gain.value = 0.08;
buzzOsc.connect(buzzGain);
buzzGain.connect(lowpassFilter);
// Noise for static/glitches (bandpassed whoosh)
noiseFilter = audioCtx.createBiquadFilter();
noiseFilter.type = 'bandpass';
noiseFilter.frequency.value = 800;
noiseFilter.Q.value = 2;
noiseGain = audioCtx.createGain();
noiseGain.gain.value = 0;
const noiseBuffer = createNoiseBuffer();
noiseSource = audioCtx.createBufferSource();
noiseSource.buffer = noiseBuffer;
noiseSource.loop = true;
noiseSource.connect(noiseFilter);
noiseFilter.connect(noiseGain);
noiseGain.connect(lowpassFilter);
// Start all sources
droneOsc.start();
buzzOsc.start();
noiseSource.start();
console.log('Backrooms audio initialized - no-clipping into the hum...');
}
// Update audio every frame (call in your animate(now) function)
function updateAudio() {
if (!audioCtx) return;
const now = audioCtx.currentTime;
glitchPhase += 0.016; // ~60fps increment
// Pitch shift like broken time: accelerates with timeRate, layers modulate base
const layerMod = (currentW + 1) * 0.03; // Higher layers = weirder pitch
const timePitch = 1 + (timeRate * 0.008);
const droneFreq = (38 + Math.sin(currentW * 1.618) * 4) * timePitch; // Procedural per wallpaper/layer
const buzzFreq = droneFreq * 3;
droneOsc.frequency.setValueAtTime(droneFreq, now);
buzzOsc.frequency.setValueAtTime(buzzFreq, now);
// Distortion ramps up with timeRate (update throttled)
const distAmount = Math.min(timeRate * 0.8, 80);
if (Date.now() - lastDistUpdate > 100) { // 10Hz update
distortionNode.curve = makeDistortionCurve(distAmount);
lastDistUpdate = Date.now();
}
// Lowpass cutoff: tightens/muffles as time breaks, opens per layer
lowpassFilter.frequency.setTargetAtTime(250 + timeRate * 1.5 + currentW * 30, now, 0.03);
// Feedback echo intensifies per layer (wallpaper "endlessness")
feedbackGain.gain.setTargetAtTime(0.2 + (currentW % 4) * 0.15, now, 0.05);
// Ambient noise level + slow LFO "breathing" hum
const lfo = 0.5 + 0.5 * Math.sin(glitchPhase * 0.1);
noiseGain.gain.setTargetAtTime((timeRate * 0.0008) * lfo, now, 0.02);
// Glitch bursts: more frequent/chaotic with timeRate, tied to layer
// const glitchProb = 0.003 + (timeRate * 0.00015) + (currentW * 0.0005);
// if (Math.random() < glitchProb) {
// // Noise burst
// noiseGain.gain.setTargetAtTime(0.25, now, 0.01);
// noiseGain.gain.setTargetAtTime(timeRate * 0.0008, now + 0.3, 0.1);
//
// // Pitch glitch (time jump echo)
// const glitchPitch = droneFreq * (1.5 + Math.random());
// droneOsc.frequency.setValueAtTime(glitchPitch, now);
// droneOsc.frequency.exponentialRampToValueAtTime(droneFreq, now + 0.4);
//
// // Delay time stutter
// delayNode.delayTime.setTargetAtTime(0.1 + Math.random() * 0.3, now, 0.01);
// delayNode.delayTime.setTargetAtTime(0.25, now + 0.2, 0.05);
// }
// Master volume LFO for subtle pulsing isolation feel
masterGain.gain.setTargetAtTime(0.18 + 0.04 * Math.sin(now * 0.05), now, 0.1);
}
//
function generateMaze() {
// Initialize the 3D array (Depth x Height x Width)
const maze = Array.from({ length: MAZE_DEPTH }, () =>
Array.from({ length: MAZE_SIZE }, () => Array(MAZE_SIZE).fill(1))
);
// Loop through each layer (w) independently
for (let w = 0; w < MAZE_DEPTH; w++) {
// Pick a random starting point for THIS specific layer
const startX = Math.floor(Math.random() * (MAZE_SIZE / 2)) * 2 + 1;
const startY = Math.floor(Math.random() * (MAZE_SIZE / 2)) * 2 + 1;
const frontier = [[startX, startY]];
maze[w][startY][startX] = 0;
while (frontier.length > 0) {
// Pick a random spot from the frontier
const idx = Math.floor(Math.random() * frontier.length);
const [x, y] = frontier.splice(idx, 1)[0];
// 2D Directions only (North, South, East, West)
const dirs = [[-2, 0], [2, 0], [0, -2], [0, 2]];
dirs.sort(() => Math.random() - 0.5);
for (const [dx, dy] of dirs) {
const nx = x + dx;
const ny = y + dy;
// Check 2D bounds
if (nx > 0 && nx < MAZE_SIZE - 1 && ny > 0 && ny < MAZE_SIZE - 1) {
if (maze[w][ny][nx] === 1) {
// Carve the destination cell
maze[w][ny][nx] = 0;
// Carve the "wall" between the current cell and the new cell
const bridgeX = x + dx / 2;
const bridgeY = y + dy / 2;
maze[w][bridgeY][bridgeX] = 0;
frontier.push([nx, ny]);
}
}
}
}
// Apply your specific "Master-style" door/edge logic for this layer
for (let i = 0; i < MAZE_SIZE; i++) {
maze[w][i][MAZE_SIZE - 1] = 0; // East edge open
maze[w][MAZE_SIZE - 1][i] = 0; // South edge open
}
}
return maze;
}
// ============== RENDER FUNCTIONS ==============
// Add 'parent' as the last argument to all these functions
function generateWalls(maze, cx, cz, layer, parent) {
const inst = new THREE.InstancedMesh(wallGeo, wallMat, MAZE_SIZE * MAZE_SIZE);
const baseboardInst = new THREE.InstancedMesh(baseboardGeo, baseboardMat, MAZE_SIZE * MAZE_SIZE);
const dummy = new THREE.Object3D();
let count = 0;
for (let y = 0; y < MAZE_SIZE; y++) {
for (let x = 0; x < MAZE_SIZE; x++) {
if (maze[layer][y][x] === 1) {
const px = (x - MAZE_SIZE/2 + 0.5) + cx * MAZE_SIZE;
const pz = (y - MAZE_SIZE/2 + 0.5) + cz * MAZE_SIZE;
dummy.position.set(px, 0.5, pz);
dummy.updateMatrix();
inst.setMatrixAt(count, dummy.matrix);
dummy.position.set(px, 0.0325, pz);
dummy.updateMatrix();
baseboardInst.setMatrixAt(count, dummy.matrix);
count++;
}
}
}
inst.count = count;
baseboardInst.count = count;
parent.add(inst); // Added to parent group
parent.add(baseboardInst);
}
function createLights(maze, cx, cz, layer, parent) {
for (let y = 0; y < MAZE_SIZE; y += 2) {
for (let x = 0; x < MAZE_SIZE; x += 2) {
const lx = (x - MAZE_SIZE/2) + (cx * MAZE_SIZE);
const lz = (y - MAZE_SIZE/2) + (cz * MAZE_SIZE);
const light = new THREE.Mesh(lightGeo, lightMat);
light.position.set(lx, 0.99, lz);
parent.add(light);
const outline = new THREE.Mesh(outlineGeo, outlineMat);
outline.position.set(lx, 0.999, lz);
parent.add(outline);
}
}
}
function createFloor(cx, cz, parent) {
const f = new THREE.Mesh(floorGeo, floorMat);
f.rotation.x = -Math.PI/2;
f.position.set(cx * MAZE_SIZE, 0, cz * MAZE_SIZE);
parent.add(f);
}
function createCeiling(cx, cz, parent) {
const c = new THREE.Mesh(ceilGeo, ceilMat);
c.rotation.x = Math.PI/2;
c.position.set(cx * MAZE_SIZE, 1, cz * MAZE_SIZE);
parent.add(c);
}
function refreshAllVisuals() {
const config = layerConfigs[currentW] || layerConfigs[0];
if (wallMat.map) wallMat.map.dispose();
// 1. Update the Wall Texture
// We load the new texture and swap it on the existing material
textureLoader.load(config.wpp, (tex) => {
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
tex.repeat.set(9, 3); // Keep your repeat settings
wallMat.map = tex;
wallMat.transparent = config.transparent;
wallMat.needsUpdate = true;
});
// 2. Update Scene Colors
const newColor = new THREE.Color(config.fog);
scene.fog.color = newColor;
renderer.setClearColor(newColor);
dirLight.color = new THREE.Color(config.light);
// 3. Clear all existing chunk groups from the scene
for (const key of chunkObjects.keys()) {
unloadChunk(key); // ← use the fixed version above
// const group = chunkObjects.get(key);
// scene.remove(group);
}
chunkObjects.clear();
// 4. Just let updateChunks rebuild them for the new currentW
updateChunks();
}
function toggleAllLayers() {
showAllLayers = !showAllLayers;
// Force full rebuild
for (const key of Array.from(chunkObjects.keys())) {
unloadChunk(key);
}
chunkObjects.clear();
updateChunks();
// Optional: visual feedback in coordinates
// console.log(`%cAll Layers Mode: ${showAllLayers ? 'ON' : 'OFF'}`, `color: ${showAllLayers ? '#0f0' : '#f80'}; font-weight: bold`);
}
function jumpTo(targetPos) {
startPos.copy(camera.position);
endPos.copy(targetPos);
jumpProgress = 0;
isJumping = true;
}
// ============== COLLISION ==============
function checkCollision(oldPos) {
const pos = controls.getObject().position;
const radius = 0.22;
const checks = [
{ x: pos.x + radius, z: pos.z + radius },
{ x: pos.x - radius, z: pos.z + radius },
{ x: pos.x + radius, z: pos.z - radius },
{ x: pos.x - radius, z: pos.z - radius }
];
for (let point of checks) {
const cx = Math.floor((point.x + MAZE_SIZE/2) / MAZE_SIZE);
const cz = Math.floor((point.z + MAZE_SIZE/2) / MAZE_SIZE);
const key = `${cx},${cz}`;
const maze = worldData.get(key);
if (!maze) continue;
const localX = Math.floor((point.x - cx * MAZE_SIZE) + MAZE_SIZE / 2);
const localZ = Math.floor((point.z - cz * MAZE_SIZE) + MAZE_SIZE / 2);
if (showAllLayers) {
// In all-layers mode we check ALL layers
for (let w = 0; w < MAZE_DEPTH; w++) {
if (maze[w] && maze[w][localZ] && maze[w][localZ][localX] === 1) {
controls.getObject().position.copy(oldPos);
velocity.set(0, 0, 0);
return;
}
}
} else {
// Normal mode - only check current layer
if (maze[currentW] && maze[currentW][localZ] && maze[currentW][localZ][localX] === 1) {
controls.getObject().position.copy(oldPos);
velocity.set(0, 0, 0);
return;
}
}
}
}
// ================ CAT =================
const loader = new OBJLoader();
let pet; // The pet (cat) model
// loader.load('public/kotek_redo.obj', (gltf) => {
// pet = gltf; // The pet model is now a part of the scene
//
// pet.scale.setScalar(0.02);
// pet.position.set(0, -0.5, 1); // Position relative to the player
// pet.traverse(child => {
// if (child.isMesh) {
// const mat = child.material.clone();
// mat.transparent = true;
// mat.side = THREE.DoubleSide; // ← fixes disappearing parts
// mat.depthWrite = false; // ← fixes wall/voxel explosion & sorting
// mat.alphaTest = 0.15; // ← discards super-transparent pixels (makes it look solid again)
// mat.opacity = 0.72; // ← tames the "back too bright" problem (tune 0.6–0.85)
//
// child.material = mat;
// child.castShadow = true;
// child.receiveShadow = true;
// }
// });
//
// scene.add(pet); // Add the pet to the scene
// });
loader.load('public/kotek_redo.obj', (gltf) => {
pet = gltf;
pet.scale.setScalar(0.025);
pet.position.set(0, -0.5, -1.0); // slight offset so tail doesn't clip camera
pet.traverse((child) => {
if (child.isMesh) {
const mat = child.material.clone();
mat.vertexColors = true; // important — uses your VEC4 RGBA
mat.transparent = true;
mat.opacity = 0.8; // let per-vertex alpha do the work (Goxel's 0.9 is already baked)
mat.side = THREE.FrontSide; // ← THIS HIDES THE LEG & FIXES TAIL SHAPE
mat.depthWrite = true; // now safe because we discard faint pixels
mat.alphaTest = 0.28; // ← magic number: discards internal faint voxels
mat.blending = THREE.NormalBlending;
// Prevent washed/glowing backs (vertex colors were too bright)
mat.color.multiplyScalar(0.82); // slight darken to match Goxel saturation
mat.emissive.set(0x000000);
mat.shininess = 0;
mat.metalness = 0;
mat.roughness = 1;
child.material = mat;
child.castShadow = false;
child.receiveShadow = false;
}
});
pet.renderOrder = 5; // renders after walls but before post-effects
scene.add(pet);
});
function updatePetPosition() {
if (pet) {
// Get the position of the player (camera or object)
const playerPosition = controls.getObject().position;
// Set the pet's position relative to the player: slightly behind and below
pet.position.lerp(new THREE.Vector3(playerPosition.x-0.5, 0.0, playerPosition.z - 0.5),0.1);
}
}
// ============== CHUNK GENERATION ==============
function unloadChunk(key) {
const group = chunkObjects.get(key);
if (group) {
scene.remove(group);
// Important: Dispose of geometries and materials to save memory
group.traverse((child) => {
if (child.isInstancedMesh) {
child.dispose();
}
});
chunkObjects.delete(key);
worldData.delete(key);
visited.delete(key);
}
}
function generateChunk(cx, cz) {
const key = `${cx},${cz}`;
if (chunkObjects.has(key)) return;
if (!worldData.has(key)) {
worldData.set(key, generateMaze());
visited.add(key);
}
const maze = worldData.get(key);
const group = new THREE.Group();
group.userData.isMazeVisual = true;
scene.add(group);
chunkObjects.set(key, group);
if (showAllLayers) {
// ==================== ALL LAYERS MODE ====================
for (let layer = 0; layer < MAZE_DEPTH; layer++) {
const layerGroup = new THREE.Group();
layerGroup.userData.layer = layer;
// Walls with per-layer material
generateWalls(maze, cx, cz, layer, layerGroup);
layerGroup.traverse((obj) => {
if (obj.isInstancedMesh) {
const mat = allLayerMaterials[layer] || wallMat;
obj.material = mat;
obj.material.needsUpdate = true;
}
});
// Add semi-transparent floor and ceiling for each layer too
const f = new THREE.Mesh(floorGeo, floorMat);
f.rotation.x = -Math.PI / 2;
f.position.set(cx * MAZE_SIZE, layer * 0.02, cz * MAZE_SIZE); // slight offset to prevent z-fighting
f.material = f.material.clone();
f.material.transparent = true;
f.material.opacity = 0.15;
layerGroup.add(f);
const c = new THREE.Mesh(ceilGeo, ceilMat);
c.rotation.x = Math.PI / 2;
c.position.set(cx * MAZE_SIZE, 1 + layer * 0.02, cz * MAZE_SIZE);
c.material = c.material.clone();
c.material.transparent = true;
c.material.opacity = 0.12;
layerGroup.add(c);
// Optional: add lights only on even layers to reduce clutter
if (layer % 2 === 0) {
createLights(maze, cx, cz, layer, layerGroup);
}
group.add(layerGroup);
}
} else {
// ==================== NORMAL SINGLE LAYER MODE ====================
generateWalls(maze, cx, cz, currentW, group);
createLights(maze, cx, cz, currentW, group);
createFloor(cx, cz, group);
createCeiling(cx, cz, group);
}
}
function updateChunks() {
const pos = controls.getObject().position;
const currentCx = Math.floor((pos.x + MAZE_SIZE / 2) / MAZE_SIZE);
const currentCz = Math.floor((pos.z + MAZE_SIZE / 2) / MAZE_SIZE);
// 1. Generate nearby chunks
for (let dx = -tolerance; dx <= tolerance; dx++) {
for (let dz = -tolerance; dz <= tolerance; dz++) {
generateChunk(currentCx + dx, currentCz + dz);
}
}
// 2. Unload far away chunks
for (const key of chunkObjects.keys()) {
const [cx, cz] = key.split(',').map(Number);
if (Math.abs(cx - currentCx) > tolerance || Math.abs(cz - currentCz) > tolerance) {
unloadChunk(key);
}
}
}
// ============== INPUT ==============
let paused = true;
const velocity = new THREE.Vector3();
const keyState = {
KeyW: false, KeyA: false, KeyS: false, KeyD: false,
KeyQ: false, KeyE: false, KeyI:false,
PageUp: false, PageDown: false,
Space: false
};
document.addEventListener('keydown', e => { if (!paused) keyState[e.key] = true; e.preventDefault();});
document.addEventListener('keyup', e => { if (!paused) keyState[e.key] = false; e.preventDefault();});
let wCooldown = 0;
// Select all radio buttons in the group
const radios = document.querySelectorAll('input[name="item_bar"]');
let currentIndex = 0; // Start from the first radio button
// Function to update the selected radio button
function updateRadioSelection() {
radios.forEach((radio, index) => {
radio.checked = index === currentIndex;
});
}
// Listen for the mousewheel event on the document
document.addEventListener('wheel', (e) => {
if (e.deltaY > 0) {
// Scroll down, move to next radio button
currentIndex = (currentIndex + 1) % radios.length;
} else {
// Scroll up, move to previous radio button
currentIndex = (currentIndex - 1 + radios.length) % radios.length;
}
updateRadioSelection();
});
// Initialize the radio selection
updateRadioSelection();
// ============== MAIN LOOP ==============
let lastTime = 0;
function animate(now = 0) {
requestAnimationFrame(animate);
stats.begin();
const dt = (now - lastTime) / 1000;
lastTime = now;
if (paused) {
composer.render();
return;
}
// W-dimension switch (Q/E or PageUp/Down)
if ((keyState.e || keyState.E || keyState.PageDown) && Date.now() > wCooldown) {
currentW = (currentW + 1) % MAZE_DEPTH;
refreshAllVisuals();
wCooldown = Date.now() + 250;
}
if ((keyState.q || keyState.Q || keyState.PageUp) && Date.now() > wCooldown) {
currentW = (currentW - 1 + MAZE_DEPTH) % MAZE_DEPTH;
refreshAllVisuals();
wCooldown = Date.now() + 250;
}
if ((keyState.i || keyState.I || keyState.CapsLock) && Date.now() > wCooldown) { // ← Change to whatever key you want
toggleAllLayers();
wCooldown = Date.now() + 250;
}
const base = controls.getObject().position.clone();
if (isJumping) {
jumpProgress += dt / jumpDuration;
if (jumpProgress >= 1) {
jumpProgress = 1;
isJumping = false;
}
const obj = controls.getObject();
const height = Math.sin(Math.PI * jumpProgress) * jumpHeight;
obj.position.y = startPos.y + height;
}
// movement
if (keyState.w || keyState.W || keyState.ArrowUp) velocity.z += acceleration*dt;
if (keyState.s || keyState.S || keyState.ArrowDown) velocity.z -= acceleration*dt;
if (keyState.a || keyState.A || keyState.ArrowLeft) velocity.x -= acceleration*dt;
if (keyState.d || keyState.D || keyState.ArrowRight) velocity.x += acceleration*dt;
updatePetPosition();
updateAudio(); //
coordinates.innerHTML = `( ${controls.getObject().position.x.toFixed(2)} ; ${controls.getObject().position.z.toFixed(2)} ; ${controls.getObject().position.y.toFixed(2)} ; ${showAllLayers?"∞":currentW} ; `;
velocity.multiplyScalar(Math.pow(damping, dt * 60));
const oldPos = controls.getObject().position.clone();
controls.moveForward(velocity.z);
controls.moveRight(velocity.x);
checkCollision(oldPos);
updateChunks();
// static noise
staticPass.uniforms.time.value = (now * 0.001)%1000;
composer.render();
stats.end();
}
window.addEventListener('keydown', (e) => {
if (e.code === 'Space' && !isJumping) {
isJumping = true;
jumpProgress = 0;
startPos.copy(camera.position);
}
});
// ============== INIT ==============
function init() {
// first chunk
const startMaze = generateMaze();
worldData.set("0,0", startMaze);
visited.add("0,0");
generateChunk(0,0)