forked from flupe/jibniz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjibniz.js
More file actions
707 lines (547 loc) · 17.2 KB
/
Copy pathjibniz.js
File metadata and controls
707 lines (547 loc) · 17.2 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
/*** Based on jibniz by flupe: https://github.com/flupe/jibniz
--- (c) Copyright 2021 - MIT License ---
***/
(function (factory) {
if (typeof module != "undefined" && typeof module.exports != "undefined") {
module.exports = factory();
} else {
window.jibniz = factory();
}
})(function () {
"use strict";
const coord = (v) => (v - 128) << 9;
// In the official IBNIZ documentation, it states
// - the audio stack is 65536 words long
// - regardless of sampling rate, audio stack is one second long
// - default sampling rate is 61440
// to make it easier, we set the sampling rate to the length of the stack
const SAMPLE_RATE = 65536;
class Stack {
constructor(buffer, offset, size) {
this.buffer = buffer;
this.memory = new Int32Array(buffer, offset << 2, size);
this.mask = size - 1;
this.top = 0;
}
push(...values) {
values.forEach((x) => {
this.memory[this.top] = x;
this.top = (this.top + 1) & this.mask;
});
}
pop(x) {
return this.memory[(this.top = (this.top + this.mask) & this.mask)];
}
peek(n) {
let r = [];
let p = this.top;
while (n--) {
p = (p + this.mask) & this.mask;
r.push(this.memory[p]);
}
return r;
}
reset() {
this.top = 0;
}
clear() {
this.memory.fill(0);
}
}
class VM {
constructor() {
this.memory = new Int32Array(1 << 20);
let buffer = (this.buffer = this.memory.buffer);
this.aRStack = new Stack(buffer, 0xc8000, 0x4000);
this.vRStack = new Stack(buffer, 0xcc000, 0x4000);
this.aStack = new Stack(buffer, 0xd0000, 0x10000);
this.vStack = new Stack(buffer, 0xe0000, 0x20000);
this.time = 0;
this.mode = "T";
this.fragments = null;
}
reset() {
this.memory.fill(0);
this.vStack.reset();
this.vRStack.reset();
this.aStack.reset();
this.aRStack.reset();
this.time = 0;
}
step(userin = 0) {
if (!this.fragments) return;
let f = this.fragments.video[this.mode];
if (this.mode == "TYX") {
for (let y = 0; y < 256; y++) {
for (let x = 0; x < 256; x++) {
// TODO(flupe): handle both T and TYX modes
this.vStack.push(this.time << 16, coord(y), coord(x));
f(
this.memory,
this.vStack,
this.vRStack,
this.time << 16,
coord(x),
coord(y),
userin
);
}
}
} else {
for (let y = 0; y < 256; y++) {
for (let x = 0; x < 256; x++) {
// TODO(flupe): handle both T and TYX modes
let w = (this.time << 16) | (y << 8) | x;
this.vStack.push(w);
f(this.memory, this.vStack, this.vRStack, w, userin);
}
}
}
// HACKY
// update audio every second
// 60 frames per second
// 0x1000 samples per second
// 0x1000 / 60 samples per frame
if (this.time % 60 == 0) {
let t = this.time;
let f = this.fragments.audio;
for (let k = 0; k < 0x10000; k++) {
let v = (k * 60) & 0xffff;
let t = (this.time + (k * 60) / 0x10000) | 0;
let w = (t << 16) | v;
this.aStack.push(w);
f(this.memory, this.aStack, this.aRStack, w, userin);
}
}
this.time++;
}
}
class Console extends VM {
constructor(canvas, audio) {
super();
this.canvas = canvas;
this.audio = audio;
//cvs = this.domElement = cvs || document.createElement("canvas");
//cvs.width = cvs.height = 256;
this.running = false;
this.videoPages = [
new Uint8Array(this.buffer, 0xe0000 << 2, 0x40000),
new Uint8Array(this.buffer, 0xf0000 << 2, 0x40000),
];
this.x = 128;
this.y = 128;
}
async init() {
let gl = (this.gl = this.canvas.getContext("webgl"));
function loadShader(src, type) {
let shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
let error = `Error occured while compiling shader: ${gl.getShaderInfoLog(
shader
)}`;
gl.deleteShader(shader);
throw error;
}
return shader;
}
let vertSrc = `
attribute vec2 pos;
varying lowp vec2 uv;
void main() {
gl_Position = vec4(pos, 0.0, 1.0);
uv = vec2((pos.x + 1.0) / 2.0, (1.0 - pos.y) / 2.0);
}
`;
let fragSrc = `
precision lowp float;
varying lowp vec2 uv;
uniform sampler2D page;
void main() {
vec4 tex = texture2D(page, uv);
float y = tex.g;
float u = tex.b <= 0.5 ? tex.b : -(1.0 - tex.b);
float v = tex.a <= 0.5 ? tex.a : -(1.0 - tex.a);
y = 1.1643 * (y - 0.0625);
float r = clamp(y+1.5958*v, 0.0, 1.0);
float g = clamp(y-0.39173*u-0.81290*v,0.0, 1.0);
float b = clamp(y+2.017*u, 0.0, 1.0);
gl_FragColor = vec4(r,g,b,1.0);
}
`;
let vert = loadShader(vertSrc, gl.VERTEX_SHADER);
let frag = loadShader(fragSrc, gl.FRAGMENT_SHADER);
let prog = (this.program = gl.createProgram());
gl.attachShader(prog, vert);
gl.attachShader(prog, frag);
gl.linkProgram(prog);
let posAttribLoc = gl.getAttribLocation(prog, "pos");
let positions = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positions);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0]),
gl.STATIC_DRAW
);
gl.vertexAttribPointer(posAttribLoc, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(posAttribLoc);
let tex = (this.texture = gl.createTexture());
let texLoc = gl.getUniformLocation(prog, "page");
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.useProgram(prog);
gl.uniform1i(texLoc, 0);
// wip audio
let actx = (this.audioCtx = document.querySelector(
"a-resonance-audio-room"
).components["resonance-audio-room"].audioContext);
await console.log("wait...");
this.streamDestination = this.audioCtx.createMediaStreamDestination();
this.source = this.audioCtx.createBufferSource();
this.myArrayBuffer = this.audioCtx.createBuffer(1, 65536 * 1, 65536);
this.source.buffer = this.myArrayBuffer;
this.source.connect(this.streamDestination);
this.source.start();
/*
await this.audioCtx.audioWorklet.addModule("processor.js");
this.ibnizWorker = new AudioWorkletNode(this.audioCtx, "processor");
this.ibnizWorker.connect(this.streamDestination);
*/
this.stream = this.streamDestination.stream;
this.audio.setAttribute("resonance-audio-src", "src", this.stream);
}
run() {
this.running = true;
this.initTime = this.time;
this.start = performance.now();
let last = this.start;
let step = () => {
if (!this.running) return;
let now = performance.now();
let elapsed = now - this.start;
let dt = (now - last) / 1000;
last = now;
this.fps = (1 / dt) | 0;
this.time = (this.initTime + (elapsed / 1000) * 60) & 0xffff;
window.requestAnimationFrame(step);
this.step();
};
window.requestAnimationFrame(step);
//setInterval(step, 12);
}
step() {
super.step((this.y << 8) | this.x);
let video = this.videoPages[(this.vStack.top >> 16) ^ 1];
let gl = this.gl;
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
256,
256,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
video
);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
// HACKY
if (this.time % 60 == 1) {
// This gives us the actual ArrayBuffer that contains the data
let nowBuffering = this.myArrayBuffer.getChannelData(0);
for (let i = 0; i < this.myArrayBuffer.length; i++) {
nowBuffering[i] =
((this.aStack.memory[i] & 0xffff) - 0x8000) / 0x8000;
}
//this.ibnizWorker.port.postMessage(nowBuffering);
this.source = this.audioCtx.createBufferSource();
this.source.buffer = this.myArrayBuffer;
this.source.connect(this.streamDestination);
this.source.start();
}
}
reset() {
this.time = 0;
this.initTime = 0;
this.start = performance.now();
super.reset();
}
install(program) {
this.fragments = program.fragments;
this.memory.set(program.data.mem);
}
}
class Program {
constructor(source) {
let { fragments, data } = compile(source);
this.fragments = fragments;
this.data = data;
}
}
let sincr = "sn=sn+1&sm;";
let sdecr = "sn=sn+sm&sm;";
let rincr = "rn=rn+1&rm;";
let rdecr = "rn=rn+rm&rm;";
let whereami = {
tyx: "S[sn]=t;" + "S[sn=sn+1&sm]=y;" + "S[sn=sn+1&sm]=x;" + sincr,
t: "S[sn]=t;" + sincr,
};
let codes = {
"+": sdecr + "a=sn+sm&sm;" + "S[a]=S[a]+S[sn];",
"-": sdecr + "a=sn+sm&sm;" + "S[a]=S[a]-S[sn];",
"*": sdecr + "a=sn+sm&sm;" + "S[a]=(S[a]/65536)*(S[sn]/65536)*65536|0;",
"/": sdecr + "a=sn+sm&sm;" + "S[a]=S[sn]==0?0:(S[a]*65536)/S[sn];",
"%": sdecr + "a=sn+sm&sm;" + "S[a]=S[sn]==0?0:S[a]%S[sn];",
q: "a=sn+sm&sm;" + "S[a]=S[a]>0?Math.sqrt(S[a]/65536)*65536|0:0;",
"&": sdecr + "a=sn+sm&sm;" + "S[a]=S[a]&S[sn];",
"|": sdecr + "a=sn+sm&sm;" + "S[a]=S[a]|S[sn];",
"^": sdecr + "a=sn+sm&sm;" + "S[a]=S[a]^S[sn];",
r:
sdecr +
"a=sn+sm&sm;" +
"b=S[sn]>>>16;" +
"c=S[a];" +
"S[a]=(c>>>b)|(c<<(32-b));",
l: sdecr + "a=sn+sm&sm;" + "S[a]=S[a]<<(S[sn]>>>16);",
"~": "a=sn+sm&sm;" + "S[a]=~S[a];",
s: "a=sn+sm&sm;" + "S[a]=Math.sin(S[a]*Math.PI/32768)*65536;",
a:
sdecr +
"a=sn+sm&sm;" +
"S[a]=Math.atan2(S[sn]/65536,S[a]/65536)/Math.PI*32768;",
"<": "a=sn+sm&sm;" + "if(S[a]>0)S[a]=0;",
">": "a=sn+sm&sm;" + "if(S[a]<0)S[a]=0;",
"=": "a=sn+sm&sm;" + "S[a]=(S[a]==0)<<16;",
d: "S[sn]=S[sn+sm&sm];" + sincr,
p: sdecr,
x: "a=sn+sm&sm;" + "b=a+sm&sm;" + "c=S[a];S[a]=S[b];S[b]=c;",
v:
"a=sn+sm&sm;" +
"b=a+sm&sm;" +
"c=b+sm&sm;" +
"d=S[a];S[a]=S[c];S[c]=S[b];S[b]=d;",
")": "a=sn+sm&sm;" + "S[a]=S[a+sm-(S[a]>>>16)&sm];",
"(": sdecr + "a=S[sn]>>16;" + sdecr + "S[sn+sm-a&sm]=S[sn];",
T: "break;",
"@": "a=sn+sm&sm;" + "b=S[a];" + "S[a]=M[(b>>>16)|(b<<16)];",
"!": "b=S[sn=sn+sm&sm];" + "a=S[sn=sn+sm&sm];" + "M[(b>>>16)|(b<<16)]=a;",
L:
"a=--R[rn+(rm<<1)&rm];" +
"if(a!=0){i=R[rn+rm&rm];continue}" +
"else " +
rdecr +
rdecr,
i: "a=R[rn+(rm<<1)&rm];" + "S[sn]=(a>>>16)|(a<<16);" + sincr,
j: "a=R[rn+(rm<<2)&rm];" + "S[sn]=(a>>>16)|(a<<16);" + sincr,
"]": sdecr + "if(S[sn]!=0){i=R[rn+rm&rm];continue}" + "else " + rdecr,
J: sdecr + "i=S[sn];continue;",
"}": rdecr + "i=R[rn];continue;",
R: rdecr + "S[sn]=R[rn];" + sincr,
P: sdecr + "R[rn]=S[sn];" + rincr,
U: "S[sn]=U;" + sincr,
};
let hexchars = "0123456789ABCDEF".split("");
let isHexaDecimal = (c) => hexchars.includes(c);
let isBlank = (c) => c == " " || c == "," || c == "\n";
let dataModes = {
b: { len: 1, mask: 1 },
q: { len: 2, mask: 3 },
o: { len: 3, mask: 7 },
h: { len: 4, mask: 15 },
};
function parse(src) {
let pos = 0;
let len = src.length;
let body = [];
let video = null;
let audio = null;
let c;
let data = [];
let currentValues = [];
let currentMode = dataModes.h;
while (pos < len) {
c = src[pos++];
if (isBlank(c)) continue;
if (c == "\\") {
while (pos < len && src[pos++] != "\n") {}
continue;
} else if (isHexaDecimal(c) || c == ".") {
let imm = 0;
if (c != ".") {
imm = parseInt(c, 16);
while (pos < len && isHexaDecimal(src[pos]))
imm = ((imm & 0xffff) << 4) | parseInt(src[pos++], 16);
imm <<= 16;
c = src[pos];
if (c == ".") pos++;
}
if (c == ".") {
let i = 4,
frac = 0;
for (; i > 0 && isHexaDecimal(src[pos]); i--)
frac = (frac << 4) | parseInt(src[pos++], 16);
while (pos < len && isHexaDecimal(src[pos])) pos++;
imm |= frac << (i << 2);
}
body.push(imm);
}
// parsing data segment
else if (c == "$") {
while (pos < len) {
c = src[pos++];
if (dataModes[c]) {
if (currentValues.length) {
data.push({ mode: currentMode, values: currentValues });
currentValues = [];
}
currentMode = dataModes[c];
} else if (isHexaDecimal(c)) {
currentValues.push(parseInt(c, 16) & currentMode.mask);
}
}
break;
} else if (c == "M") {
video = body;
body = [];
} else body.push({ op: c, pos: pos - 1 });
}
if (video) {
audio = body;
findSkips(video);
findSkips(audio);
} else {
video = audio = body;
findSkips(body);
}
data.push({ mode: currentMode, values: currentValues });
return { video, audio, data };
}
function findSkips(tokens) {
let len = tokens.length;
// find skip points
for (let i = 0; i < len; i++) {
let t = tokens[i];
if (typeof t == "number") continue;
let c = t.op;
let seek0 = null;
let seek1 = null;
if (c == "?") {
seek0 = ":";
seek1 = ";";
}
if (c == ":") {
seek0 = ";";
}
if (c == "{") {
seek0 = "}";
}
if (seek0) {
for (let j = i + 1; j < len; j++) {
let c = tokens[j];
if (typeof c != "number" && (c.op == seek0 || c.op == seek1)) {
t.skip = j + 1;
break;
}
}
}
}
}
function compile(src) {
let { video, audio, data } = parse(src);
let nbits = data.reduce(
(n, { values, mode }) => n + values.length * mode.len,
0
);
let nbytes = (nbits + 7) >> 3;
// hack because of endianness
let mem = new Uint32Array(new ArrayBuffer(nbytes));
let cb = 0,
cv = 0,
cl = 0;
data.forEach(({ values, mode }) => {
values.forEach((v) => {
cv = (cv << mode.len) | v;
cl += mode.len;
if (cl > 32) {
mem[cb++] = cv >> (cl -= 32);
}
});
});
mem[cb] = cv << (32 - cl);
let videoTYX = codegen(video, whereami.tyx);
let videoT = codegen(video, whereami.t);
let audioT = codegen(audio, whereami.t);
return {
fragments: {
video: {
T: new Function("M", "VS", "RS", "t", "U", videoT),
TYX: new Function("M", "VS", "RS", "t", "x", "y", "U", videoTYX),
},
audio: new Function("M", "VS", "RS", "t", "U", audioT),
},
data: { mem, nbits },
};
}
function codegen(tokens, whereami) {
let body = `
let l=true,
i=0,
S=VS.memory,
sm=VS.mask,
sn=VS.top,
R=RS.memory,
rm=RS.mask,
rn=RS.top
while(l) {
switch(i) {`;
let len = tokens.length;
let instructions = tokens.map((tok, k) => {
let sub = `\ncase ${k}:`;
if (typeof tok == "number") sub += "S[sn]=" + tok + ";" + sincr;
else if (codes[tok.op]) sub += codes[tok.op];
else if (tok.op == "w") sub += whereami;
else if (tok.op == "?") {
if (!tok.skip) sub += sdecr + "if(S[sn]==0)break;";
else sub += sdecr + `if(S[sn]==0){i=${tok.skip};continue};`;
} else if (tok.op == ":") {
if (!tok.skip) sub = "break;" + sub;
else sub = `i=${tok.skip};continue;` + sub;
} else if (tok.op == "{") {
if (!tok.skip) sub += sdecr + "M[S[sn]>>16]=" + (k + 1) + ";break;";
else
sub +=
sdecr + "M[S[sn]>>16]=" + (k + 1) + ";" + `i=${tok.skip};continue;`;
} else if (tok.op == "V") {
sub +=
sdecr + "i=M[S[sn]>>16];" + `R[rn]=${k + 1};` + rincr + "continue;";
} else if (tok.op == "X") {
sub +=
sdecr +
"a=S[sn];" +
"R[rn]=(a>>>16)|(a<<16);" +
rincr +
"R[rn]=" +
(k + 1) +
";" +
rincr;
} else if (tok.op == "[") {
sub += "R[rn]=" + (k + 1) + ";" + rincr;
} else return "";
return sub;
});
body += instructions.join("");
body += `
}
break
}
VS.top=sn
RS.top=rn`;
return body;
}
return { Stack, VM, Program, Console };
});