-
Notifications
You must be signed in to change notification settings - Fork 71
/
VDP.js
2611 lines (2150 loc) · 134 KB
/
VDP.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
// Copyright 2015 by Paulo Augusto Peccin. See license.txt distributed with this file.
// V9958/V9938/V9918 VDPs supported
// This implementation is line-accurate
// Digitize, Superimpose, LightPen, Mouse, Color Bus, External Synch, B/W Mode, Wait Function not supported
// Original base clock: 21477270 Hz which is 6x CPU clock. Rectified to real 60Hz: 21504960 Hz
wmsx.VDP = function(machine, cpu, vSyncConnection) {
"use strict";
var self = this;
function init() {
videoSignal = new wmsx.VideoSignal(self, "Internal");
audioClockPulse32 = machine.getAudioSocket().audioClockPulse32;
initColorCaches();
initFrameResources(false);
initDebugPatternTables();
initSpritesConflictMap();
modeData = modes[0];
backdropCacheUpdatePending = true;
self.setDefaults();
commandProcessor = new wmsx.VDPCommandProcessor();
commandProcessor.connectVDP(self, vram, register, status);
commandProcessor.setVDPModeData(modeData);
renderWidth = wmsx.VDP.SIGNAL_START_WIDTH_V9938;
renderHeight = WMSX.MACHINES_CONFIG[WMSX.MACHINE].TYPE === 1 ? wmsx.VDP.SIGNAL_HEIGHT_V9918 : wmsx.VDP.SIGNAL_START_HEIGHT_V9938;
}
this.setMachineType = function(machineType) {
var type = WMSX.VDP_TYPE > 0 ? WMSX.VDP_TYPE : machineType; // auto: According to Machine Type
isV9918 = type <= M_TYPES.MSX1;
isV9938 = type === M_TYPES.MSX2;
isV9958 = type >= M_TYPES.MSX2P;
cpuBusClockPulses = cpu.busClockPulses;
cpuMemoryRefresh = cpu.r800MemoryRefresh;
};
this.connectBus = function(bus) {
bus.connectInputDevice( 0x98, this.input98);
bus.connectOutputDevice(0x98, this.output98);
bus.connectInputDevice( 0x99, this.input99);
bus.connectOutputDevice(0x99, this.output99);
bus.connectInputDevice( 0x9a, wmsx.DeviceMissing.inputPortIgnored);
bus.connectOutputDevice(0x9a, this.output9a);
bus.connectInputDevice( 0x9b, wmsx.DeviceMissing.inputPortIgnored);
bus.connectOutputDevice(0x9b, this.output9b);
};
this.connectSlave = function(pSlave) {
slave = pSlave;
if (slave) slave.setVideoStandard(videoStandard);
updateSignalMetrics(true);
updateRenderMetrics(true);
// this.refreshDisplayMetrics();
};
this.powerOn = function() {
this.reset();
};
this.powerOff = function() {
videoSignal.signalOff();
};
this.setVideoStandard = function(pVideoStandard) {
videoStandard = pVideoStandard;
updateSynchronization();
if (slave) slave.setVideoStandard(videoStandard);
//logInfo("VideoStandard set: " + videoStandard.name);
};
this.setVSynchMode = function(mode) {
vSynchMode = mode;
updateSynchronization();
};
this.getVideoSignal = function() {
return videoSignal;
};
this.getDesiredVideoPulldown = function () {
return pulldown;
};
this.videoClockPulse = function() {
// Generate correct amount of lines per cycle, according to the current pulldown cadence
cycleEvents();
// Send updated image to Monitor if needed
if (refreshWidth) refresh();
if (slave) slave.cycleEventRefresh();
};
// VRAM Read
this.input98 = function() {
dataFirstWrite = null;
var res = dataPreRead;
dataPreRead = vram[vramPointer];
++vramPointer;
checkVRAMPointerWrap();
return res;
};
// VRAM Write
this.output98 = function(val) {
//if ((vramPointer >= spriteAttrTableAddress + 512) /* && (vramPointer <= spriteAttrTableAddress + 512 + 32 * 4) */)
// logInfo("VRAM Write: " + val.toString(16) + " at: " + vramPointer.toString(16));
// if (vramPointer >= 0x3800 && vramPointer <= 0x3807)
// console.error("Write:", vramPointer.toString(16), val.toString(16), "PC:", cpu.eval("PC").toString(16),
// ", Pri:", machine.bus.getPrimarySlotConfig().toString(16), ", Sec:", machine.bus.slots[3].getSecondarySlotConfig().toString(16));
dataFirstWrite = null;
vram[vramPointer] = dataPreRead = val;
++vramPointer;
checkVRAMPointerWrap();
};
// Status Register Read
this.input99 = function() {
dataFirstWrite = null;
var reg = register[15];
var res;
switch(reg) {
case 0:
res = getStatus0(); // Dynamic value. status[0] is never accurate
break;
case 1:
res = status[1] | FH; // Dynamic value. status[1] is never accurate
if ((register[0] & 0x10) && FH) {
FH = 0; // FH = 0, only if interrupts are enabled (IE1 = 1)
updateIRQ();
}
// logInfo("Status1 read: " + res.toString(16));
break;
case 2:
commandProcessor.updateStatus();
res = status[2] // Dynamic value. status[2] is never accurate
| (VR << 6) | (HR << 5) | (EO << 1);
// logInfo("VDP Status2 Read : " + res.toString(16));
break;
case 3: case 4: case 6:
res = status[reg];
break;
case 5:
res = status[5];
spritesCollisionX = spritesCollisionY = -1; // Clear collision coordinates and status registers
status[3] = status[4] = status[5] = status[6] = 0;
break;
case 7:
res = status[7];
commandProcessor.cpuRead();
break;
case 8: case 9:
res = status[reg];
break;
default:
res = 0xff; // Invalid register
}
//logInfo("Reading status " + reg + ", " + res.toString(16));
return res;
};
// Register/VRAM Address write
this.output99 = function(val) {
if (dataFirstWrite === null) {
// First write. Data to write to register or VRAM Address Pointer low (A7-A0)
dataFirstWrite = val;
// On V9918, the VRAM pointer low gets written right away
if (isV9918) vramPointer = (vramPointer & ~0xff) | val;
} else {
// Second write
if (val & 0x80) {
// Register write
if (isV9918) {
registerWrite(val & 0x07, dataFirstWrite);
// On V9918, the VRAM pointer high gets also written when writing to registers
vramPointer = (vramPointer & 0x1c0ff) | ((val & 0x3f) << 8);
} else {
// On V9938 register write only if "WriteMode = 0"
if ((val & 0x40) === 0) registerWrite(val & 0x3f, dataFirstWrite);
}
} else {
// VRAM Address Pointer middle (A13-A8). Finish VRAM Address Pointer setting
vramPointer = (vramPointer & 0x1c000) | ((val & 0x3f) << 8) | dataFirstWrite;
// Pre-read VRAM if "WriteMode = 0"
if ((val & 0x40) === 0) {
dataPreRead = vram[vramPointer];
++vramPointer;
checkVRAMPointerWrap();
}
}
dataFirstWrite = null;
}
};
// Palette Write
this.output9a = function(val) {
if (isV9918) return;
if (paletteFirstWrite === null) {
paletteFirstWrite = val;
} else {
paletteRegisterWrite(register[16], (val << 8) | paletteFirstWrite, false);
if (++register[16] > 15) register[16] = 0;
paletteFirstWrite = null;
}
};
// Indirect Register Write
this.output9b = function(val) {
if (isV9918) return;
var reg = register[17] & 0x3f;
if (reg !== 17) registerWrite(reg, val);
if ((register[17] & 0x80) === 0) register[17] = (reg + 1) & 0x3f; // Increment if needed
};
this.toggleDebugModes = function(dec) {
setDebugMode(debugMode + (dec ? -1 : 1));
videoSignal.showOSD("Debug Mode" + (debugMode > 0 ? " " + debugMode : "") + ": "
+ [ "OFF", "Sprites Highlighted", "Sprite Numbers", "Sprite Names",
"Sprites Hidden", "Pattern Bits", "Pattern Color Blocks", "Pattern Names"][debugMode], true);
return debugMode;
};
this.toggleSpriteDebugModes = function(dec) {
setSpriteDebugMode(spriteDebugMode + (dec ? -1 : 1));
videoSignal.showOSD("Sprites Mode" + (spriteDebugMode > 0 ? " " + spriteDebugMode : "") + ": "
+ ["Normal", "Unlimited", "NO Collisions", "Unlimited, No Collisions"][spriteDebugMode], true);
};
this.setColorAndPaletteMode = function(color, palette) {
wmsx.ColorCache.setColorAndPaletteMode(color, palette);
initColorCaches();
updateAllPaletteValues();
};
this.getSpriteDebugModeQuickDesc = function() {
return ["Normal", "Unlimited", "No Collis.", "Both"][spriteDebugMode];
};
this.setVDPTurboMulti = function(multi) {
commandProcessor.setVDPTurboMulti(multi);
};
this.getVDPTurboMulti = function() {
return commandProcessor.getVDPTurboMulti();
};
this.setDefaults = function() {
setDebugMode(STARTING_DEBUG_MODE);
setSpriteDebugMode(STARTING_SPRITES_DEBUG_MODE);
};
this.videoSignalDisplayStateUpdate = function(displayed, superimposeActive) {
videoDisplayed = displayed;
//console.log("VDP displayed:", displayed);
};
this.refreshDisplayMetrics = function () {
videoSignal.setDisplayMetrics(renderWidth, renderHeight);
};
this.resetOutputAutoMode = function() {
// Ignore
};
this.reset = function() {
frame = 0;
dataFirstWrite = null; dataPreRead = 0; vramPointer = 0; paletteFirstWrite = null;
verticalAdjust = horizontalAdjust = 0;
leftMask = leftScroll2Pages = false; leftScrollChars = leftScrollCharsInPage = rightScrollPixels = 0;
backdropColor = backdropValue = 0;
spritesCollided = false; spritesCollisionX = spritesCollisionY = spritesInvalid = -1; spritesMaxComputed = 0;
horizontalIntLine = 0;
vramInterleaving = false;
renderMetricsChangePending = false;
refreshWidth = refreshHeight = 0;
frameVideoStandard = videoStandard; framePulldown = pulldown;
currentScanline = -1;
initRegisters();
initColorPalette();
commandProcessor.reset();
updateSignalMetrics(true);
updateIRQ();
updateMode(true);
updateSpritesConfig();
updateBackdropColor();
updateTransparency();
updateSynchronization();
updateBlinking();
beginFrame();
};
this.getVDPCycles = function() {
return cpu.getBUSCycles() * 6;
};
this.getScreenText = function() {
var cols = modeData.textCols;
if (!cols) return null;
var lines = (register[9] & 0x80) ? 27 : 24;
var linesStr = [];
for (var line = 0; line < lines; ++line) {
linesStr.push(wmsx.Util.int8BitArrayToByteString(vram, layoutTableAddress + line * cols, cols).replace(/\s+$/,"")); // right trim
}
return linesStr.join("\n").replace(/[\x00\xff]/g, " ").replace(/\s+$/,""); // right trim
};
function registerWrite(reg, val) {
if (reg > 46) return;
var add;
var mod = register[reg] ^ val;
register[reg] = val;
//logInfo("Reg: " + reg + " = " + val.toString(16));
switch (reg) {
case 0:
//if (mod) logInfo("Register0: " + val.toString(16));
if (mod & 0x10) { // IE1
// Clear FH bit immediately when IE becomes 0? Not as per https://www.mail-archive.com/msx@stack.nl/msg13886.html
// We clear it only at the beginning of the next line if IE === 0
// Laydock2 has glitches on WebMSX with Turbo and also on a real Expert3 at 10MHz
// if (((val & 0x10) === 0) && FH) FH = 0
updateIRQ();
}
if (mod & 0x0e) updateMode(); // Mx
break;
case 1:
//if (mod) logInfo("Register1: " + val.toString(16));
if (mod & 0x20) updateIRQ(); // IE0
if (mod & 0x40) { // BL
blankingChangePending = true; // only at next line
//logInfo("Blanking: " + !!(val & 0x40));
}
if (mod & 0x18) updateMode(); // Mx
if (mod & 0x04) updateBlinking(); // CDR (Undocumented, changes reg 13 timing to lines instead of frames)
if (mod & 0x03) updateSpritesConfig(); // SI, MAG
break;
case 2:
if (mod & 0x7f) updateLayoutTableAddress();
break;
case 10:
if ((mod & 0x07) === 0) break;
// else fall through
case 3:
add = ((register[10] << 14) | (register[3] << 6)) & 0x1ffff;
colorTableAddress = add & modeData.colorTBase;
colorTableAddressMask = add | colorTableAddressMaskBase;
//logInfo("Setting: " + val.toString(16) + " to ColorTableAddress: " + colorTableAddress.toString(16));
break;
case 4:
if ((mod & 0x3f) === 0) break;
add = (val << 11) & 0x1ffff;
patternTableAddress = add & modeData.patTBase;
patternTableAddressMask = add | patternTableAddressMaskBase;
//logInfo("Setting: " + val.toString(16) + " to PatternTableAddress: " + patternTableAddress.toString(16));
break;
case 11:
if ((mod & 0x03) === 0) break;
// else fall through
case 5:
add = ((register[11] << 15) | (register[5] << 7)) & 0x1ffff;
spriteAttrTableAddress = add & modeData.sprAttrTBase;
//logInfo("SpriteAttrTable: " + spriteAttrTableAddress.toString(16));
break;
case 6:
if (mod & 0x3f) updateSpritePatternTableAddress();
break;
case 7:
if (mod & (modeData.bdPaletted ? 0x0f : 0xff)) updateBackdropColor(); // BD
break;
case 8:
if (mod & 0x20) updateTransparency(); // TP
if (mod & 0x02) updateSpritesConfig(); // SPD
break;
case 9:
if (mod & 0x80) updateSignalMetrics(false); // LN
if (mod & 0x08) updateRenderMetrics(false); // IL
if (mod & 0x04) updateLayoutTableAddressMask(); // EO
if (mod & 0x02) updateVideoStandardSoft(); // NT
break;
case 13:
updateBlinking(); // Always, even with no change
break;
case 14:
if (mod & 0x07) vramPointer = ((val & 0x07) << 14) | (vramPointer & 0x3fff);
//console.log("Setting reg14: " + val.toString(16) + ". VRAM Pointer: " + vramPointer.toString(16));
break;
case 16:
paletteFirstWrite = null;
break;
case 18:
if (mod & 0x0f) horizontalAdjust = -7 + ((val & 0x0f) ^ 0x07);
if (mod & 0xf0) {
verticalAdjust = -7 + ((val >>> 4) ^ 0x07);
updateSignalMetrics(false);
}
break;
case 19:
horizontalIntLine = (val - register[23]) & 255;
// logInfo("Line Interrupt set: " + val + ", reg23: " + register[23]);
break;
case 23:
horizontalIntLine = (register[19] - val) & 255;
//logInfo("Vertical offset set: " + val);
break;
case 25:
if (isV9958) {
if (mod & 0x18) updateMode(); // YJK, YAE
leftMask = (val & 0x02) !== 0; // MSK
leftScroll2Pages = (val & 0x01) !== 0; // SP2
}
break;
case 26:
if (isV9958) {
leftScrollChars = val & 0x3f; // H08-H03
leftScrollCharsInPage = leftScrollChars & 31;
}
break;
case 27:
if (isV9958) rightScrollPixels = val & 0x07; // H02-H01
// logInfo("Reg17 - Right Scroll set: " + val);
break;
case 44:
commandProcessor.cpuWrite(val);
break;
case 46:
commandProcessor.startCommand(val);
break;
}
}
function updateLayoutTableAddress() {
// Interleaved modes (G6, G7, YJK, YAE) have different address bits position in reg 2. Only A16 can be specified for base address, A10 always set in mask
var add = modeData.vramInter ?((register[2] & 0x3f) << 11) | (1 << 10) : (register[2] & 0x7f) << 10;
layoutTableAddress = add & modeData.layTBase;
layoutTableAddressMaskSetValue = add | layoutTableAddressMaskBase;
updateLayoutTableAddressMask();
//logInfo(/* "Setting: " + reg.toString(16) + " to " + */ "LayoutTableAddress: " + layoutTableAddress.toString(16));
}
// Consider Alternative Page (EO and Blink)
function updateLayoutTableAddressMask() {
layoutTableAddressMask = layoutTableAddressMaskSetValue &
(blinkEvenPage || ((register[9] & 0x04) && !EO) ? modeData.blinkPageMask : ~0);
}
function updateSpritePatternTableAddress() {
spritePatternTableAddress = debugModeSpriteInfo
? spritesSize === 16 ? DEBUG_PAT_DIGI16_TABLE_ADDRESS : DEBUG_PAT_DIGI8_TABLE_ADDRESS
: (register[6] << 11) & 0x1ffff;
//logInfo("SpritePatTable: " + spritePatternTableAddress.toString(16));
}
function getStatus0() {
var res = 0;
// Vertical Int
if (F) { // F
res |= 0x80;
F = 0;
updateIRQ();
}
// Collision
if (spritesCollided) {
res |= 0x20; // C
spritesCollided = false;
}
// Invalid Sprite, otherwise Greatest Sprite number drawn
if (spritesInvalid >= 0) {
res |= 0x40 | spritesInvalid; // 5S, 5SN
spritesInvalid = -1;
} else
res |= spritesMaxComputed; // 5SN
spritesMaxComputed = 0;
// logInfo("Status0 read: " + res.toString(16));
return res; // Everything is cleared at this point (like status[0] == 0)
}
function checkVRAMPointerWrap() {
if ((vramPointer & 0x3fff) === 0) {
//wmsx.Util.log("VRAM Read Wrapped, vramPointer: " + vramPointer.toString(16) + ", register14: " + register[14].toString(16));
if (modeData.isV9938) register[14] = (register[14] + 1) & 0x07;
vramPointer = register[14] << 14;
}
}
function paletteRegisterWrite(reg, val, force) {
if (paletteRegister[reg] === val && !force) return;
//logInfo("Palette register " + reg + ": " + val);
paletteRegister[reg] = val;
var value = getColorValueForPaletteValue(val);
colorPaletteReal[reg] = value;
if (debugModeSpriteHighlight) value &= DEBUG_DIM_ALPHA_MASK;
colorPaletteSolid[reg] = value;
// Special case for color 0
if (reg === 0) {
if (color0Solid) colorPalette[0] = value;
} else
colorPalette[reg] = value;
if (reg === backdropColor) updateBackdropValue();
else if (modeData.tiled && reg <= 3) backdropCacheUpdatePending = true;
}
function getColorValueForPaletteValue(val) {
return colors9bitValues[((val & 0x700) >>> 2) | ((val & 0x70) >>> 1) | (val & 0x07)]; // 9 bit GRB
}
function setDebugMode(mode) {
debugMode = (mode + 8) % 8;
var oldDebugModeSpriteHighlight = debugModeSpriteHighlight;
debugModeSpriteHighlight = debugMode >= 1 && debugMode <= 3;
debugModeSpriteInfo = debugMode === 2 || debugMode === 3;
debugModeSpriteInfoNumbers = debugMode === 2;
// mode 3 is SpriteInfoName
debugModeSpritesHidden = debugMode >= 4;
var oldDebugModePatternInfo = debugModePatternInfo;
debugModePatternInfo = debugMode >= 5;
debugModePatternInfoBlocks = debugMode === 6;
debugModePatternInfoNames = debugMode === 7;
if (oldDebugModeSpriteHighlight !== debugModeSpriteHighlight || oldDebugModePatternInfo !== debugModePatternInfo) updateAllPaletteValues();
initFrameResources(debugModeSpriteHighlight);
updateLineActiveType();
updateSpritesConfig();
updateSpritePatternTableAddress();
if (slave) slave.setDebugMode(debugMode);
videoSignal.setDebugMode(debugMode > 0);
}
function setSpriteDebugMode(mode) {
spriteDebugMode = mode >= 0 ? mode % 4 : 4 + mode;
spriteDebugModeLimit = (spriteDebugMode === 0) || (spriteDebugMode === 2);
spriteDebugModeCollisions = spriteDebugMode < 2;
if (slave) slave.setSpriteDebugMode(spriteDebugMode);
}
function updateAllPaletteValues() {
if (isV9918) initColorPalette();
else for (var reg = 0; reg < 16; reg++) paletteRegisterWrite(reg, paletteRegister[reg], true);
}
function updateSynchronization() {
// According to the native video frequency detected, target Video Standard and vSynchMode, use a specific pulldown configuration
if (vSynchMode === 1) { // ON
// Will V-synch to host freq if detected and supported, or use optimal timer configuration)
pulldown = videoStandard.pulldowns[machine.getVideoClockSocket().getVSynchNativeFrequency()] || videoStandard.pulldowns.TIMER;
} else { // OFF, DISABLED
// No V-synch. Always use the optimal timer configuration)
pulldown = videoStandard.pulldowns.TIMER;
}
// console.log("Update Synchronization. Pulldown " + pulldown.standard + " " + pulldown.frequency);
}
// Total frame lines: 262 for NTSC, 313 for PAL
// Total frame CPU clocks: 59736 for NTSC, 71364 for PAL
function cycleEvents() {
var cycleLines = framePulldown.linesPerCycle;
// Adjust pulldown cadence if necessary
if (pulldown.steps > 1 && (frame % pulldown.steps) === 0) cycleLines += pulldown.firstStepCycleLinesAdjust;
for (var i = cycleLines; i > 0; --i) lineEvents();
}
// Total line clocks: VDP: 1368, CPU: 228, PSG 7.125
// Timing should be different for mode T1 and T2 since borders are wider. Ignoring for now.
function lineEvents() {
// Start of line
// debugLineStartBUSCycles = cpu.getBUSCycles();
// Page blinking per line (undocumented CDR bit set)
if (blinkPerLine && blinkPageDuration > 0)
if (clockPageBlinking()) updateLayoutTableAddressMask();
// Verify and change sections of the screen
if (currentScanline === startingActiveScanline) setActiveDisplay();
else if (currentScanline - frameStartingActiveScanline === signalActiveHeight) setBorderDisplay();
// Sync signal: 100 clocks
// Left erase: 102 clocks
cpuMemoryRefresh();
cpuBusClockPulses(33); audioClockPulse32();
// Left border: 56 clocks
if (blankingChangePending) updateLineActiveType();
if (FH && ((register[0] & 0x10) === 0)) FH = 0; // FH = 0 if interrupts disabled (IE1 = 0)
if (currentScanline === startingActiveScanline - 1) VR = 0; // VR = 0 at the scanline before first Active scanline
else if (currentScanline - frameStartingActiveScanline === signalActiveHeight) // VR = 1, F = 1 at the first Bottom Border line
triggerVerticalInterrupt();
cpuBusClockPulses(10);
// Active Display: 1024 clocks
HR = 0; // HR = 0
if (slave) slave.lineEventStartActiveDisplay();
cpuBusClockPulses(22); audioClockPulse32();
cpuBusClockPulses(33); audioClockPulse32();
cpuBusClockPulses(32); audioClockPulse32();
// ~ Middle of Active Line
if (currentScanline >= startingVisibleTopBorderScanline
&& currentScanline < startingInvisibleScanline ) renderLine(); // Only render if visible
if (slave) slave.lineEventRenderLine();
cpuMemoryRefresh();
cpuBusClockPulses(33); audioClockPulse32();
cpuBusClockPulses(32); audioClockPulse32();
cpuBusClockPulses(18);
// End of Active Display
HR = 1; // HR = 1
if (currentScanline - frameStartingActiveScanline === horizontalIntLine)
triggerHorizontalInterrupt(); // FH = 1
if (slave) slave.lineEventEndActiveDisplay();
// Right border: 59 clocks
// Right erase: 27 clocks
cpuBusClockPulses(15); audioClockPulse32();
if ((currentScanline & 0x7) === 0) audioClockPulse32(); // One more audioClock32 each 8 lines
// End of line
++currentScanline;
if (slave) slave.lineEventEnd();
if (currentScanline >= finishingScanline) {
finishFrame();
if (slave) slave.frameEventFinishFrame();
}
}
function triggerVerticalInterrupt() {
VR = 1; // VR = 1
if (!F) {
F = 1;
updateIRQ();
}
// logInfo("Vertical Frame Int reached. Ints " + ((register[1] & 0x20) ? "ENABLED" : "disabled"));
}
function triggerHorizontalInterrupt() {
if (!FH) {
FH = 1; // FH = 1
updateIRQ();
}
// logInfo("Horizontal Int Line reached. Ints " + ((register[0] & 0x10) ? "ENABLED" : "disabled"));
}
function updateIRQ() {
if ((F && (register[1] & 0x20)) // F == 1 and IE0 == 1
|| (FH && (register[0] & 0x10))) { // FH == 1 and IE1 == 1
cpu.setINTChannel(0, 0); // VDP uses fixed channel 0
} else {
cpu.setINTChannel(0, 1);
}
// logInfo(">>> VDP INT VERTICAL: " + (F && (register[1] & 0x20)));
// logInfo(">>> VDP INT HORIZONTAL: " + (FH && (register[0] & 0x10)));
}
function updateVRAMInterleaving() {
if (modeData.vramInter === true && !vramInterleaving) vramEnterInterleaving();
else if (modeData.vramInter === false && vramInterleaving) vramExitInterleaving();
}
function vramEnterInterleaving() {
var e = 0;
var o = VRAM_SIZE >> 1;
var aux = vram.slice(0, o); // Only first halt needs to be saved. Verify: Optimize slice?
for (var i = 0; i < VRAM_SIZE; i += 2, ++e, ++o) {
vram[i] = aux[e];
vram[i + 1] = vram[o];
}
vramInterleaving = true;
//console.log("VRAM ENTERING Interleaving");
}
function vramExitInterleaving() {
var h = VRAM_SIZE >> 1;
var e = 0;
var o = h;
var aux = vram.slice(h); // Only last half needs to be saved. Verify: Optimize slice?
for (var i = 0; i < h; i += 2, ++e, ++o) {
vram[e] = vram[i];
vram[o] = vram[i + 1];
}
for (i = 0; i < h; i += 2, ++e, ++o) {
vram[e] = aux[i];
vram[o] = aux[i + 1];
}
vramInterleaving = false;
//console.log("VRAM EXITING Interleaving");
}
function setMode(m) {
registerWrite(0, (register[0] & ~0x0e) | ((m & 0x07) << 1));
registerWrite(1, (register[1] & ~0x18) | (m & 0x18));
}
function updateMode(forceRenderMetrics) {
var oldData = modeData;
// All Mx bits. Ignore YAE, YJK. Ignore M4, M5 if V9918
var modeBits = (register[1] & 0x18) | ((register[0] & (isV9918 ? 0x02 : 0x0e)) >>> 1);
commandProcessor.setVDPModeData(modes[modeBits]); // Independent of YJK modes!
// If YJK is set in any non-TEXT mode, modeData for rendering is determined by YAE, YJK only
if (isV9958 && (register[25] & 0x08) !== 0 && (modeBits & 0x10) === 0) modeBits = 0x20 | ((register[25] & 0x18) >> 3);
modeData = modes[modeBits];
// Update Tables base addresses
var add;
updateLayoutTableAddress();
add = ((register[10] << 14) | (register[3] << 6)) & 0x1ffff ;
colorTableAddress = add & modeData.colorTBase;
colorTableAddressMask = add | colorTableAddressMaskBase;
add = (register[4] << 11) & 0x1ffff;
patternTableAddress = add & modeData.patTBase;
patternTableAddressMask = add | patternTableAddressMaskBase;
add = ((register[11] << 15) | (register[5] << 7)) & 0x1ffff ;
spriteAttrTableAddress = add & modeData.sprAttrTBase;
updateSpritePatternTableAddress();
// Color modes
if (modeData.bdPaletted !== oldData.bdPaletted) updateBackdropColor();
if (modeData.tiled !== oldData.tiled) backdropCacheUpdatePending = true;
updateVRAMInterleaving();
updateLineActiveType();
updateRenderMetrics(forceRenderMetrics);
//logInfo("Update Mode: " + modeData.name + ". Reg0: " + register[0].toString(16));
}
function updateVideoStandardSoft() {
//logInfo("PC: " + cpu.eval("PC").toString(16) + ", reg9: " + register[9].toString(16) + ", slots: " + machine.bus.getPrimarySlotConfig().toString(16));
//wmsx.Util.dumpSlot(WMSX.room.machine.bus.slots[3].subSlots[0], cpu.eval("SP"), 30);
var pal = (register[9] & 0x02);
machine.setVideoStandardSoft(pal ? wmsx.VideoStandard.PAL : wmsx.VideoStandard.NTSC);
//logInfo("VideoStandard soft: " + (pal ? "PAL" : "NTSC"));
}
function updateSignalMetrics(force) {
var addBorder;
// Fixed metrics for V9918 with no slave (V9990)
if (isV9918 && !slave) {
signalActiveHeight = 192; addBorder = 0;
} else {
if (!isV9918 && (register[9] & 0x80)) { signalActiveHeight = 212; addBorder = 0; } // LN
else { signalActiveHeight = 192; addBorder = 10; }
}
// Render starts at first Top Border line
// Total Top border height is 16. UX decision: Visible top and bottom border height with no Vertical Adjust is 8
startingVisibleTopBorderScanline = 16 - 8; // 0-7 Top Border lines left invisible (NTSC with LN = 0)
startingActiveScanline = startingVisibleTopBorderScanline + 8 + addBorder + verticalAdjust;
var startingVisibleBottomBorderScanline = startingActiveScanline + signalActiveHeight;
startingInvisibleScanline = startingVisibleBottomBorderScanline + 8 + addBorder - verticalAdjust; // Remaining left invisible: Bottom border, Bottom Erase, Sync and Top Erase
finishingScanline = frameVideoStandard.totalHeight;
if (force) frameStartingActiveScanline = startingActiveScanline;
// logInfo("Update Signal Metrics: " + force + ", activeHeight: " + signalActiveHeight);
}
function updateRenderMetrics(force) {
var newRenderWidth, newRenderHeight, changed = false, clean = false;
// Fixed metrics for V9918 with no slave (V9990)
if (isV9918 && !slave) {
newRenderWidth = wmsx.VDP.SIGNAL_WIDTH_V9918;
newRenderHeight = wmsx.VDP.SIGNAL_HEIGHT_V9918;
} else {
newRenderWidth = modeData.width === 512 ? 512 + 16 * 2 : 256 + 8 * 2;
newRenderHeight = !isV9918 && (register[9] & 0x08) ? 424 + 16 * 2 : 212 + 8 * 2;
}
renderMetricsChangePending = false;
if (newRenderWidth === renderWidth && newRenderHeight === renderHeight) return;
// console.error("Update Render Metrics. " + force + " Asked: " + newRenderWidth + "x" + newRenderHeight + ", set: " + renderWidth + "x" + renderHeight);
// Only change width if before visible display (beginFrame), or if going to higher width
if (newRenderWidth !== renderWidth) {
if (currentScanline < startingVisibleTopBorderScanline || newRenderWidth > renderWidth) {
if (currentScanline >= startingVisibleTopBorderScanline) {
if (force) clean = true;
else stretchFromCurrentToTopScanline();
}
renderWidth = newRenderWidth;
changed = true;
} else
renderMetricsChangePending = true;
}
// Only change height if forced (loadState and beginFrame)
if (newRenderHeight !== renderHeight) {
if (force) {
if (currentScanline >= startingVisibleTopBorderScanline || newRenderHeight > renderHeight) clean = true;
renderHeight = newRenderHeight;
changed = true;
} else
renderMetricsChangePending = true;
}
if (clean) cleanFrameBuffer();
if (changed) self.refreshDisplayMetrics();
}
function setActiveDisplay() {
renderLine = renderLineActive;
}
function setBorderDisplay() {
renderLine = renderLineBorders;
}
function updateLineActiveType() {
var wasActive = renderLine === renderLineActive;
renderLineActive = (register[1] & 0x40) === 0 ? renderLineBlanked
: debugModePatternInfo ? modeData.renderLinePatInfo
: modeData.renderLine;
if (wasActive) renderLine = renderLineActive;
blankingChangePending = false;
}
function updateSpritesConfig() {
spritesEnabled = !debugModeSpritesHidden && (register[8] & 0x02) === 0; // SPD
spritesSize = (register[1] & 0x02) ? 16 : 8; // SI
spritesMag = register[1] & 0x01; // MAG
//logInfo("Sprites enabled: " + spritesEnabled + ", size: " + spritesSize + ", mag: " + spritesMag);
}
function updateTransparency() {
color0Solid = (register[8] & 0x20) !== 0;
colorPalette[0] = color0Solid ? colorPaletteSolid[0] : backdropValue;
//console.log("TP: " + color0Solid + ", currentLine: " + currentScanline);
}
function updateBackdropColor() {
backdropColor = register[7] & (modeData.bdPaletted ? 0x0f : 0xff);
//console.log("Backdrop Color: " + backdropColor + ", currentLine: " + currentScanline);
updateBackdropValue();
}
function updateBackdropValue() {
var value = debugModePatternInfo ? debugBackdropValue
: modeData.bdPaletted ? colorPaletteSolid[backdropColor] // From current palette (solid regardless of TP)
: colors8bitValues[backdropColor]; // From all 256 colors
if (backdropValue === value) return;
backdropValue = value;
if (!color0Solid) colorPalette[0] = value;
backdropCacheUpdatePending = true;
//logInfo("Backdrop Value: " + backdropValue.toString(16));
}
function updateBackdropLineCache() {
if (modeData.tiled && !debugModePatternInfo) { // Special case for tiled mode (G5, Screen 6)
var odd = colorPaletteSolid[backdropColor >>> 2]; var even = colorPaletteSolid[backdropColor & 0x03];
for (var i = 0; i < LINE_WIDTH; i += 2) {
backdropLineCache[i] = odd; backdropLineCache[i + 1] = even;
}
backdropTileOdd = odd; backdropTileEven = even;
} else {
wmsx.Util.arrayFill(backdropLineCache, backdropValue);
if (modeData.tiled) backdropTileOdd = backdropTileEven = backdropValue;
}
backdropCacheUpdatePending = false;
//console.log("Update BackdropCaches");
}
function updateBlinking() {
blinkPerLine = (register[1] & 0x04) !== 0; // Set Blinking speed per line instead of frame, based on undocumented CDR bit
if ((register[13] >>> 4) === 0) {
blinkEvenPage = false; blinkPageDuration = 0; // Force page to be fixed on the Odd page
} else if ((register[13] & 0x0f) === 0) {
blinkEvenPage = true; blinkPageDuration = 0; // Force page to be fixed on the Even page
} else {
blinkEvenPage = true; blinkPageDuration = 1; // Force next page to be the Even page and let alternance start
}
updateLayoutTableAddressMask(); // To reflect correct page
}
function clockPageBlinking() {
if (--blinkPageDuration === 0) {
blinkEvenPage = !blinkEvenPage;
blinkPageDuration = ((register[13] >>> (blinkEvenPage ? 4 : 0)) & 0x0f) * 10; // Duration in frames or lines depending on undocumented CDR bit
return true;
}
return false;
}
function renderLineBorders() {
if (!videoDisplayed) return;
if (backdropCacheUpdatePending) updateBackdropLineCache();
frameBackBuffer.set(backdropLineCache, bufferPosition);
bufferPosition = bufferPosition + bufferLineAdvance;
}
function renderLineBlanked() {
renderLineBorders();
}
function getRealLine() {
return (currentScanline - frameStartingActiveScanline + register[23]) & 255;
}
// V9958: Only Left Masking and Right Pixel Scroll supported. Left Char Scroll and Scroll Pages not supported
function renderLineModeT1() { // Text (Screen 0 width 40)
if (!videoDisplayed) return;
paintBackdrop16(bufferPosition); paintBackdrop16(bufferPosition + 256);
var bufferPos = bufferPosition + 8 + horizontalAdjust + rightScrollPixels;
var realLine = getRealLine();