-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNeolutionLayout.html
More file actions
948 lines (835 loc) · 29.6 KB
/
NeolutionLayout.html
File metadata and controls
948 lines (835 loc) · 29.6 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/>
<title>Neo-VECTR's Neolution — Neon Rhythm on a TRON grid (CPU-light Canvas2D)</title>
<style>
:root{--bg:#000;--hud:rgba(0,0,0,.42);--b:rgba(73,230,255,.18);--fg:rgba(220,240,255,.92)}
html,body{margin:0;height:100%;background:var(--bg);overflow:hidden}
canvas{position:fixed;inset:0;width:100vw;height:100vh;display:block}
#hud{position:fixed;left:12px;top:12px;z-index:5;font:12px/1.35 ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;color:var(--fg);background:var(--hud);border:1px solid var(--b);border-radius:14px;padding:10px 12px;backdrop-filter:blur(5px);max-width:min(900px,calc(100vw - 24px))}
#hud .row{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
#hud b{font-weight:900;letter-spacing:.2px}
#hud select,#hud button,#hud input[type=range]{background:rgba(9,7,18,.65);border:1px solid rgba(73,230,255,.18);color:rgba(234,230,255,.95);border-radius:10px;padding:4px 8px;font:inherit}
#hud button{cursor:pointer}
#hud .small{opacity:.9}
#hud #status{margin-top:8px;white-space:pre-wrap;opacity:.92}
#score{position:fixed;right:14px;top:10px;z-index:5;color:rgba(230,245,255,.92);font:12px/1.35 ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;text-align:right;text-shadow:0 0 12px rgba(120,240,255,.22)}
#filePick{display:inline-flex;gap:8px;align-items:center}
</style>
</head>
<body>
<canvas id="sim" aria-label="Neo-VECTR's Neolution rhythm grid"></canvas>
<div id="hud">
<div class="row" style="margin-bottom:6px"><b>Neo-VECTR's Neolution</b> — Neon Rhythm on a TRON grid (CPU-light Canvas2D)</div>
<div class="row">
<label class="small">Song
<select id="songSel">
<option value="SpeedDemon.wav" selected>Speed Demon (wav)</option>
<option value="Numb.wav">Numb (wav)</option>
<option value="LostSauce.mp3">LostSauce (mp3)</option>
<option value="Rize.mp3">Rize (mp3)</option>
</select>
</label>
<label class="small">Difficulty
<select id="diffSel">
<option value="0">0 - Beginner</option>
<option value="1" selected>1 - Easy</option>
<option value="2">2 - Normal</option>
<option value="3">3 - Hard</option>
<option value="4">4 - Expert</option>
</select>
</label>
<button id="btnStart">Start</button>
<button id="btnPause">Pause</button>
<button id="btnRestart">Restart</button>
<label class="small">Offset (ms)
<input id="offset" type="range" min="-250" max="250" value="0" step="1"/>
</label>
<span class="small" id="offsetLbl">0</span>
</div>
<div class="row" style="margin-top:6px">
<span id="filePick">
<input id="file" type="file" accept="audio/*"/>
<span class="small">(custom song)</span>
</span>
</div>
<div class="small" style="margin-top:6px">
Inputs: Arrow keys = neon arrows • WASD = neon symbols • Controller = D-pad (arrows) + PlayStation buttons (□ × ○ △)
<br/>Keys: <b>Space</b> start/stop • <b>Esc</b> reset • <b>H</b> toggle HUD
</div>
<div id="status"></div>
</div>
<div id="score"><div>Score <span id="scoreVal">0</span></div><div>Combo x<span id="comboVal">0</span></div></div>
<script>
(() => {
'use strict';
const canvas = document.getElementById('sim');
const ctx = canvas.getContext('2d', { alpha:false, desynchronized:true });
const ui = {
songSel: document.getElementById('songSel'),
diffSel: document.getElementById('diffSel'),
start: document.getElementById('btnStart'),
pause: document.getElementById('btnPause'),
restart: document.getElementById('btnRestart'),
file: document.getElementById('file'),
offset: document.getElementById('offset'),
offsetLbl: document.getElementById('offsetLbl'),
status: document.getElementById('status'),
scoreVal: document.getElementById('scoreVal'),
comboVal: document.getElementById('comboVal'),
hud: document.getElementById('hud')
};
// --- resize ---
function resize(){
const dpr = Math.max(1, window.devicePixelRatio || 1);
canvas.width = Math.max(320, Math.floor(innerWidth * dpr));
canvas.height = Math.max(180, Math.floor(innerHeight * dpr));
}
window.addEventListener('resize', resize);
resize();
// --- helpers ---
const clamp = (v,a,b) => Math.max(a, Math.min(b, v));
const lerp = (a,b,t) => a + (b-a)*t;
// --- input ---
const keys = new Set();
let hudVisible = true;
window.addEventListener('keydown', (e) => {
keys.add(e.code);
if (e.code === 'KeyH'){
hudVisible = !hudVisible;
ui.hud.style.display = hudVisible ? 'block' : 'none';
}
if (e.code === 'Space') toggleStartStop();
if (e.code === 'Escape') hardReset();
});
window.addEventListener('keyup', (e) => keys.delete(e.code));
// --- audio ---
let audioCtx = null;
let analyser = null;
let mediaSrc = null;
const audioEl = new Audio();
audioEl.preload = 'auto';
// crossOrigin can break file:// playback in some browsers; only set it on http(s).
try{
if (location && (location.protocol === 'http:' || location.protocol === 'https:')){
audioEl.crossOrigin = 'anonymous';
}
} catch(_){}
let waveform = new Uint8Array(1024);
function ensureAudioGraph(){
if (!audioCtx){
audioCtx = new (window.AudioContext || window.webkitAudioContext)({ latencyHint: 'interactive' });
}
if (!analyser){
analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
analyser.smoothingTimeConstant = 0.65;
}
if (!mediaSrc){
mediaSrc = audioCtx.createMediaElementSource(audioEl);
mediaSrc.connect(analyser);
analyser.connect(audioCtx.destination);
}
}
// Deterministic chart build from decoded audio when possible.
// We prefer decoding from File input (reliable). For dropdown songs under file://,
// browsers sometimes block fetch/decode; playback still works, but charting may fall back.
function fnv1a(str){
let h = 2166136261 >>> 0;
for (let i=0;i<str.length;i++){
h ^= str.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return h >>> 0;
}
function mulberry32(seed){
let t = seed >>> 0;
return function(){
t += 0x6D2B79F5;
let x = Math.imul(t ^ (t >>> 15), 1 | t);
x ^= x + Math.imul(x ^ (x >>> 7), 61 | x);
return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
};
}
async function decodeForChartFromFile(file){
const ab = await file.arrayBuffer();
ensureAudioGraph();
// decode in AudioContext (not Offline) for widest support
const buf = await audioCtx.decodeAudioData(ab.slice(0));
return buf;
}
// Cheap onset-like peak detection (time-domain energy + local maxima)
function buildPeaksFromBuffer(buf){
const ch = buf.getChannelData(0);
const sr = buf.sampleRate;
const win = 1024;
const hop = 512;
const energies = [];
for (let i=0;i+win<ch.length;i+=hop){
let e = 0;
for (let j=0;j<win;j++) e += Math.abs(ch[i+j]);
energies.push(e / win);
}
// adaptive threshold
let mean = 0;
for (const e of energies) mean += e;
mean /= Math.max(1, energies.length);
let thresh = mean * 1.35;
const peaks = [];
for (let i=2;i<energies.length-2;i++){
const e = energies[i];
if (e > thresh && e > energies[i-1] && e >= energies[i+1] && e > energies[i-2] && e >= energies[i+2]){
const t = (i * hop) / sr;
peaks.push({ t, e });
}
}
// If too few peaks (quiet track), drop threshold
if (peaks.length < 120){
thresh = mean * 1.15;
peaks.length = 0;
for (let i=2;i<energies.length-2;i++){
const e = energies[i];
if (e > thresh && e > energies[i-1] && e >= energies[i+1]){
const t = (i * hop) / sr;
peaks.push({ t, e });
}
}
}
return peaks;
}
// --- rhythm state ---
const LANES = 8;
// lane groups: 0..3 arrows, 4..7 symbols
const laneLabel = [
{ type:'arrow', code:'ArrowLeft', glyph:'←' },
{ type:'arrow', code:'ArrowDown', glyph:'↓' },
{ type:'arrow', code:'ArrowUp', glyph:'↑' },
{ type:'arrow', code:'ArrowRight',glyph:'→' },
{ type:'sym', code:'KeyA', glyph:'□' }, // square
{ type:'sym', code:'KeyS', glyph:'×' }, // cross
{ type:'sym', code:'KeyD', glyph:'○' }, // circle
{ type:'sym', code:'KeyW', glyph:'△' }, // triangle
];
// controller mapping (standard mapping; best-effort)
const padMap = {
arrows: { left: 14, down: 13, up: 12, right: 15 },
ps: { square: 2, cross: 0, circle: 1, triangle: 3 }
};
let songId = 'SpeedDemon.wav';
let songLabel = 'SpeedDemon.wav';
let customObjectUrl = null;
let playing = false;
let paused = false;
let chartReady = false;
let chartSeed = 123456;
let notes = []; // {t,lane,hit:false,miss:false}
let score = 0;
let combo = 0;
// hit feedback
let hitFlash = 0;
let missFlash = 0;
// difficulty params
const diffParams = [
{ name:'Beginner', keep:0.35, minGap:0.42, travel:2.6, hitWin:0.135 },
{ name:'Easy', keep:0.50, minGap:0.34, travel:2.45, hitWin:0.120 },
{ name:'Normal', keep:0.65, minGap:0.28, travel:2.30, hitWin:0.105 },
{ name:'Hard', keep:0.78, minGap:0.24, travel:2.15, hitWin:0.095 },
{ name:'Expert', keep:0.88, minGap:0.20, travel:2.00, hitWin:0.085 },
];
function currentDiff(){
return diffParams[clamp(parseInt(ui.diffSel.value,10)||1,0,4)];
}
let lastError = '';
function setStatus(msg){
ui.status.textContent = msg;
}
function setError(err){
lastError = err ? String(err) : '';
}
function updateScoreUI(){
ui.scoreVal.textContent = String(score);
ui.comboVal.textContent = String(combo);
}
// --- chart building ---
function buildDeterministicChart(peaks, durationSec, seedStr){
const d = currentDiff();
const seed = fnv1a(seedStr);
chartSeed = seed;
const rng = mulberry32(seed);
// Filter peaks by spacing and difficulty keep ratio
const kept = [];
let lastT = -999;
for (const p of peaks){
if ((p.t - lastT) < d.minGap) continue;
if (rng() > d.keep) continue;
kept.push(p.t);
lastT = p.t;
}
// If decoding gave too few peaks, fall back to a fixed grid (still deterministic)
if (kept.length < 80){
kept.length = 0;
const step = lerp(0.55, 0.22, (parseInt(ui.diffSel.value,10)||1) / 4);
for (let t=1.0; t<durationSec-1.0; t += step){
if (rng() < 0.85) kept.push(t);
}
}
// Lane selection: keep it readable; alternate groups
const out = [];
let mode = 0;
for (const t of kept){
const swing = rng();
if (swing > 0.82) mode = 1-mode;
const base = mode===0 ? 0 : 4;
const lane = base + Math.floor(rng()*4);
out.push({ t, lane, hit:false, miss:false });
// occasional chord on higher diffs
if (parseInt(ui.diffSel.value,10) >= 3 && rng() < 0.14){
let lane2 = base + Math.floor(rng()*4);
if (lane2 === lane) lane2 = base + ((lane2+1)%4);
out.push({ t, lane: lane2, hit:false, miss:false });
}
}
// Sort & return
out.sort((a,b)=>a.t-b.t || a.lane-b.lane);
return out;
}
async function rebuildChartUsingDecodeIfPossible(sourceLabel, fromFile){
chartReady = false;
setStatus('building chart...');
try{
let buf = null;
if (fromFile){
buf = await decodeForChartFromFile(fromFile);
} else {
// Try fetch+decode for dropdown songs. This may fail under file://.
ensureAudioGraph();
const res = await fetch(sourceLabel);
const ab = await res.arrayBuffer();
buf = await audioCtx.decodeAudioData(ab.slice(0));
}
const peaks = buildPeaksFromBuffer(buf);
notes = buildDeterministicChart(peaks, buf.duration, sourceLabel + '|' + buf.length + '|' + buf.sampleRate);
chartReady = true;
setStatus(`chart ready: ${notes.length} notes | ${currentDiff().name}\n(If timing feels off, adjust Offset.)`);
} catch (err){
// Fallback: deterministic, duration-based.
const dur = isFinite(audioEl.duration) ? audioEl.duration : 180;
const seedStr = sourceLabel + '|' + String(dur.toFixed(3));
const pseudoPeaks = [];
const rng = mulberry32(fnv1a(seedStr));
// pseudo-peaks (not sound-based, but stable)
const step = lerp(0.52, 0.20, (parseInt(ui.diffSel.value,10)||1) / 4);
for (let t=1.0; t<dur-1.0; t += step){
if (rng() < 0.92) pseudoPeaks.push({ t, e: 1 });
}
notes = buildDeterministicChart(pseudoPeaks, dur, seedStr);
chartReady = true;
setStatus(
'audio analysis blocked (likely file://).\n' +
'Playback is fine, chart is deterministic fallback.\n' +
'For true soundwave charting: use Choose File OR run a local server.\n' +
`notes: ${notes.length}`
);
console.warn('Chart decode failed:', err);
}
}
function clearNotesState(){
for (const n of notes){ n.hit=false; n.miss=false; }
score = 0; combo = 0;
hitFlash = 0; missFlash = 0;
updateScoreUI();
}
// --- transport ---
function audioTime(){
// Offset is ms added to judgement so user can calibrate
const off = (parseInt(ui.offset.value,10)||0) / 1000;
return (audioEl.currentTime || 0) + off;
}
async function loadSongFromDropdown(){
songId = ui.songSel.value;
songLabel = songId;
if (customObjectUrl){
URL.revokeObjectURL(customObjectUrl);
customObjectUrl = null;
}
audioEl.src = songId;
audioEl.load();
clearNotesState();
setError('');
await waitMetadata();
await rebuildChartUsingDecodeIfPossible(songId, null);
}
async function loadSongFromFile(file){
songId = 'custom';
songLabel = file.name;
if (customObjectUrl) URL.revokeObjectURL(customObjectUrl);
customObjectUrl = URL.createObjectURL(file);
audioEl.src = customObjectUrl;
audioEl.load();
clearNotesState();
setError('');
await waitMetadata();
await rebuildChartUsingDecodeIfPossible(file.name, file);
}
function waitMetadata(){
return new Promise((resolve, reject) => {
if (isFinite(audioEl.duration) && audioEl.duration > 0) return resolve();
const onOk = () => { cleanup(); resolve(); };
const onErr = (e) => { cleanup(); reject(e); };
const cleanup = () => {
audioEl.removeEventListener('loadedmetadata', onOk);
audioEl.removeEventListener('error', onErr);
};
audioEl.addEventListener('loadedmetadata', onOk);
audioEl.addEventListener('error', onErr);
});
}
function waitCanPlay(){
return new Promise((resolve, reject) => {
if (audioEl.readyState >= 2) return resolve();
const onOk = () => { cleanup(); resolve(); };
const onErr = () => { cleanup(); reject(audioEl.error || new Error('audio element error')); };
const cleanup = () => {
audioEl.removeEventListener('canplay', onOk);
audioEl.removeEventListener('canplaythrough', onOk);
audioEl.removeEventListener('error', onErr);
};
audioEl.addEventListener('canplay', onOk);
audioEl.addEventListener('canplaythrough', onOk);
audioEl.addEventListener('error', onErr);
});
}
async function startPlayback(){
ensureAudioGraph();
if (audioCtx.state === 'suspended') await audioCtx.resume();
// Ensure the media element has data buffered before play() to reduce NotSupported/Abort errors.
await waitCanPlay();
try{
await audioEl.play();
} catch(e){
// Surface useful diagnostics
const src = audioEl.currentSrc || audioEl.src || '(no src)';
const code = audioEl.error && audioEl.error.code ? audioEl.error.code : '';
const extra = code ? ` (mediaErrCode ${code})` : '';
throw new Error(`play() failed: ${e && e.name ? e.name : e}${extra} | src: ${src}`);
}
setError('');
playing = true;
paused = false;
}
function pausePlayback(){
audioEl.pause();
paused = true;
playing = false;
}
async function restartPlayback(){
audioEl.currentTime = 0;
clearNotesState();
await startPlayback();
}
function hardReset(){
pausePlayback();
audioEl.currentTime = 0;
clearNotesState();
}
async function toggleStartStop(){
if (!playing) {
try{ await startPlayback(); }
catch(e){
setError(e && e.message ? e.message : e);
console.error(e);
}
} else {
pausePlayback();
}
}
// --- gameplay judgement ---
function tryHitLane(lane){
if (!chartReady) return;
const tNow = audioTime();
const d = currentDiff();
// Find nearest unhit note in this lane within window
let best = null;
let bestIdx = -1;
let bestAbs = 9e9;
for (let i=0;i<notes.length;i++){
const n = notes[i];
if (n.lane !== lane || n.hit || n.miss) continue;
const dt = n.t - tNow;
const adt = Math.abs(dt);
if (adt < bestAbs){
bestAbs = adt;
best = n;
bestIdx = i;
}
if (n.t > tNow + d.hitWin) break;
}
if (best && bestAbs <= d.hitWin){
best.hit = true;
combo += 1;
score += 100 + Math.min(900, combo * 5);
hitFlash = 1.0;
updateScoreUI();
return true;
}
// No note: treat as miss input (small penalty)
combo = 0;
missFlash = 1.0;
updateScoreUI();
return false;
}
function markMisses(){
if (!chartReady) return;
const tNow = audioTime();
const d = currentDiff();
for (const n of notes){
if (n.hit || n.miss) continue;
if (n.t < tNow - d.hitWin){
n.miss = true;
combo = 0;
missFlash = 1.0;
updateScoreUI();
} else {
break;
}
}
}
// --- controller polling (edge-triggered) ---
const lastPad = { axes:[], btn:[] };
function pollGamepadEdges(){
const pads = navigator.getGamepads ? navigator.getGamepads() : [];
const gp = pads && pads[0];
if (!gp) return;
// buttons
for (let i=0;i<gp.buttons.length;i++){
const v = gp.buttons[i] && gp.buttons[i].pressed ? 1 : 0;
const prev = lastPad.btn[i] || 0;
if (v && !prev){
// rising edge
if (i === padMap.arrows.left) tryHitLane(0);
if (i === padMap.arrows.down) tryHitLane(1);
if (i === padMap.arrows.up) tryHitLane(2);
if (i === padMap.arrows.right) tryHitLane(3);
if (i === padMap.ps.square) tryHitLane(4);
if (i === padMap.ps.cross) tryHitLane(5);
if (i === padMap.ps.circle) tryHitLane(6);
if (i === padMap.ps.triangle) tryHitLane(7);
}
lastPad.btn[i] = v;
}
}
// --- visuals: TRON grid ---
let gridN = 28; // density
let pitch = 0.28; // perspective strength
function cellPxNear(){
return clamp(140 - gridN * 1.4, 26, 140);
}
function drawNeonLine(x1,y1,x2,y2,w,glow,a1,a2,color){
ctx.globalCompositeOperation = 'lighter';
ctx.lineCap = 'round';
ctx.strokeStyle = color;
ctx.globalAlpha = a1;
ctx.lineWidth = w;
ctx.beginPath(); ctx.moveTo(x1,y1); ctx.lineTo(x2,y2); ctx.stroke();
ctx.globalAlpha = a2;
ctx.lineWidth = w + glow;
ctx.beginPath(); ctx.moveTo(x1,y1); ctx.lineTo(x2,y2); ctx.stroke();
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
}
function drawGrid3D(){
const W = canvas.width;
const H = canvas.height;
const cx = W*0.5;
const horizon = H * 0.23;
const nearY = H * 0.88;
// subtle floor vignette
ctx.globalCompositeOperation = 'source-over';
const grad = ctx.createRadialGradient(cx, nearY, H*0.05, cx, nearY, H*0.60);
grad.addColorStop(0, 'rgba(20,22,40,0.55)');
grad.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = grad;
ctx.fillRect(0,0,W,H);
const cellNear = cellPxNear();
const halfSpan = W * 0.55;
const lanesFar = 46;
const lanesNear = 120;
// perspective helper: for a given depth z in [0,1], return y, scale
function proj(z){
const y = lerp(nearY, horizon, z);
const k = lerp(1.0, 0.10, z);
return { y, k };
}
// horizontal lines
for (let i=0;i<lanesFar;i++){
const z = i/(lanesFar-1);
const p = proj(z);
const y = p.y;
const k = p.k;
const span = halfSpan * k;
const major = (i % 4 === 0);
const col = major ? 'rgba(255,184,77,0.80)' : 'rgba(73,230,255,0.30)';
const a1 = major ? 0.34 : 0.22;
const a2 = major ? 0.10 : 0.06;
drawNeonLine(cx - span, y, cx + span, y, major?1.4:1.0, major?6.8:5.2, a1, a2, col);
}
// vertical rays
const n = Math.min(lanesNear, Math.floor(W / (cellNear*0.55)));
for (let i=-n;i<=n;i++){
const xNear = cx + i * cellNear;
const xFar = cx + i * cellNear * 0.06;
const major = (i % 6 === 0);
const col = major ? 'rgba(255,184,77,0.65)' : 'rgba(73,230,255,0.22)';
const a1 = major ? 0.30 : 0.18;
const a2 = major ? 0.10 : 0.06;
drawNeonLine(xNear, nearY, xFar, horizon, major?1.25:0.95, major?7.2:5.2, a1, a2, col);
}
// vanishing point glow
ctx.globalCompositeOperation = 'lighter';
const g2 = ctx.createRadialGradient(cx, horizon, 0, cx, horizon, H*0.08);
g2.addColorStop(0,'rgba(200,240,255,0.55)');
g2.addColorStop(1,'rgba(0,0,0,0)');
ctx.fillStyle = g2;
ctx.fillRect(0,0,W,H);
ctx.globalCompositeOperation = 'source-over';
return { cx, horizon, nearY };
}
// --- rhythm overlay in perspective ---
function laneXNear(idx, W){
// 8 lanes spread across a centered band
const band = W * 0.56;
const left = (W - band) * 0.5;
const w = band / LANES;
return left + w*(idx + 0.5);
}
function laneXFar(idx, W, vpX){
// converge towards VP
const bandFar = W * 0.05;
const left = vpX - bandFar*0.5;
const w = bandFar / LANES;
return left + w*(idx + 0.5);
}
function notePos(tNow, noteT, travel, geom){
const { cx, horizon, nearY } = geom;
const dt = noteT - tNow;
const u = clamp(1 - (dt / travel), 0, 1); // 0 far, 1 near
const z = clamp(1 - u, 0, 1);
const y = lerp(nearY, horizon, z);
const k = lerp(1.0, 0.10, z);
return { u, z, y, k };
}
function drawWaveform(geom){
if (!analyser) return;
analyser.getByteTimeDomainData(waveform);
const W = canvas.width;
const H = canvas.height;
const yBase = geom.horizon - H*0.06;
const x0 = W*0.15;
const x1 = W*0.85;
ctx.globalCompositeOperation = 'lighter';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// thin wave
ctx.strokeStyle = 'rgba(255,90,90,0.28)';
ctx.lineWidth = 1.1;
ctx.beginPath();
for (let i=0;i<waveform.length;i++){
const v = (waveform[i] - 128) / 128;
const x = lerp(x0, x1, i/(waveform.length-1));
const y = yBase + v * H*0.015;
if (i===0) ctx.moveTo(x,y); else ctx.lineTo(x,y);
}
ctx.stroke();
// glow
ctx.strokeStyle = 'rgba(255,90,90,0.12)';
ctx.lineWidth = 4.6;
ctx.stroke();
ctx.globalCompositeOperation = 'source-over';
}
function drawReceptors(geom){
const W = canvas.width;
const { cx, horizon, nearY } = geom;
const hitY = nearY - canvas.height * 0.035;
// RED HIT LINE (requested)
const baseA = 0.22;
const a = baseA + 0.35*hitFlash + 0.45*missFlash;
const glow = 10 + 16*hitFlash + 22*missFlash;
drawNeonLine(W*0.22, hitY-10, W*0.78, hitY-10, 2.2, glow, a, a*0.35, 'rgba(255,60,60,0.90)');
// circles + glyphs
for (let i=0;i<LANES;i++){
const x = laneXNear(i, W);
const r = 10.5;
ctx.globalCompositeOperation = 'lighter';
// ring
ctx.strokeStyle = 'rgba(255,90,230,0.85)';
ctx.lineWidth = 2.6;
ctx.beginPath(); ctx.arc(x, hitY, r, 0, Math.PI*2); ctx.stroke();
ctx.strokeStyle = 'rgba(255,90,230,0.18)';
ctx.lineWidth = 8.5;
ctx.beginPath(); ctx.arc(x, hitY, r, 0, Math.PI*2); ctx.stroke();
// glyph
ctx.fillStyle = 'rgba(225,240,255,0.92)';
ctx.font = '14px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(laneLabel[i].glyph, x, hitY);
ctx.globalCompositeOperation = 'source-over';
}
return { hitY };
}
function drawNotes(geom){
if (!chartReady) return;
const W = canvas.width;
const tNow = audioTime();
const d = currentDiff();
for (const n of notes){
if (n.hit || n.miss) continue;
const pos = notePos(tNow, n.t, d.travel, geom);
if (pos.u <= 0) continue; // not yet spawned
if (pos.u >= 1.15) continue;
const xN = laneXNear(n.lane, W);
const xF = laneXFar(n.lane, W, geom.cx);
const x = lerp(xF, xN, pos.u);
const y = pos.y;
const r = lerp(4.2, 11.0, pos.u);
const alpha = lerp(0.10, 0.95, pos.u);
const isArrow = (n.lane < 4);
const col = isArrow ? 'rgba(73,230,255,1)' : 'rgba(255,184,77,1)';
// note body
ctx.globalCompositeOperation = 'lighter';
ctx.fillStyle = col;
ctx.globalAlpha = alpha * 0.22;
ctx.beginPath(); ctx.arc(x,y,r*1.55,0,Math.PI*2); ctx.fill();
ctx.globalAlpha = alpha * 0.85;
ctx.beginPath(); ctx.arc(x,y,r*0.80,0,Math.PI*2); ctx.fill();
// glyph
ctx.globalAlpha = alpha;
ctx.fillStyle = 'rgba(235,245,255,0.92)';
ctx.font = `${Math.floor(r*1.45)}px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(laneLabel[n.lane].glyph, x, y+0.5);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
}
}
// --- main loop ---
let last = performance.now();
let acc = 0;
const dtFixed = 1/120;
function step(dt){
// decay flashes
hitFlash = Math.max(0, hitFlash - dt*3.2);
missFlash = Math.max(0, missFlash - dt*2.4);
// inputs: keyboard hits (edge-ish)
// We use keydown edges by checking a latch per frame.
}
const keyLatch = new Map();
function consumePress(code){
const down = keys.has(code);
const was = keyLatch.get(code) || false;
keyLatch.set(code, down);
return down && !was;
}
function handleInputs(){
// arrows
if (consumePress('ArrowLeft')) tryHitLane(0);
if (consumePress('ArrowDown')) tryHitLane(1);
if (consumePress('ArrowUp')) tryHitLane(2);
if (consumePress('ArrowRight'))tryHitLane(3);
// WASD symbols
if (consumePress('KeyA')) tryHitLane(4);
if (consumePress('KeyS')) tryHitLane(5);
if (consumePress('KeyD')) tryHitLane(6);
if (consumePress('KeyW')) tryHitLane(7);
pollGamepadEdges();
}
function draw(){
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = '#000';
ctx.fillRect(0,0,canvas.width,canvas.height);
const geom = drawGrid3D();
// waveform (thin)
drawWaveform(geom);
// notes and receptors
drawNotes(geom);
drawReceptors(geom);
// status
const t = audioEl.currentTime || 0;
const dur = isFinite(audioEl.duration) ? audioEl.duration : 0;
const d = currentDiff();
const mode = playing ? (paused ? 'paused' : 'playing') : 'stopped';
const errLine = lastError ? (`ERROR: ${lastError}\n`) : '';
setStatus(
errLine + `song: ${songLabel}\n` +
`mode: ${mode} | time: ${t.toFixed(2)} / ${dur?dur.toFixed(2):'--'}\n` +
`diff: ${d.name} | travel: ${d.travel.toFixed(2)}s | hitwin: ${Math.round(d.hitWin*1000)}ms\n` +
(chartReady ? `notes: ${notes.length} | seed: ${chartSeed}` : 'chart: building...')
);
}
function frame(){
const now = performance.now();
let dt = (now - last) / 1000;
last = now;
dt = Math.min(dt, 0.05);
acc += dt;
while (acc >= dtFixed){
step(dtFixed);
acc -= dtFixed;
}
handleInputs();
if (playing) markMisses();
draw();
requestAnimationFrame(frame);
}
// --- UI wiring ---
ui.offset.addEventListener('input', () => ui.offsetLbl.textContent = ui.offset.value);
ui.offsetLbl.textContent = ui.offset.value;
ui.songSel.addEventListener('change', async () => {
try{ await loadSongFromDropdown(); }
catch(e){ setError('audio error — ' + (e && e.message ? e.message : 'see console')); console.error(e); }
});
ui.diffSel.addEventListener('change', async () => {
// rebuild chart deterministically at new density
try{
if (songId === 'custom' && ui.file.files && ui.file.files[0]){
await loadSongFromFile(ui.file.files[0]);
} else {
await loadSongFromDropdown();
}
} catch(e){
setError(e && e.message ? e.message : e);
console.error(e);
}
});
ui.file.addEventListener('change', async () => {
if (!ui.file.files || !ui.file.files[0]) return;
try{ await loadSongFromFile(ui.file.files[0]); }
catch(e){ setError('audio error — ' + (e && e.message ? e.message : 'see console')); console.error(e); }
});
ui.start.addEventListener('click', async () => {
try{ await toggleStartStop(); }
catch(e){ setError('audio error — ' + (e && e.message ? e.message : 'see console')); console.error(e); }
});
ui.pause.addEventListener('click', () => pausePlayback());
ui.restart.addEventListener('click', async () => {
try{ await restartPlayback(); }
catch(e){ setError('audio error — ' + (e && e.message ? e.message : 'see console')); console.error(e); }
});
// --- init ---
(async () => {
try{
await loadSongFromDropdown();
updateScoreUI();
} catch(e){
setError(e && e.message ? e.message : e);
console.error(e);
}
})();
requestAnimationFrame(frame);
})();
</script>
</body>
</html>