Repository navigation
Expand file tree
/
Copy pathbb.js
More file actions
3376 lines (3089 loc) · 128 KB
/
Copy pathbb.js
File metadata and controls
3376 lines (3089 loc) · 128 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
/*
* BB — a port of the AA-group ASCII demo (1997) to TSVM/TVDOS.
*
* Original: Jan Hubicka, Filip Kupsa, Mojmir Svoboda, Kamil Toman
* Music: bb.taud / bb2.taud / bb3.taud (converted from the S3M originals)
* Port: CuriousTorvald
*
* Run from TVDOS: bb
* Skip a scene: Backspace
* Quit: Q (or Esc)
*/
const taud = require("taud")
const lfs = require("lfs")
// ============================================================================
// Asset directory — relative to the current drive
// ============================================================================
const BB_DIR = _G.shell.getFileDir()
const aa = require("aa")
// ============================================================================
// Data assets live inside bb-assets.lfs and are unpacked to a fresh $:/TMP
// directory on first run. lfs.extractAll transparently decompresses zstd/gzip
// payloads, but keeps the archived leaf names — so e.g. `zeb.raw.zst` ends up
// as a file literally named `zeb.raw.zst` whose contents are the inflated
// `.raw` bytes. The loaders below read by path, so the extension on disk is
// just a label — no rename pass is needed.
// ============================================================================
const ASSETS_DIR = (function() {
const dir = lfs.extractAll(BB_DIR + "/bb-assets.lfs")
return dir.fullPath + "\\"
})()
// ============================================================================
// Terminal geometry & globals
// ============================================================================
const [TROWS, TCOLS] = con.getmaxyx()
const HALF_W = (TCOLS / 2) | 0
const HALF_H = (TROWS / 2) | 0
const BLACK = 255
const WHITE = 254
const GREY = 253
const DARKGREY = 245
const DIM = 244
let g_t0_ns = 0
let g_quit = false
let g_skip = false
// ============================================================================
// AAlib context — created on demand so scenes that don't need it cost nothing.
// Image buffer is 2x screen resolution in each axis (TROWS*2 by TCOLS*2);
// each text cell maps to a 2x2 NW/NE/SW/SE patch sampled at render time.
// ============================================================================
let g_aa = null
let g_aaPar = null
let g_font = null
// aaFont() returns the TSVM 7x14 system font, used both by aa.print() for
// typesetting big text into the image buffer AND (via aa.init's opts.font)
// by AAlib's glyph-selection LUT. The font is loaded from tsvm.chr — the
// native ROM format produced by tvdos/tuidev/font_rom_builder.c, identical
// to GraphicsAdapter.kt's character ROM, so it stays in sync with what the
// hardware text mode actually draws.
function aaFont() {
if (!g_font) g_font = aa.loadChrFontROM(ASSETS_DIR + "tsvm.chr.zst")
return g_font
}
function aaCtx() {
if (!g_aa) {
g_aa = aa.init(TCOLS, TROWS, { font: aaFont() })
g_aaPar = aa.getrenderparams()
}
return g_aa
}
function sysNow() { return sys.nanoTime() }
function sleepMs(ms) { if (ms > 0) sys.sleep(ms) }
// ============================================================================
// Key polling
// ============================================================================
// Keyboard MMIO snapshot lives at -40..-48 (see JS_INIT.js con.poll_keys).
const KEY_BACKSPACE = 67
const KEY_ESC = 111
const KEY_Q = 45
function checkInput() {
sys.poke(-40, 1)
for (let a = -41; a >= -48; a--) {
const k = sys.peek(a)
if (k === 0) continue
if (k === KEY_BACKSPACE) g_skip = true
else if (k === KEY_ESC || k === KEY_Q) { g_quit = true; g_skip = true }
}
}
// ============================================================================
// Drawing primitives
// ============================================================================
function setFG(c) { print("\x1B[38;5;" + (c|0) + "m") }
function setBG(c) { print("\x1B[48;5;" + (c|0) + "m") }
function reset() { print("\x1B[m") }
function clearScreen() { con.color_pair(WHITE, BLACK); con.clear() }
// ============================================================================
// Direct-VRAM text helpers — never trigger scrolling on (TROWS, TCOLS).
//
// Writing to the bottom-right cell via the cursor (print() or mvaddch) makes
// the cursor advance past column TCOLS, wrap to row TROWS+1, and scroll the
// entire screen up by one row. By poking the GPU text-plane VRAM directly we
// place characters without moving the cursor at all.
//
// Layout: peripheral byte k lives at JS address (gpuMemBase - k).
// char plane : textArea[5122..7681] (80 x 32, row-major)
// fore plane : textArea[2..2561]
// back plane : textArea[2562..5121]
// ============================================================================
const _GPU_BASE = graphics.getGpuMemBase()
const _TXT_CHAR_PTR = _GPU_BASE - 259072 // textArea[5122]
const _TXT_FORE_PTR = _GPU_BASE - 253952 // textArea[2]
const _TXT_BACK_PTR = _GPU_BASE - 256512 // textArea[2562]
function putCh(y, x, ch) {
if (y < 1 || y > TROWS || x < 1 || x > TCOLS) return
const off = (y - 1) * 80 + (x - 1)
sys.poke(_TXT_CHAR_PTR - off, ch & 0xFF)
sys.poke(_TXT_FORE_PTR - off, con.get_color_fore())
sys.poke(_TXT_BACK_PTR - off, con.get_color_back())
}
// Write a row of characters into VRAM at (y, x) 1-indexed. Clips to TCOLS,
// honours the cursor's current FG/BG via the colour planes.
function vramPutRow(y, x, str) {
if (y < 1 || y > TROWS) return
if (x > TCOLS) return
let s = str
if (x < 1) { s = s.substring(1 - x); x = 1 }
const room = TCOLS - x + 1
if (s.length > room) s = s.substring(0, room)
const len = s.length
if (len <= 0) return
const off = (y - 1) * 80 + (x - 1)
const fg = con.get_color_fore()
const bg = con.get_color_back()
const cA = new Uint8Array(len)
const fA = new Uint8Array(len)
const bA = new Uint8Array(len)
for (let i = 0; i < len; i++) {
cA[i] = s.charCodeAt(i) & 0xFF
fA[i] = fg
bA[i] = bg
}
sys.pokeBytes(_TXT_CHAR_PTR - off, cA, len)
sys.pokeBytes(_TXT_FORE_PTR - off, fA, len)
sys.pokeBytes(_TXT_BACK_PTR - off, bA, len)
}
function centerText(y, text) {
if (y < 1 || y > TROWS) return
let x = ((TCOLS - text.length) >>> 1) + 1
if (x < 1) x = 1
vramPutRow(y, x, text)
}
function drawText(y, x, text) {
if (y < 1 || y > TROWS) return
if (x > TCOLS) return
vramPutRow(y, x, text)
}
// ============================================================================
// Music
// ============================================================================
const PLAYHEAD = audio.getFreePlayhead(0)
function loadSong(path) {
audio.resetParams(PLAYHEAD)
audio.purgeQueue(PLAYHEAD)
audio.stop(PLAYHEAD)
try {
taud.uploadTaudFile(path, 0, PLAYHEAD)
audio.setMasterVolume(PLAYHEAD, 255)
audio.setMasterPan(PLAYHEAD, 128)
audio.setCuePosition(PLAYHEAD, 0)
return true
} catch (e) {
serial.println("bb: music load failed: " + path + " - " + e)
return false
}
}
function startMusic() { audio.play(PLAYHEAD) }
function stopMusic() { audio.stop(PLAYHEAD) }
// ============================================================================
// Scene runner
// ============================================================================
function runScene(durUs, fps, tick) {
if (g_quit) return false
g_skip = false
const frameUs = Math.max(1, (1000000 / fps) | 0)
const start = sysNow()
let lastFrame = -1
while (true) {
if (g_quit || g_skip) break
const elapsedUs = ((sysNow() - start) / 1000) | 0
if (elapsedUs >= durUs) break
const f = (elapsedUs / frameUs) | 0
if (f !== lastFrame) {
tick(elapsedUs, durUs)
lastFrame = f
}
checkInput()
const sleep = 1 + ((frameUs / 1000) >> 2)
sleepMs(sleep)
}
g_skip = false
return !g_quit
}
function waitMs(ms) {
return runScene(ms * 1000, 60, function() {})
}
// ============================================================================
// SCENE 1 — near-verbatim port of scene1.c
//
// Constants mirror the C #defines:
// EFECT=2 → ETIME = 2 s per typewriter / scramble phase
// EFECT2=6.0 → 6 s of "decrandom" (AA / PRESENTS sharpening)
// N_STEP=30, MAXSHIFT=800, MAXRAND=40, MAXEFECT2=3570
//
// The original drives every effect through timestuff(rate, control, draw, dur):
// the control() function fires at `rate` Hz and receives n ticks elapsed since
// the last call; draw() repaints between ticks. We reproduce that semantics.
// ============================================================================
const _S1_EFECT = 2
const _S1_EFECT2 = 6.0
const _S1_ETIME = _S1_EFECT * 1000000 // 2,000,000 µs
const _S1_ETIME1 = _S1_EFECT * 1000000
const _S1_MAXSHIFT = _S1_EFECT * 400 // 800
const _S1_MAXRAND = _S1_EFECT * 20 // 40
const _S1_N_STEP = 30
const _S1_MAXEFECT2 = (_S1_N_STEP * _S1_EFECT2 * 20 - _S1_N_STEP) | 0 // 3570
// HEXA — every other call yields a hex digit (A-F or 0-9), one in three a
// space. The C macro is `(rand()&2 ? 'A'+rand()%6 : '0'+rand()%10)`; we keep
// the same A-F vs 0-9 split.
function _s1Hexa() {
return (Math.random() < 0.5)
? String.fromCharCode(0x41 + ((Math.random() * 6) | 0)) // A-F
: String.fromCharCode(0x30 + ((Math.random() * 10) | 0)) // 0-9
}
// timestuff(rate, control, draw, durUs) — fires control(n) at |rate| Hz with
// n = number of ticks accumulated since the previous call, and draw() at
// frame pace between firings. Returns false if the user quit, true otherwise.
function timestuff(rate, control, draw, durUs) {
if (g_quit) return false
if (control === null) rate = -40
const absRate = Math.abs(rate)
const intervalUs = Math.max(1, (1000000 / absRate) | 0)
const start = sysNow()
let nextTickUs = intervalUs
if (control !== null) control(1) // initial kick, matching C
while (true) {
if (g_quit || g_skip) break
const elapsedUs = ((sysNow() - start) / 1000) | 0
if (elapsedUs >= durUs) break
if (control !== null && elapsedUs >= nextTickUs) {
const n = 1 + (((elapsedUs - nextTickUs) / intervalUs) | 0)
nextTickUs += n * intervalUs
control(n)
}
if (draw) draw()
checkInput()
sleepMs(1)
}
if (draw && !g_quit) draw()
g_skip = false
return !g_quit
}
// Image-buffer centerprint — mirror of bb.c:centerprint(x, y, size, color, t, 0)
// height = imgH / size
// width = height * imgW * 0.75 / imgH * mmH / mmW
// In our context mmW == scrW and mmH == scrH, so mmH/mmW == scrH/scrW.
function _s1Centerprint(ctx, font, x, y, size, color, text) {
const W = aa.imgwidth(ctx), H = aa.imgheight(ctx)
const mmW = aa.mmwidth(ctx), mmH = aa.mmheight(ctx)
const height = H / size
const width = height * W * 0.75 / H * mmH / mmW
if (width < 1 || height < 1) return
const w0 = Math.max(1, width | 0)
const h0 = Math.max(1, height | 0)
aa.print(ctx,
(x - (w0 * text.length) / 2) | 0,
(y - (h0 >>> 1)) | 0,
w0, h0, font, color | 0, text)
}
// Same for centerprinth — width is the divisor:
// width = imgW / size
// height = width * imgH * 1.333 / imgW * mmW / mmH
function _s1Centerprinth(ctx, font, x, y, size, color, text) {
const W = aa.imgwidth(ctx), H = aa.imgheight(ctx)
const mmW = aa.mmwidth(ctx), mmH = aa.mmheight(ctx)
const width = W / size
const height = width * H * 1.333 / W * mmW / mmH
if (width < 1 || height < 1) return
const w0 = Math.max(1, width | 0)
const h0 = Math.max(1, height | 0)
aa.print(ctx,
(x - (w0 * text.length) / 2) | 0,
(y - (h0 >>> 1)) | 0,
w0, h0, font, color | 0, text)
}
// ── Module-level draw / strobik (mirror of bb.c:draw, scene1.c:strobik*) ────
// `bbDraw` is the global draw(): calls the current drawptr (if any), renders
// the image buffer into the text buffer (via aa.render), overlays the current
// status text in AA_SPECIAL, then flushes. Used by every effect that wants
// the standard pipeline.
let g_drawptr = null
let g_overlayText = ""
function bbOverlay() {
if (!g_overlayText || !g_overlayText.length) return
const ctx = aaCtx()
const scrW = aa.scrwidth(ctx), scrH = aa.scrheight(ctx)
const x = ((scrW - g_overlayText.length) / 2) | 0
aa.puts(ctx, x, (scrH / 2) | 0, aa.AA_SPECIAL, g_overlayText)
}
function bbDraw() {
const ctx = aaCtx()
if (g_drawptr !== null) g_drawptr()
aa.render(ctx, g_aaPar)
bbOverlay()
aa.flush(ctx)
}
// strobikstart / strobikend — the white-flash + fade primitives. Each portrait
// transition, every blazinec card, and the scene1 → scene3 handoff all pivot
// on these.
function strobikstart() {
const params = g_aaPar
params.bright = 0
timestuff(-60, function(n) { params.bright += n * 50 }, bbDraw, (1000000 / 15) | 0)
params.bright = 255
bbDraw()
}
function strobikend() {
const params = g_aaPar
timestuff(-60, function(n) { params.bright = params.bright >> n }, bbDraw, (1000000 / 3.5) | 0)
params.bright = 0
bbDraw()
}
// bbwait — equivalent of bb.c:bbwait(): block for `us` microseconds while
// keeping input polling alive. Returns false if the user quit.
function bbwait(us) { return runScene(us, 60, function() {}) }
// bbflushwait — bb.c:bbflushwait(). Pushes the textbuffer to the screen then
// waits `us` µs. Used by scene4's invader animation (purely textbuffer ops,
// no image-buffer pipeline).
function bbflushwait(us) {
const ctx = aaCtx()
aa.flush(ctx)
return bbwait(us)
}
// bbGetwidth — bb.c:getwidth(size). Per-glyph width that centerprint would
// use for the given size on the current context.
function bbGetwidth(ctx, size) {
const W = aa.imgwidth(ctx), H = aa.imgheight(ctx)
const mmW = aa.mmwidth(ctx), mmH = aa.mmheight(ctx)
const height = H / size
return height * W * 0.75 / H * mmH / mmW
}
function scene1() {
const ctx = aaCtx()
const params = g_aaPar
const font = aaFont()
const scrW = aa.scrwidth(ctx), scrH = aa.scrheight(ctx)
const imgW = aa.imgwidth(ctx), imgH = aa.imgheight(ctx)
const tb = ctx.textbuffer, ab = ctx.attrbuffer
clearScreen(); con.curs_set(0)
aa.cleartext(ctx)
aa.clear(ctx)
aa.flush(ctx)
params.dither = aa.AA_FLOYD_S
params.bright = 0
params.contrast = 0
params.randomval = 0
g_overlayText = "Please wait. Precalculating data"
g_drawptr = null
let cursorx = 0, cursory = 0
let s1_bright = 255
let s1_pos = 0, s1_delta = 0, s1_dist = 0
let s1_f = -10.0
let randshift = 0, randcharacters = 0, randattrs = 0
// ── drawwait: just flush current textbuffer with overlay ────────────────
const drawwait = function() {
bbOverlay()
aa.flush(ctx)
}
// ── calculateslow: write one cell per call (the "slow typewriter") ─────
const calculateslow = function(n) {
cursorx++
if (cursorx >= scrW) {
cursory++
cursorx = 1
if (cursory >= scrH) cursory = 0
}
const ch = ((cursorx % 3) !== 0) ? _s1Hexa().charCodeAt(0) : 0x20
tb[cursory * scrW + cursorx - 1] = ch
ab[cursory * scrW + cursorx - 1] = aa.AA_NORMAL
}
// ── drawline: full-row scramble used by calculatefast / drawwait3 ──────
const drawline = function(y) {
const useShift = (Math.random() * _S1_MAXSHIFT) < randshift
const shift = useShift ? ((Math.random() * 1048576) | 0) : -1
const base = y * scrW
for (let x = 0; x < scrW; x++) {
if (randattrs && (Math.random() * _S1_MAXRAND) < randattrs) {
// leave attr alone
} else {
ab[base + x] = aa.AA_NORMAL
}
if (randcharacters && (Math.random() * _S1_MAXRAND) < randcharacters) {
// leave char alone
continue
}
tb[base + x] = (((x - shift) % 3) !== 0) ? _s1Hexa().charCodeAt(0) : 0x20
}
}
// ── calculatefast: scramble n whole lines per call ─────────────────────
const calculatefast = function(n) {
if (randshift) randshift += n
for (let i = 0; i < n; i++) {
drawline(cursory)
cursory++
cursorx = 0
if (cursory >= scrH) cursory = 0
}
}
// ── drawwait3: render the (empty) image buffer then scramble all rows ──
const drawwait3 = function() {
aa.render(ctx, params)
for (let y = 0; y < scrH; y++) drawline(y)
bbOverlay()
aa.flush(ctx)
}
// ── calculatefastest: just ramp randcharacters / randattrs in place ────
const calculatefastest = function(n) {
if (randcharacters) randcharacters += n
if (randattrs) randattrs += n
}
// ── decrandom: decrease params.randomval (sharpens the AA/PRESENTS) ────
const decrandom = function(n) {
if (params.randomval > 0) params.randomval -= n * _S1_N_STEP
if (params.randomval < 60) params.randomval = 60
}
// ── decbright: decrease the local `bright` (fades the AA/PRESENTS) ─────
const decbright = function(n) { s1_bright -= n * 16 }
// ── makepos / makepos1 / makepos2: damped harmonic for the two B's ─────
const makepos = function(n) {
for (let i = 0; i < n; i++) {
s1_f += (imgH / 2 - s1_pos) / 60.0
s1_f *= 0.95
s1_pos += s1_f
}
}
const makepos1 = function(n) {
for (let i = 0; i < n; i++) {
s1_f += (imgH / 2 - s1_pos) / 60.0
s1_f *= 0.95
s1_pos += s1_f
s1_delta += 0.2
}
}
const makepos2 = function(n) {
for (let i = 0; i < n; i++) {
s1_f += (imgH / 2 - s1_pos) / 60.0
s1_f *= 0.95
s1_pos += s1_f
s1_delta -= 0.2
if (s1_delta <= 2) s1_delta = 0.1
s1_dist += 0.08
}
}
// ── drawwait2: AA + PRESENTS (image-buffer ink, faded via `bright`) ────
const drawwait2 = function() {
let i = s1_bright
if (i < 0) i = 0
_s1Centerprint(ctx, font, imgW / 2, imgH / 3, 2, i, "AA")
i = s1_bright + 255
if (i < 0) i = 0
if (i > 255) i = 255
_s1Centerprinth(ctx, font, imgW / 2, 2 * imgH / 3, 8, i, "PRESENTS")
}
// ── drawwait4: two mirrored B's drifting on a damped harmonic ──────────
const drawwait4 = function() {
aa.clear(ctx)
const closeTogether = 14
const size = 1.1 + s1_delta / 2
_s1Centerprint(ctx, font, imgW / 4 - s1_dist * imgW + closeTogether, s1_pos, size, 255, "B")
_s1Centerprint(ctx, font, 3 * imgW / 4 + s1_dist * imgW - closeTogether, imgH - s1_pos, size, 255, "B")
}
const hlaska = function(t, sz) {
aa.clear(ctx)
_s1Centerprint(ctx, font, imgW / 2, imgH / 2, sz, 255, t)
}
const blazinec = function() {
const blText = [
"the","100 %","TSVM","COMPATIBLE","DEMO",";^D","(^;",
"FULL","80-COL","TEXT","MODE","",
"DEVELOPED","UNDER","openSUSE","!","!","!","?",
]
const blSize = [3,3.5,3.5,4.6,3,2,2,3,3,3,3,1,4.4,3,4,1.5,2.2,3,4.2]
for (let i = 0; i < blText.length; i++) {
if (g_quit || g_skip) { g_skip = false; return }
strobikstart()
params.randomval = 0
hlaska(blText[i], blSize[i] / 1.5) // arbitrary resizing
strobikend()
}
strobikstart()
bbDraw()
}
// ── Opening typewriter ramp — 7 phases × ETIME (2 s each) = 14 s ───────
timestuff(-10, calculateslow, drawwait, _S1_ETIME1)
timestuff(-40, calculateslow, drawwait, _S1_ETIME1)
timestuff(-80, calculateslow, drawwait, _S1_ETIME1)
timestuff(-30, calculatefast, drawwait, _S1_ETIME1)
timestuff(-200, calculatefast, drawwait, _S1_ETIME1)
timestuff(-420, calculatefast, drawwait, _S1_ETIME)
if (g_quit) return
randshift = 1
timestuff(600, calculatefast, drawwait, _S1_ETIME1)
randshift = _S1_MAXSHIFT
params.randomval = _S1_MAXEFECT2 + 50
g_overlayText = ""
aa.gotoxy(ctx, 0, 0)
aa.hidecursor(ctx)
if (g_quit) return
// ── Full-screen scramble — 5 phases × ETIME (2 s each) = 10 s ──────────
timestuff(20, calculatefastest, drawwait3, _S1_ETIME)
timestuff(20, calculatefastest, drawwait3, _S1_ETIME)
randcharacters = 1
timestuff(20, calculatefastest, drawwait3, _S1_ETIME)
randcharacters = _S1_MAXRAND
randattrs = 1
timestuff(20, calculatefastest, drawwait3, _S1_ETIME)
randattrs = _S1_MAXRAND
timestuff(20, calculatefastest, drawwait3, _S1_ETIME)
if (g_quit) return
// ── play(): music fires HERE, exactly as in scene1.c:377 ───────────────
g_drawptr = drawwait2
startMusic()
// ── AA / PRESENTS — randomval drops, then bright fades ─────────────────
timestuff(20, decrandom, bbDraw, (_S1_EFECT2 * 1000000) | 0) // 6 s
timestuff(20, decbright, bbDraw, _S1_ETIME) // 2 s
if (g_quit) return
// ── Two falling B's, harmonic settles, then they part and exit ─────────
s1_pos = imgH * 2
g_drawptr = drawwait4
timestuff(60, makepos, bbDraw, 5 * 1000000)
timestuff(60, makepos1, bbDraw, 0.2 * 1000000)
timestuff(60, makepos2, bbDraw, 0.3 * 1000000)
g_drawptr = null
if (g_quit) return
// ── Final strobe parade ────────────────────────────────────────────────
blazinec()
}
// ============================================================================
// SCENE 2 — Greetings scroller + group-name zoomer parade
// ============================================================================
// ── scene2.c port ───────────────────────────────────────────────────────────
// Two phases:
// 1. dvojprujezd2(): "Greetings" slides L→R at H/3, "To" slides R→L at 2H/3.
// Runs 2.75 s.
// 2. pokec parade: each name zooms outward from a tiny point at the centre
// (small + bright → large + dark) while the PREVIOUS name continues its
// zoom-out from 650 ms ago, producing a crossfade. ETIME=650 ms per name,
// 3*ETIME for the last.
// ============================================================================
function _scene2Drawzoomer(ctx, font, mesg, stateUs, posIdx, imgW, imgH) {
if (!mesg || mesg.length === 0) return
if (stateUs <= 0) return
const width = 1000000.0 / stateUs
if (width > 1.0) {
let color = ((width - 1) * 255) | 0
if (color > 255) color = 255
if (color < 0) color = 0
_s1Centerprint(ctx, font, imgW / 2, posIdx * imgH / 6, width, color, mesg)
}
}
function scene2() {
const ctx = aaCtx(), font = aaFont()
const params = g_aaPar
const imgW = aa.imgwidth(ctx), imgH = aa.imgheight(ctx)
clearScreen(); con.curs_set(0)
aa.cleartext(ctx); aa.clear(ctx)
params.dither = aa.AA_FLOYD_S
params.bright = 0
params.contrast = 0
params.randomval = 0
g_drawptr = null
g_overlayText = ""
// ── Phase 1: dvojprujezd2 ───────────────────────────────────────────────
const dur1 = 2750000
let phaseStart = sysNow()
g_drawptr = function() {
const STATE = ((sysNow() - phaseStart) / 1000) | 0
const total = dur1
aa.clear(ctx)
const w = bbGetwidth(ctx, 2)
// text1 = "Greetings" slides L→R at H/3
const t1 = "Greetings"
let p = w * t1.length + 1
_s1Centerprint(ctx, font,
-p / 2 + (imgW + p * 1.2) * STATE / total,
imgH / 3, 2, 255, t1)
// text2 = "To" slides R→L at 2H/3
const t2 = "To"
p = w * t2.length + 1
_s1Centerprint(ctx, font,
imgW + p / 2 - (imgW + p * 1.2) * STATE / total,
2 * imgH / 3, 2, 255, t2)
}
timestuff(60, null, bbDraw, dur1)
if (g_quit) return
// ── Phase 2: pokec parade ───────────────────────────────────────────────
const pokec = [
"Future", "Crew", "Triton", "Cascada", "Complex", "Pascal",
"Titans", "Xography", "Sonic PC", "Scrymag", "...",
"Microsoft", "", "!?!",
]
const ETIME = 650000
let mesg = "", lastmesg = ""
let pos = 2, lastpos = 1
for (let i = 0; i < pokec.length; i++) {
if (g_quit) return
lastpos = pos
pos++
if (pos > 4) pos = 2
lastmesg = mesg
mesg = pokec[i]
const itemDur = (i === pokec.length - 1) ? 3 * ETIME : ETIME
const iterStart = sysNow()
const _mesg = mesg, _lastmesg = lastmesg
const _pos = pos, _lastpos = lastpos
g_drawptr = function() {
const STATE = ((sysNow() - iterStart) / 1000) | 0
aa.clear(ctx)
// Previous name lingers — it was launched ETIME ago.
_scene2Drawzoomer(ctx, font, _lastmesg, STATE + ETIME, _lastpos, imgW, imgH)
// Current name just started.
_scene2Drawzoomer(ctx, font, _mesg, STATE, _pos, imgW, imgH)
}
timestuff(0, null, bbDraw, itemDur)
}
g_drawptr = null
waitMs(300) // TSVM timing fix
}
// ============================================================================
// SCENE 3 — plasma + sliding messages
//
// Near-verbatim port of scene3.c (plasma engine) + scene2.c's message() /
// centerprint() (the wobbly bottom-to-top scrollers).
//
// - 190-step zoom table of signed cosine values is precomputed once
// (initPlasmaTables). Each plasma pixel reads six entries from the
// active zoom slice and sums them mod 256.
// - Two custom palettes (Pal[0], Pal[1]) are cross-faded into TempPal
// every 64 ticks via cplasma(). aa.renderpalette() applies the result
// across the whole image buffer at render time.
// - message() rasterises text into the image buffer at a size that
// oscillates as (1+cos(pp))*5+2 (huge → tiny → huge) while scrolling
// up the screen, with brightness sin(pp/2)*255 (fade in, peak, fade out).
// - The text ink lands in the image buffer as raw luminance values, which
// get re-mapped by the same plasma palette — so bright text reads as
// dark "voids" cut into the plasma, matching the C demo.
// ============================================================================
const _PLASMA_ZTABSIZE = 190 // (2.70 - 0.80) / 0.01
const _PLASMA_FRAMERATE = 35
const _PLASMA_STIME = 11 * 1000000 // first message starts at +11 s
const _PLASMA_TTIME = 1 * 1000000 // each message slot is 1 s apart
const _PLASMA_MAXPOS = 2500000 // each message lives for 2.5 s
const _PLASMA_DUR_US = 42 * 1000000 // scene length
let g_plasmaTbl = null // Int8Array(190*256)
let g_plasmaPal = null // [Uint8Array(256), Uint8Array(256)]
let g_plasmaTemp = null // Uint8Array(256)
function initPlasmaTables() {
if (g_plasmaTbl) return
g_plasmaTbl = new Int8Array(_PLASMA_ZTABSIZE * 256)
for (let pnum = 0; pnum < _PLASMA_ZTABSIZE; pnum++) {
const czoom = 0.80 + pnum * 0.01
const div = czoom * czoom * czoom * czoom
const base = pnum * 256
for (let i = 0; i < 256; i++) {
// RAD(i * 256/180) — angle in degrees, converted to radians.
const angle = (i * 256 / 180) * Math.PI / 180
// Cast to signed 8-bit (Int8Array auto-wraps via two's complement),
// matching the original `(char)` truncation.
g_plasmaTbl[base + i] = (Math.cos(angle) * 256 / div) | 0
}
}
const p0 = new Uint8Array(256)
const p1 = new Uint8Array(256)
for (let i = 0; i < 64; i++) { p0[i] = i * 4; p1[i] = i * 1 }
for (let i = 64; i < 128; i++) { p0[i] = (128 - i) * 4; p1[i] = (128 - i) * 1 }
for (let i = 128; i < 192; i++) { p0[i] = (i - 128) * 1; p1[i] = (i - 128) * 4 }
for (let i = 192; i < 256; i++) { p0[i] = (256 - i) * 1; p1[i] = (256 - i) * 4 }
g_plasmaPal = [p0, p1]
g_plasmaTemp = new Uint8Array(256)
}
function scene3() {
// Do NOT clear VRAM here: scene1's final strobikstart() leaves the
// textbuffer in a white-out state (params.bright=255 saturates every
// cell). Preserving that fill — and letting the plasma loop's per-tick
// `bright -= 2` decay it — reproduces scene1.c → scene3.c's white-fade
// transition near-verbatim.
const ctx = aaCtx()
const params = g_aaPar
const font = aaFont()
params.dither = aa.AA_FLOYD_S
params.contrast = 0
params.randomval = 0
initPlasmaTables()
const W = aa.imgwidth(ctx)
const H = aa.imgheight(ctx)
const buf = ctx.imagebuffer
const tbl = g_plasmaTbl
const fw = font.width, fh = font.height
// Message list — straight from scene3.c's `text[]`. Empty strings act
// as pauses so the TTIME-spaced slots stay aligned with the C timing.
const TEXTS = [
"STILL", "WATCHING", "BB", "?", "GREAT",
"", "",
"NOW", "IT'S", "A GREAT", "TIME", "TO",
"FILL", "IN", "YOUR", "REGISTRATION", "CARD",
"",
"????",
"NEVER", "MORE",
"",
"(E.A. POE)",
"...",
]
// Plasma state
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0
let pnum = 0, dir = 1
let m = 0, n = 0, f = 0
// Inherit whatever bright value scene1 left behind (255 after the final
// strobikstart()); do_plasma decays it back to 0 — that's the fade-in.
let bright = params.bright | 0
// centerprint(x, y, size, color, text) — drives aa.print using the
// same "size is a divisor of image height" convention as the C code,
// but with the font's native aspect (so chars don't look squat).
function centerprint(cx, cy, size, color, text) {
if (!text.length) return
let height = H / size
let width = height * fw / fh
// Clip the per-glyph width so the line still fits horizontally.
// (REGISTRATION at size=2 would otherwise overflow on a 160px buffer.)
const maxTotalW = W * 0.95
if (width * text.length > maxTotalW) width = maxTotalW / text.length
if (width < 1 || height < 1) return
const w0 = width | 0
const h0 = height | 0
aa.print(ctx,
(cx - (w0 * text.length) / 2) | 0,
(cy - (h0 >>> 1)) | 0,
w0, h0, font, color | 0, text)
}
function drawMessage(text, stateUs) {
if (stateUs <= 0 || stateUs >= _PLASMA_MAXPOS) return
const pp = stateUs * Math.PI * 2 / _PLASMA_MAXPOS
const size = (1 + Math.cos(pp)) * 5 + 2 // 12 → 2 → 12
if (size <= 0) return
const ypos = (H - H * stateUs / _PLASMA_MAXPOS) | 0
const color = (Math.sin(pp / 2) * 255) | 0
centerprint(W >>> 1, ypos, size, color, text)
}
// Initial half-second pause to match `bbwait(500000)`.
// which is adjusted for TSVM timing
// or put global multiplier to waitMs(), the typewriter is also sluggish
if (!waitMs(500)) return
runScene(_PLASMA_DUR_US, _PLASMA_FRAMERATE, function(elapsed, total) {
// ── do_plasma(step=1) ────────────────────────────────────────────
// Dim the global brightness as we approach the end of the scene.
const closing = (total - elapsed) < (128 * 1000000 / _PLASMA_FRAMERATE)
bright -= 2
if (!closing && bright < 0) bright = 0
params.bright = bright
// Palette cross-fade.
f += 1
if (f > 64) {
f = 0
m = n
n = (Math.random() * 2) | 0
}
const pa = g_plasmaPal[n], pb = g_plasmaPal[m], tp = g_plasmaTemp
for (let j = 0; j < 256; j++) {
tp[j] = (pb[j] + ((pa[j] - pb[j]) * f / 64)) & 0xFF
}
// Advance the scroll positions (uchar wrap).
pos1 = (pos1 - 4 - ((Math.random() * 2) | 0)) & 0xFF
pos3 = (pos3 + 4 + ((Math.random() * 1) | 0)) & 0xFF
pos2 = (pos2 - ((Math.random() * 2) | 0)) & 0xFF
pos4 = (pos4 - ((Math.random() * 2) | 0)) & 0xFF
pnum += dir
if (pnum > _PLASMA_ZTABSIZE - 2) dir = -1
else if (pnum <= 0) dir = +1
// ── draw_plasma() ────────────────────────────────────────────────
const tblBase = pnum * 256
let p3 = pos3, p4 = pos4
for (let i = 0; i < W; i++) {
let p1 = pos1
let p2 = pos2
const vi = tbl[tblBase + (i & 0xFF)]
const v3 = tbl[tblBase + p3]
const v4 = tbl[tblBase + p4]
for (let j = 0; j < H; j++) {
const vj = tbl[tblBase + (j & 0xFF)]
const color = tbl[tblBase + p1] + tbl[tblBase + p2] + v3 + v4 + vi + vj
buf[j * W + i] = color & 0xFF
p1 = (p1 + 3) & 0xFF
p2 = (p2 + 1) & 0xFF
}
p3 = (p3 + 2) & 0xFF
p4 = (p4 + 3) & 0xFF
}
// Messages — each slot fires `_PLASMA_STIME + i*_PLASMA_TTIME` µs in.
for (let i = 0; i < TEXTS.length; i++) {
if (!TEXTS[i]) continue
const stateUs = elapsed - (_PLASMA_STIME + i * _PLASMA_TTIME)
drawMessage(TEXTS[i], stateUs)
}
// Re-map every pixel through the cross-faded palette as we render.
aa.renderpalette(ctx, g_plasmaTemp, params)
aa.flush(ctx)
})
params.bright = 0
setFG(WHITE)
if (g_quit) return
con.clear()
}
// ============================================================================
// SCENE 4 — near-verbatim port of scene4.c
//
// Five textbuffer phases (invader build-up, swaying march, explosion, drop-
// down to "\@@/", drop-down to "\--/") followed by an image-buffer fire
// engine. Each text phase is a series of aa.puts + bbflushwait — the
// invaders, cannon, and explosion ASCII are byte-identical to scene4.c.
//
// Fire engine:
// - tableLUT[i] = (i - minus) / 5 if i > minus else 0
// - firemain(): each pixel := table[sum of 3 neighbours one row below +
// 2 neighbours two rows below]
// - drawfire(n) seeds the row right below the visible area with random
// intensity bursts capped by `height` (which ramps up/down based on the
// remaining scene time), then runs firemain() to propagate the flame
// upward and decays params.bright by 12.
// The image buffer is reallocated +4 rows tall so firemain can read past the
// visible bottom without out-of-bounds; we use a swap-in scratch buffer.
// ============================================================================
function scene4() {
const ctx = aaCtx(), font = aaFont()
const params = g_aaPar
const scrW = aa.scrwidth(ctx), scrH = aa.scrheight(ctx)
const imgW = aa.imgwidth(ctx), imgH = aa.imgheight(ctx)
clearScreen(); con.curs_set(0)
aa.cleartext(ctx)
aa.clear(ctx)
params.dither = aa.AA_FLOYD_S
params.bright = 0
params.contrast = 0
params.randomval = 0
g_drawptr = null
g_overlayText = ""
const N = 10
const N1 = 20
let n, wtime, x, y, p, q, d, k, i
// ── Phase 1: build a row of " ----" invaders one chunk at a time ────────
n = ((scrW - 5 - N1 + 5) / 6) | 0
wtime = (1.0 * 1000000 / n) | 0
for (x = 0; x < scrW - 5 - N1; x += 6) {
if (g_quit) return
for (y = 0; y < 10; y += 3)
aa.puts(ctx, x, y, aa.AA_NORMAL, " ----")
if (!bbflushwait(wtime)) return
}
// ── Phase 2: draw the cannon row "/~~\" sliding L→R ─────────────────────
n = ((scrW - 7 + 7) / 8) | 0
wtime = (1.0 * 1000000 / n) | 0
for (x = 0; x < scrW - 7; x += 8) {
if (g_quit) return
aa.puts(ctx, x, scrH - 3, aa.AA_NORMAL, "/~~\\")
if (!bbflushwait(wtime)) return
}
// ── Phase 3: " -oo-" fills in invader rows one stripe at a time ─────────
for (y = 0; y < 10; y += 3) {
if (g_quit) return
for (x = 0; x < scrW - 5 - N1; x += 6)
aa.puts(ctx, x, y, aa.AA_NORMAL, " -oo-")
if (!bbflushwait(0.1 * 1000000)) return
}
if (!bbflushwait(0.2 * 1000000)) return
// ── Phase 4: invader sway + cannon jitter at the bottom ─────────────────
// Three outer iterations (q = 0,2,4 entry → q ends at 6), each with two
// passes of N1 inner steps. The first pass shifts invaders right; the
// second shifts them back. The cannon "[^]" wobbles by rand()%3-1 each
// inner step.
p = (scrW / 2) | 0
d = k = 0
const clrinvaz = function() {
const limit = Math.min(15, scrH)
const tb = ctx.textbuffer, ab = ctx.attrbuffer
for (let j = 0; j < scrW * limit; j++) {
tb[j] = 0x20
ab[j] = aa.AA_NORMAL
}
}
for (q = 0; q < 5; q++) {
if (g_quit) return
clrinvaz()
for (i = 0; i < N1; i++) {
if (g_quit) return
d++; if (d > 8) { k ^= 1; d = 0 }
for (x = 0; x < scrW - 5 - N1; x += 6)
for (y = 0; y < 10; y += 3)
aa.puts(ctx, x + i, y + q, aa.AA_NORMAL, k ? " \\oo/ " : " /OO\\ ")
aa.puts(ctx, p, scrH - 1, aa.AA_NORMAL, " [^] ")
p += ((Math.random() * 3) | 0) - 1
if (!bbflushwait(0.02 * 1000000)) return
}
q++
clrinvaz()