-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCpcVm.js
3714 lines (3169 loc) · 101 KB
/
CpcVm.js
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
// CpcVm.js - CPC Virtual Machine
// (c) Marco Vieth, 2019
// https://benchmarko.github.io/CPCBasic/
//
"use strict";
var Utils, CpcVmRsx, Random;
if (typeof require !== "undefined") {
/* eslint-disable global-require */
Utils = require("./Utils.js");
CpcVmRsx = require("./CpcVmRsx.js");
Random = require("./Random.js");
/* eslint-enable global-require */
}
function CpcVm(options) {
this.vmInit(options);
}
CpcVm.prototype = {
iFrameTimeMs: 1000 / 50, // 50 Hz => 20 ms
iTimerCount: 4, // number of timers
iSqTimerCount: 3, // sound queue timers
iStreamCount: 10, // 0..7 window, 8 printer, 9 cassette
iMinHimem: 370,
iMaxHimem: 42747, // high memory limit (42747 after symbol after 256)
mWinData: [ // window data for mode mode 0,1,2,3 (we are counting from 0 here)
{
iLeft: 0,
iRight: 19,
iTop: 0,
iBottom: 24
},
{
iLeft: 0,
iRight: 39,
iTop: 0,
iBottom: 24
},
{
iLeft: 0,
iRight: 79,
iTop: 0,
iBottom: 24
},
{
iLeft: 0, // mode 3 not available on CPC
iRight: 79,
iTop: 0,
iBottom: 49
}
],
mUtf8ToCpc: { // needed for UTF-8 character data in openin / input#9
8364: 128,
8218: 130,
402: 131,
8222: 132,
8230: 133,
8224: 134,
8225: 135,
710: 136,
8240: 137,
352: 138,
8249: 139,
338: 140,
381: 142,
8216: 145,
8217: 146,
8220: 147,
8221: 148,
8226: 149,
8211: 150,
8212: 151,
732: 152,
8482: 153,
353: 154,
8250: 155,
339: 156,
382: 158,
376: 159
},
vmInit: function (options) {
var i;
this.options = options || {};
this.fnOpeninHandler = this.vmOpeninCallback.bind(this);
this.fnCloseinHandler = this.vmCloseinCallback.bind(this);
this.fnCloseoutHandler = this.vmCloseoutCallback.bind(this);
this.fnLoadHandler = this.vmLoadCallback.bind(this);
this.fnRunHandler = this.vmRunCallback.bind(this);
this.oCanvas = this.options.canvas;
this.oKeyboard = this.options.keyboard;
this.oSound = this.options.sound;
this.oVariables = this.options.variables;
this.rsx = new CpcVmRsx(this);
this.oRandom = new Random();
this.oStop = {
sReason: "", // stop reason
iPriority: 0, // stop priority (higher number means higher priority which can overwrite lower priority)
oParas: null // optional stop parameters
};
// special stop reasons and priorities:
// "timer": 20 (timer expired)
// "waitFrame": 40 (FRAME command: wait for frame fly)
// "waitKey": 41 (wait for key; higher priority that waitFrame)
// "waitSound": 43 (wait for sound queue)
// "waitInput": 45 (wait for input: INPUT, LINE INPUT, RANDOMIZE without parameter)
// "fileCat": 45 (CAT)
// "fileDir": 45 (|DIR)
// "fileEra": 45 (|ERA)
// "fileRen": 45 (|REN)
// "error": 50 (BASIC error, ERROR command)
// "onError": 50 (ON ERROR GOTO active, hide error)
// "stop": 60 (STOP or END command)
// "break": 80 (break pressed)
// "escape": 85 (escape key, set in controller)
// "renumLines": 85 (RENUMber program)
// "deleteLines": 90,
// "end": 90 (end of program)
// "list": 90,
// "fileLoad": 90 (CHAIN, CHAIN MERGE, LOAD, MERGE, OPENIN, RUN)
// "fileSave": 90 (OPENOUT, SAVE)
// "reset": 90 (reset system)
// "run": 90
this.aInputValues = []; // values to input into script
this.oInFile = {}; // file handling
this.oOutFile = {}; // file handling
// "bOpen": File open flag
// "sCommand": Command that started the file open (in: chain, chainMerge, load, merge, openin, run; out: save, openput)
// "sName": File name
// "sType": File type: A, B, P, T
// "iStart": start address of data
// "iLength": length of data
// "iEntry": entry address (save)
// "iLine": ?
// "aFileData": File contents for (LINE) INPUT #9; PRINT #9, WRITE #9
// "fnFileCallback": Callback for stop reason "fileLoad", "fileSave"
// "iLine": run line (CHAIN, CHAIN MERGE)
// "iFirst": first line to delete (CHAIN MERGE)
// "iLast": last line to delete (CHAIN MERGE)
this.iInkeyTime = 0; // if >0, next time when inkey$ can be checked without inserting "waitFrame"
this.aGosubStack = []; // stack of line numbers for gosub/return
this.aMem = []; // for peek, poke
this.aData = []; // array for BASIC data lines (continuous)
this.aWindow = []; // window data for window 0..7,8,9
for (i = 0; i < this.iStreamCount; i += 1) {
this.aWindow[i] = {};
}
this.aTimer = []; // BASIC timer 0..3 (3 has highest priority)
for (i = 0; i < this.iTimerCount; i += 1) {
this.aTimer[i] = {};
}
this.aSoundData = [];
this.aSqTimer = []; // Sound queue timer 0..2
for (i = 0; i < this.iSqTimerCount; i += 1) {
this.aSqTimer[i] = {};
}
this.aCrtcData = [];
},
vmReset: function () {
this.iStartTime = Date.now();
this.oRandom.init();
this.lastRnd = 0;
this.iNextFrameTime = Date.now() + this.iFrameTimeMs; // next time of frame fly
this.iTimeUntilFrame = 0;
this.iStopCount = 0;
this.iLine = 0; // current line number (or label)
this.iStartLine = 0; // line to start
this.iErrorGotoLine = 0;
this.iErrorResumeLine = 0;
this.iBreakGosubLine = 0;
this.iBreakResumeLine = 0;
this.aInputValues.length = 0;
this.vmResetFileHandling(this.oInFile);
this.vmResetFileHandling(this.oOutFile);
this.vmResetControlBuffer();
this.sOut = ""; // console output
this.vmStop("", 0, true);
this.vmResetData();
this.iErr = 0; // last error code
this.iErl = 0; // line of last error
this.aGosubStack.length = 0;
this.bDeg = false; // degree or radians
this.bTron = this.options.tron || false; // trace flag
this.iTronLine = 0; // last trace line
this.aMem.length = 0; // clear memory (for PEEK, POKE)
this.iRamSelect = 0; // for banking with 16K banks in the range 0x4000-0x7fff (0=default; 1...=additional)
this.iScreenPage = 3; // 16K screen page, 3=0xc000..0xffff
this.iCrtcReg = 0;
this.aCrtcData.length = 0;
this.iMinCharHimem = this.iMaxHimem;
this.iMaxCharHimem = this.iMaxHimem;
this.iHimem = this.iMaxHimem;
this.iMinCustomChar = 256;
this.symbolAfter(240); // set also iMinCustomChar
this.vmResetTimers();
this.iTimerPriority = -1; // priority of running task: -1=low (min priority to start new timers)
this.iZone = 13; // print tab zone value
this.defreal("a-z"); // init var types
this.iMode = null;
this.vmResetWindowData(true); // reset all, including pen and paper
this.width(132); // set default printer width
this.mode(1); // including vmResetWindowData() without pen and paper
this.oCanvas.reset();
this.oKeyboard.reset();
this.oSound.reset();
this.aSoundData.length = 0;
this.iInkeyTime = 0; // if >0, next time when inkey$ can be checked without inserting "waitFrame"
},
vmResetTimers: function () {
var oData = {
iLine: 0, // gosub line when timer expires
bRepeat: false, // flag if timer is repeating (every) or one time (after)
iIntervalMs: 0, // interval or timeout
bActive: false, // flag if timer is active
iNextTimeMs: 0, // next expiration time
bHandlerRunning: false, // flag if handler (subroutine) is running
iStackIndexReturn: 0, // index in gosub stack with return, if handler is running
iSavedPriority: 0 // priority befora calling the handler
},
aTimer = this.aTimer,
aSqTimer = this.aSqTimer,
i;
for (i = 0; i < this.iTimerCount; i += 1) {
Object.assign(aTimer[i], oData);
}
// sound queue timer
for (i = 0; i < this.iSqTimerCount; i += 1) {
Object.assign(aSqTimer[i], oData);
}
},
vmResetWindowData: function (bResetPenPaper) {
var oWinData = this.mWinData[this.iMode],
oData = {
iPos: 0, // current text position in line
iVpos: 0,
bTextEnabled: true, // text enabled
bTag: false, // tag=text at graphics
bTransparent: false, // transparent mode
bCursorOn: false, // system switch
bCursorEnabled: true // user switch
},
oPrintData = {
iPos: 0,
iVpos: 0,
iRight: 132 // override
},
oCassetteData = {
iPos: 0,
iVpos: 0,
iRight: 255 // override
},
i, oWin;
if (bResetPenPaper) {
oData.iPen = 1;
oData.iPaper = 0;
}
for (i = 0; i < this.aWindow.length - 2; i += 1) { // for window streams
oWin = this.aWindow[i];
Object.assign(oWin, oWinData, oData);
}
oWin = this.aWindow[8]; // printer
Object.assign(oWin, oWinData, oPrintData);
oWin = this.aWindow[9]; // cassette
Object.assign(oWin, oWinData, oCassetteData);
},
vmResetControlBuffer: function () {
this.sPrintControlBuf = ""; // collected control characters for PRINT
},
vmResetFileHandling: function (oFile) {
oFile.bOpen = false;
oFile.sCommand = ""; // to be sure
},
vmResetData: function () {
this.aData.length = 0; // array for BASIC data lines (continuous)
this.iData = 0; // current index
this.oDataLineIndex = { // line number index for the data line buffer
0: 0 // for line 0: index 0
};
},
vmResetInks: function () {
this.oCanvas.setDefaultInks();
this.oCanvas.setSpeedInk(10, 10);
},
vmReset4Run: function () {
var iStream = 0;
this.vmResetInks();
this.clearInput();
this.closein();
this.closeout();
this.cursor(iStream, 0);
},
vmGetAllVariables: function () { // called from JS program
return this.oVariables.getAllVariables();
},
vmSetStartLine: function (iLine) {
this.iStartLine = iLine;
},
vmOnBreakContSet: function () {
return this.iBreakGosubLine < 0; // on break cont
},
vmOnBreakHandlerActive: function () {
return this.iBreakResumeLine;
},
vmEscape: function () {
var bStop = true;
if (this.iBreakGosubLine > 0) { // on break gosub n
if (!this.iBreakResumeLine) { // do not nest break gosub
this.iBreakResumeLine = this.iLine;
this.gosub(this.iLine, this.iBreakGosubLine);
}
bStop = false;
} else if (this.iBreakGosubLine < 0) { // on break cont
bStop = false;
} // else: on break stop
return bStop;
},
vmAssertNumber: function (n, sErr) {
if (typeof n !== "number") {
throw this.vmComposeError(Error(), 13, sErr + " " + n); // Type mismatch
}
},
vmAssertString: function (s, sErr) {
if (typeof s !== "string") {
throw this.vmComposeError(Error(), 13, sErr + " " + s); // Type mismatch
}
},
// round number (-2^31..2^31) to integer; throw error if no number
vmRound: function (n, sErr) { // optional sErr
this.vmAssertNumber(n, sErr || "?");
return (n >= 0) ? (n + 0.5) | 0 : (n - 0.5) | 0; // eslint-disable-line no-bitwise
},
/*
// round for comparison TODO
vmRound4Cmp: function (n) {
var nAdd = (n >= 0) ? 0.5 : -0.5;
return ((n * 1e12 + nAdd) | 0) / 1e12; // eslint-disable-line no-bitwise
},
*/
vmInRangeRound: function (n, iMin, iMax, sErr) { // optional sErr
n = this.vmRound(n, sErr);
if (n < iMin || n > iMax) {
Utils.console.warn("vmInRangeRound: number not in range:", iMin + "<=" + n + "<=" + iMax);
throw this.vmComposeError(Error(), n < -32768 || n > 32767 ? 6 : 5, sErr + " " + n); // 6=Overflow, 5=Improper argument
}
return n;
},
vmRound2Complement: function (n, err) {
n = this.vmInRangeRound(n, -32768, 65535, err);
if (n < 0) {
n += 65536;
}
return n;
},
vmDetermineVarType: function (sVarType) { // also used in controller
var sType = (sVarType.length > 1) ? sVarType.charAt(1) : this.oVariables.getVarType(sVarType.charAt(0));
return sType;
},
vmAssertNumberType: function (sVarType) {
var sType = this.vmDetermineVarType(sVarType);
if (sType !== "I" && sType !== "R") { // not integer or real?
throw this.vmComposeError(Error(), 13, "type " + sType); // "Type mismatch"
}
},
// format a value for assignment to a variable with type determined from sVarType
vmAssign: function (sVarType, value) {
var sType = this.vmDetermineVarType(sVarType);
if (sType === "R") { // real
this.vmAssertNumber(value, "=");
} else if (sType === "I") { // integer
value = this.vmRound(value, "="); // round number to integer
} else if (sType === "$") { // string
if (typeof value !== "string") {
Utils.console.warn("vmAssign: expected string but got:", value);
throw this.vmComposeError(Error(), 13, "type " + sType + "=" + value); // "Type mismatch"
}
}
return value;
},
vmGetError: function (iErr) { // BASIC error numbers
var aErrors = [
"Improper argument", // 0
"Unexpected NEXT", // 1
"Syntax Error", // 2
"Unexpected RETURN", // 3
"DATA exhausted", // 4
"Improper argument", // 5
"Overflow", // 6
"Memory full", // 7
"Line does not exist", // 8
"Subscript out of range", // 9
"Array already dimensioned", // 10
"Division by zero", // 11
"Invalid direct command", // 12
"Type mismatch", // 13
"String space full", // 14
"String too long", // 15
"String expression too complex", // 16
"Cannot CONTinue", // 17
"Unknown user function", // 18
"RESUME missing", // 19
"Unexpected RESUME", // 20
"Direct command found", // 21
"Operand missing", // 22
"Line too long", // 23
"EOF met", // 24
"File type error", // 25
"NEXT missing", // 26
"File already open", // 27
"Unknown command", // 28
"WEND missing", // 29
"Unexpected WEND", // 30
"File not open", // 31,
"Broken", // 32 "Broken in" (derr=146: xxx not found)
"Unknown error" // 33...
],
sError = aErrors[iErr] || aErrors[aErrors.length - 1]; // Unknown error
return sError;
},
vmGotoLine: function (line, sMsg) {
if (Utils.debug > 5) {
if (typeof line === "number" || Utils.debug > 7) { // non-number labels only in higher debug levels
Utils.console.debug("dvmGotoLine:", sMsg + ": " + line);
}
}
this.iLine = line;
},
fnCheckSqTimer: function () {
var bTimerExpired = false,
oTimer, i;
if (this.iTimerPriority < 2) {
for (i = 0; i < this.iSqTimerCount; i += 1) {
oTimer = this.aSqTimer[i];
// use oSound.sq(i) and not this.sq(i) since that would reset onSq timer
if (oTimer.bActive && !oTimer.bHandlerRunning && (this.oSound.sq(i) & 0x07)) { // eslint-disable-line no-bitwise
this.gosub(this.iLine, oTimer.iLine);
oTimer.bHandlerRunning = true;
oTimer.iStackIndexReturn = this.aGosubStack.length;
oTimer.bRepeat = false; // one shot
bTimerExpired = true;
break; // found expired timer
}
}
}
return bTimerExpired;
},
vmCheckTimer: function (iTime) {
var bTimerExpired = false,
iDelta, oTimer, i;
for (i = this.iTimerCount - 1; i > this.iTimerPriority; i -= 1) { // check timers starting with highest priority first
oTimer = this.aTimer[i];
if (oTimer.bActive && !oTimer.bHandlerRunning && iTime > oTimer.iNextTimeMs) { // timer expired?
this.gosub(this.iLine, oTimer.iLine);
oTimer.bHandlerRunning = true;
oTimer.iStackIndexReturn = this.aGosubStack.length;
oTimer.iSavedPriority = this.iTimerPriority;
this.iTimerPriority = i;
if (!oTimer.bRepeat) { // not repeating
oTimer.bActive = false;
} else {
iDelta = iTime - oTimer.iNextTimeMs;
oTimer.iNextTimeMs += oTimer.iIntervalMs * Math.ceil(iDelta / oTimer.iIntervalMs);
}
bTimerExpired = true;
break; // found expired timer
} else if (i === 2) { // for priority 2 we check the sq timers which also have priority 2
if (this.fnCheckSqTimer()) {
break; // found expired timer
}
}
}
return bTimerExpired;
},
vmCheckTimerHandlers: function () {
var i, oTimer;
for (i = this.iTimerCount - 1; i >= 0; i -= 1) {
oTimer = this.aTimer[i];
if (oTimer.bHandlerRunning) {
if (oTimer.iStackIndexReturn > this.aGosubStack.length) {
oTimer.bHandlerRunning = false;
this.iTimerPriority = oTimer.iSavedPriority; // restore priority
oTimer.iStackIndexReturn = 0;
}
}
}
},
vmCheckSqTimerHandlers: function () {
var bTimerReloaded = false,
i, oTimer;
for (i = this.iSqTimerCount - 1; i >= 0; i -= 1) {
oTimer = this.aSqTimer[i];
if (oTimer.bHandlerRunning) {
if (oTimer.iStackIndexReturn > this.aGosubStack.length) {
oTimer.bHandlerRunning = false;
this.iTimerPriority = oTimer.iSavedPriority; // restore priority
oTimer.iStackIndexReturn = 0;
if (!oTimer.bRepeat) { // not reloaded
oTimer.bActive = false;
} else {
bTimerReloaded = true;
}
}
}
}
return bTimerReloaded;
},
vmCheckNextFrame: function (iTime) {
var iDelta;
if (iTime >= this.iNextFrameTime) { // next time of frame fly
iDelta = iTime - this.iNextFrameTime;
if (iDelta > this.iFrameTimeMs) {
this.iNextFrameTime += this.iFrameTimeMs * Math.ceil(iDelta / this.iFrameTimeMs);
} else {
this.iNextFrameTime += this.iFrameTimeMs;
}
this.oCanvas.updateSpeedInk();
this.vmCheckTimer(iTime); // check BASIC timers and sound queue
this.oSound.scheduler(); // on a real CPC it is 100 Hz, we use 50 Hz
}
},
vmGetTimeUntilFrame: function (iTime) {
var iTimeUntilFrame;
iTime = iTime || Date.now();
iTimeUntilFrame = this.iNextFrameTime - iTime;
return iTimeUntilFrame;
},
vmLoopCondition: function () {
var iTime = Date.now();
if (iTime >= this.iNextFrameTime) {
this.vmCheckNextFrame(iTime);
this.iStopCount += 1;
if (this.iStopCount >= 5) { // do not stop too often because of just timer reason because setTimeout is expensive
this.iStopCount = 0;
this.vmStop("timer", 20);
}
}
return this.oStop.sReason === "";
},
vmInitUntypedVariables: function (sVarChar) {
var aNames = this.oVariables.getAllVariableNames(),
i, sName;
for (i = 0; i < aNames.length; i += 1) {
sName = aNames[i];
if (sName.charAt(0) === sVarChar) {
if (sName.indexOf("$") === -1 && sName.indexOf("%") === -1 && sName.indexOf("!") === -1) { // no explicit type?
this.oVariables.initVariable(sName);
}
}
}
},
vmDefineVarTypes: function (sType, sNameOrRange, sErr) {
var aRange, iFirst, iLast, i, sVarChar;
this.vmAssertString(sNameOrRange, sErr);
if (sNameOrRange.indexOf("-") >= 0) {
aRange = sNameOrRange.split("-", 2);
iFirst = aRange[0].trim().toLowerCase().charCodeAt(0);
iLast = aRange[1].trim().toLowerCase().charCodeAt(0);
} else {
iFirst = sNameOrRange.trim().toLowerCase().charCodeAt(0);
iLast = iFirst;
}
for (i = iFirst; i <= iLast; i += 1) {
sVarChar = String.fromCharCode(i);
if (this.oVariables.getVarType(sVarChar) !== sType) { // type changed?
this.oVariables.setVarType(sVarChar, sType);
// initialize all untyped variables starting with sVarChar!
this.vmInitUntypedVariables(sVarChar);
}
}
},
vmStop: function (sReason, iPriority, bForce, oParas) { // optional bForce, oParas
iPriority = iPriority || 0;
if (bForce || iPriority >= this.oStop.iPriority) {
this.oStop.iPriority = iPriority;
this.oStop.sReason = sReason;
this.oStop.oParas = oParas;
}
},
vmNotImplemented: function (sName) {
Utils.console.warn("Not implemented:", sName);
},
// not complete
vmUsingFormat1: function (sFormat, arg) {
var sPadChar = " ",
re1 = /^\\ *\\$/,
iDecimals, iPadLen, sPad, aFormat, sStr;
if (typeof arg === "string") {
if (sFormat === "&") {
sStr = arg;
} else if (sFormat === "!") {
sStr = arg.charAt(0);
} else if (re1.test(sFormat)) { // "\...\"
sStr = arg.substr(0, sFormat.length);
iPadLen = sFormat.length - arg.length;
sPad = (iPadLen > 0) ? sPadChar.repeat(iPadLen) : "";
sStr = arg + sPad; // string left aligned
} else { // no string format
throw this.vmComposeError(Error(), 13, "USING format " + sFormat); // "Type mismatch"
}
} else { // number (not fully implemented)
if (sFormat === "&" || sFormat === "!" || re1.test(sFormat)) { // string format for number?
throw this.vmComposeError(Error(), 13, "USING format " + sFormat); // "Type mismatch"
}
if (sFormat.indexOf(".") < 0) { // no decimal point?
arg = Number(arg).toFixed(0);
} else { // assume ###.##
aFormat = sFormat.split(".", 2);
iDecimals = aFormat[1].length;
// To avoid rounding errors: https://www.jacklmoore.com/notes/rounding-in-javascript
arg = Number(Math.round(Number(arg + "e" + iDecimals)) + "e-" + iDecimals);
arg = arg.toFixed(iDecimals);
}
if (sFormat.indexOf(",") >= 0) { // contains comma => insert thousands separator
arg = Utils.numberWithCommas(arg);
}
iPadLen = sFormat.length - arg.length;
sPad = (iPadLen > 0) ? sPadChar.repeat(iPadLen) : "";
sStr = sPad + arg;
if (sStr.length > sFormat.length) {
sStr = "%" + sStr; // mark too long
}
}
return sStr;
},
vmGetStopObject: function () {
return this.oStop;
},
vmGetInFileObject: function () {
return this.oInFile;
},
vmGetOutFileObject: function () {
return this.oOutFile;
},
vmAdaptFilename: function (sName, sErr) {
var iIndex;
this.vmAssertString(sName, sErr);
sName = sName.replace(/ /g, ""); // remove spaces
if (sName.indexOf("!") === 0) {
sName = sName.substr(1); // remove preceding "!"
}
iIndex = sName.indexOf(":");
if (iIndex >= 0) {
sName = sName.substr(iIndex + 1); // remove user and drive letter including ":"
}
sName = sName.toLowerCase();
if (!sName) {
throw this.vmComposeError(Error(), 32, "Bad filename: " + sName);
}
return sName;
},
vmGetSoundData: function () {
return this.aSoundData;
},
vmTrace: function (iLine) {
var iStream = 0;
this.iTronLine = iLine;
if (this.bTron) {
this.print(iStream, "[" + iLine + "]");
}
},
vmDrawMovePlot: function (sType, x, y, iGPen, iGColMode) {
x = this.vmInRangeRound(x, -32768, 32767, sType);
y = this.vmInRangeRound(y, -32768, 32767, sType);
if (iGPen !== undefined) {
iGPen = this.vmInRangeRound(iGPen, 0, 15, sType);
this.oCanvas.setGPen(iGPen);
}
if (iGColMode !== undefined) {
iGColMode = this.vmInRangeRound(iGColMode, 0, 3, sType);
this.oCanvas.setGColMode(iGColMode);
}
this.oCanvas[sType.toLowerCase()](x, y); // draw, drawr, move, mover, plot, plotr
},
vmAfterEveryGosub: function (sType, iInterval, iTimer, iLine) {
var oTimer, iIntervalMs;
iInterval = this.vmInRangeRound(iInterval, 0, 32767, sType); // more would be overflow
iTimer = this.vmInRangeRound(iTimer || 0, 0, 3, sType);
oTimer = this.aTimer[iTimer];
if (iInterval) {
iIntervalMs = iInterval * this.iFrameTimeMs; // convert to ms
oTimer.iIntervalMs = iIntervalMs;
oTimer.iLine = iLine;
oTimer.bRepeat = (sType === "EVERY");
oTimer.bActive = true;
oTimer.iNextTimeMs = Date.now() + iIntervalMs;
} else { // interval 0 => switch running timer off
oTimer.bActive = false;
}
},
vmCopyFromScreen: function (iSource, iDest) {
var i, iByte;
for (i = 0; i < 0x4000; i += 1) {
iByte = this.oCanvas.getByte(iSource + i); // get byte from screen memory
if (iByte === null) { // byte not visible on screen?
iByte = this.aMem[iSource + i] || 0; // get it from our memory
}
this.aMem[iDest + i] = iByte;
}
},
vmCopyToScreen: function (iSource, iDest) {
var i, iByte;
for (i = 0; i < 0x4000; i += 1) {
iByte = this.aMem[iSource + i] || 0; // get it from our memory
this.oCanvas.setByte(iDest + i, iByte);
}
},
vmSetScreenBase: function (iByte) {
var iPage, iOldPage, iAddr;
iByte = this.vmInRangeRound(iByte, 0, 255, "screenBase");
iPage = iByte >> 6; // eslint-disable-line no-bitwise
iOldPage = this.iScreenPage;
if (iPage !== iOldPage) {
iAddr = iOldPage << 14; // eslint-disable-line no-bitwise
this.vmCopyFromScreen(iAddr, iAddr);
this.iScreenPage = iPage;
iAddr = iPage << 14; // eslint-disable-line no-bitwise
this.vmCopyToScreen(iAddr, iAddr);
}
},
vmSetScreenOffset: function (iOffset) {
this.oCanvas.setScreenOffset(iOffset);
},
// could be also set vmSetScreenViewBase? thisiScreenViewPage? We always draw on visible canvas?
vmSetTransparentMode: function (iStream, iTransparent) {
var oWin = this.aWindow[iStream];
oWin.bTransparent = Boolean(iTransparent);
},
// --
abs: function (n) {
this.vmAssertNumber(n, "ABS");
return Math.abs(n);
},
addressOf: function (sVar) { // addressOf operator
var iPos;
// not really implemented
sVar = sVar.replace("v.", "");
sVar = sVar.replace("[", "(");
iPos = sVar.indexOf("("); // array variable with indices?
if (iPos >= 0) {
sVar = sVar.substr(0, iPos); // remove indices
}
iPos = this.oVariables.getVariableIndex(sVar);
if (iPos < 0) {
throw this.vmComposeError(Error(), 5, "@" + sVar); // Improper argument
}
return iPos;
},
afterGosub: function (iInterval, iTimer, iLine) {
this.vmAfterEveryGosub("AFTER", iInterval, iTimer, iLine);
},
// and
vmGetCpcCharCode: function (iCode) {
if (iCode > 255) { // map some UTF-8 character codes
if (this.mUtf8ToCpc[iCode]) {
iCode = this.mUtf8ToCpc[iCode];
}
}
return iCode;
},
asc: function (s) {
this.vmAssertString(s, "ASC");
if (!s.length) {
throw this.vmComposeError(Error(), 5, "ASC"); // Improper argument
}
return this.vmGetCpcCharCode(s.charCodeAt(0));
},
atn: function (n) {
this.vmAssertNumber(n, "ATN");
n = Math.atan(n);
return this.bDeg ? Utils.toDegrees(n) : n;
},
auto: function () {
this.vmNotImplemented("AUTO");
},
bin$: function (n, iPad) {
n = this.vmRound2Complement(n, "BIN$");
iPad = this.vmInRangeRound(iPad || 0, 0, 16, "BIN$");
return n.toString(2).padStart(iPad, "0");
},
border: function (iInk1, iInk2) { // ink2 optional
iInk1 = this.vmInRangeRound(iInk1, 0, 31, "BORDER");
if (iInk2 === undefined) {
iInk2 = iInk1;
} else {
iInk2 = this.vmInRangeRound(iInk2, 0, 31, "BORDER");
}
this.oCanvas.setBorder(iInk1, iInk2);
},
// break
vmMcSetMode: function (iMode) {
var iAddr = this.iScreenPage << 14, // eslint-disable-line no-bitwise
iCanvasMode = this.oCanvas.getMode();
iMode = this.vmInRangeRound(iMode, 0, 3, "MCSetMode");
if (iMode !== iCanvasMode) {
// keep screen bytes, just interpret in other mode
this.vmCopyFromScreen(iAddr, iAddr); // read bytes from screen memory into memory
this.oCanvas.changeMode(iMode); // change mode and interpretation of bytes
this.vmCopyToScreen(iAddr, iAddr); // write bytes back to screen memory
this.oCanvas.changeMode(iCanvasMode); // keep moe
// TODO: new content should still be written in old mode but interpreted in new mode
}
},
vmTxtInverse: function (iStream) { // iStream must be checked
var oWin = this.aWindow[iStream],
iTmp;
iTmp = oWin.iPen;
this.pen(iStream, oWin.iPaper);
this.paper(iStream, iTmp);
},
vmPutKeyInBuffer: function (sKey) {
var oKeyDownHandler = this.oKeyboard.getKeyDownHandler();
this.oKeyboard.putKeyInBuffer(sKey);
if (oKeyDownHandler) {
oKeyDownHandler();
}
},
call: function (iAddr) { // eslint-disable-line complexity
// varargs (adr + parameters)
iAddr = this.vmRound2Complement(iAddr, "CALL");
switch (iAddr) {
case 0xbb00: // KM Initialize (ROM &19E0)
this.oKeyboard.resetCpcKeysExpansions();
this.call(0xbb03); // KM Reset
break;
case 0xbb03: // KM Reset (ROM &1AE1)
this.clearInput();
this.oKeyboard.resetExpansionTokens();
// TODO: reset also speed key
break;
case 0xbb06: // KM Wait Char (ROM &1A3C)
// since we do not return a character, we do the same as call &bb18
if (this.inkey$() === "") { // no key?
this.vmStop("waitKey", 41); // wait for key
}
break;
case 0xbb0c: // KM Char Return (ROM &1A77), depending on number of args
this.vmPutKeyInBuffer(String.fromCharCode(arguments.length - 1));
break;
case 0xbb18: // KM Wait Key (ROM &1B56)
if (this.inkey$() === "") { // no key?
this.vmStop("waitKey", 41); // wait for key
}
break;
case 0xbb4e: // TXT Initialize (ROM &1078)
this.oCanvas.resetCustomChars();