-
Notifications
You must be signed in to change notification settings - Fork 0
/
asapwriter.fu
888 lines (845 loc) · 27.2 KB
/
asapwriter.fu
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
// asapwriter.fu - format conversions
//
// Copyright (C) 2011-2023 Piotr Fusik
//
// This file is part of ASAP (Another Slight Atari Player),
// see http://asap.sourceforge.net
//
// ASAP is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the License,
// or (at your option) any later version.
//
// ASAP is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ASAP; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
/// Exception thrown when format conversion fails.
public class ASAPConversionException : Exception
{
}
class ASAPNativeModuleWriter
{
internal ASAPWriter!? Writer;
internal byte[]? SourceModule;
internal int SourceOffset;
int AddressDiff;
int GetByte(int offset)
=> SourceModule[SourceOffset + offset];
internal int GetWord(int offset)
=> ASAPInfo.GetWord(SourceModule, SourceOffset + offset);
void Copy(int endOffset)
throws ASAPConversionException
{
Writer.WriteBytes(SourceModule, SourceOffset + Writer.OutputOffset, SourceOffset + endOffset);
}
void RelocateBytes(int lowOffset, int highOffset, int count, int shift)
throws ASAPConversionException
{
lowOffset += SourceOffset;
highOffset += SourceOffset;
for (int i = 0; i < count; i++) {
int address = SourceModule[lowOffset + i] + (SourceModule[highOffset + i] << 8);
if (address != 0 && address != 0xffff)
address += AddressDiff;
Writer.WriteByte((address >> shift) & 0xff);
}
}
void RelocateLowHigh(int count)
throws ASAPConversionException
{
int lowOffset = Writer.OutputOffset;
RelocateBytes(lowOffset, lowOffset + count, count, 0);
RelocateBytes(lowOffset, lowOffset + count, count, 8);
}
void RelocateWords(int count)
throws ASAPConversionException
{
while (--count >= 0) {
int address = GetWord(Writer.OutputOffset);
if (address != 0 && address != 0xffff)
address += AddressDiff;
Writer.WriteWord(address);
}
}
internal void Write!(ASAPInfo info, ASAPModuleType type, int moduleLen)
throws ASAPConversionException
{
int startAddr = GetWord(2);
AddressDiff = info.GetMusicAddress() < 0 ? 0 : info.GetMusicAddress() - startAddr;
if (GetWord(4) + AddressDiff > 0xffff)
throw ASAPConversionException("Address set too high");
switch (type) {
case ASAPModuleType.Cmc:
case ASAPModuleType.Cm3:
case ASAPModuleType.Cmr:
case ASAPModuleType.Cms:
// * -> CMC
RelocateWords(3); // DOS header
Copy(6 + 0x14); // CMC header
RelocateLowHigh(64); // patterns
break;
case ASAPModuleType.Dlt:
// * -> DLT
RelocateWords(3); // DOS header
break;
case ASAPModuleType.Mpt:
// * -> MPT
RelocateWords(3 + 32 + 64); // DOS header, instruments, patterns
Copy(6 + 64 + 128 + 256); // note lookup tables
RelocateLowHigh(4); // tracks
break;
case ASAPModuleType.Rmt:
// * -> RMT
Writer.WriteWord(0xffff); // RMT-generated SAPs have a player before the module
RelocateWords(2); // DOS header
Copy(6 + 8); // RMT header
int patternLowAddress = GetWord(0x10);
RelocateWords((patternLowAddress - startAddr - 8) >> 1); // 4 pointers, instruments
RelocateLowHigh(GetWord(0x12) - patternLowAddress); // patterns
int songOffset = 6 + GetWord(0x14) - startAddr;
Copy(songOffset);
int songEnd = 7 + GetWord(4) - startAddr;
while (songOffset + 3 < songEnd) {
int nextSongOffset = songOffset + GetByte(9) - '0';
if (GetByte(songOffset) == 0xfe) {
// song jump
Copy(songOffset + 2); // copy 0xfe, line_number
RelocateWords(1); // relocate jump address
}
if (nextSongOffset > songEnd)
nextSongOffset = songEnd;
Copy(nextSongOffset);
songOffset = nextSongOffset;
}
Copy(songEnd);
if (moduleLen >= songEnd + 5)
RelocateWords(2); // DOS header of text info: title and instrument names
break;
case ASAPModuleType.Tmc:
// * -> TMC
RelocateWords(3); // DOS header
Copy(6 + 32); // TMC header
RelocateLowHigh(64); // instruments
RelocateLowHigh(128); // patterns
break;
case ASAPModuleType.Tm2:
// * -> TM2
RelocateWords(3); // DOS header
Copy(6 + 128); // TM2 header
RelocateBytes(6 + 128, 6 + 128 + 128 + 512, 128, 0); // instruments/low
RelocateLowHigh(256); // patterns
RelocateBytes(6 + 128, 6 + 128 + 128 + 512, 128, 8); // instruments/high
break;
default:
throw ASAPConversionException("Impossible conversion");
}
Copy(moduleLen); // copy remaining bytes
}
}
/// Static methods for writing modules in different formats.
public class ASAPWriter
{
/// Maximum number of extensions returned by `GetSaveExts`.
public const int MaxSaveExts = 3;
public ASAPWriter()
{
}
/// Enumerates possible file types the given module can be written as.
/// Returns the number of extensions written to `exts`.
public static int GetSaveExts(
/// Receives filename extensions without the leading dot.
/// Must be `MaxSaveExts` long.
string[]! exts,
/// File information.
ASAPInfo info,
/// Contents of the file.
byte[] module,
/// Length of the file.
int moduleLen)
{
int i = 0;
switch (info.Type) {
case ASAPModuleType.SapB:
case ASAPModuleType.SapC:
exts[i++] = "sap";
string? ext = info.GetOriginalModuleExt(module, moduleLen);
if (ext != null)
exts[i++] = ext;
exts[i++] = "xex";
break;
case ASAPModuleType.SapD:
exts[i++] = "sap";
if (info.GetPlayerRateScanlines() == 312)
exts[i++] = "xex";
break;
case ASAPModuleType.SapS:
exts[i++] = "sap";
break;
default:
exts[i++] = info.GetOriginalModuleExt(module, moduleLen);
exts[i++] = "sap";
exts[i++] = "xex";
break;
}
return i;
}
static void TwoDigitsToString(byte[]! result, int offset, int value)
{
result[offset] = '0' + value / 10;
result[offset + 1] = '0' + value % 10;
}
static bool SecondsToString(byte[]! result, int offset, int value)
{
if (value < 0 || value >= 100 * 60 * 1000)
return false;
value /= 1000;
TwoDigitsToString(result, offset, value / 60);
result[offset + 2] = ':';
TwoDigitsToString(result, offset + 3, value % 60);
return true;
}
/// Maximum length of text representation of a duration.
/// Corresponds to the longest format which is `"mm:ss.xxx"`.
public const int MaxDurationLength = 9;
/// Writes text representation of the given duration.
/// Returns the number of bytes written to `result`.
public static int DurationToString(
/// The output buffer.
byte[]! result,
/// Number of milliseconds.
int value)
{
if (!SecondsToString(result, 0, value))
return 0;
value %= 1000;
if (value == 0)
return 5;
result[5] = '.';
TwoDigitsToString(result, 6, value / 10);
value %= 10;
if (value == 0)
return 8;
result[8] = '0' + value;
return 9;
}
internal byte[]! Output;
internal int OutputOffset;
int OutputEnd;
/// Sets the destination array for `Write`.
public void SetOutput!(
/// The destination array.
byte[]! output,
/// The array offset to start writing at.
int startIndex,
/// The array offset to finish writing before.
int endIndex)
{
Output = output;
OutputOffset = startIndex;
OutputEnd = endIndex;
}
internal void WriteByte!(int value)
throws ASAPConversionException
{
if (OutputOffset >= OutputEnd)
throw ASAPConversionException("Output full");
Output[OutputOffset++] = value;
}
internal void WriteWord!(int value)
throws ASAPConversionException
{
WriteByte(value & 0xff);
WriteByte(value >> 8);
}
internal void WriteBytes!(byte[] array, int startIndex, int endIndex)
throws ASAPConversionException
{
int length = endIndex - startIndex;
if (OutputOffset + length > OutputEnd)
throw ASAPConversionException("Output full");
array.CopyTo(startIndex, Output, OutputOffset, length);
OutputOffset += length;
}
void WriteString!(string s)
throws ASAPConversionException
{
foreach (int c in s)
WriteByte(c);
}
void WriteDec!(int value)
throws ASAPConversionException
{
if (value >= 10) {
WriteDec(value / 10);
value %= 10;
}
WriteByte('0' + value);
}
void WriteTextSapTag!(string tag, string value)
throws ASAPConversionException
{
WriteString(tag);
WriteByte('"');
if (value.Length == 0)
value = "<?>";
WriteString(value);
WriteByte('"');
WriteByte('\r');
WriteByte('\n');
}
void WriteDecSapTag!(string tag, int value)
throws ASAPConversionException
{
WriteString(tag);
WriteDec(value);
WriteByte('\r');
WriteByte('\n');
}
void WriteHexSapTag!(string tag, int value)
throws ASAPConversionException
{
if (value < 0)
return;
WriteString(tag);
for (int i = 12; i >= 0; i -= 4) {
int digit = (value >> i) & 0xf;
WriteByte(digit + (digit < 10 ? '0' : 'A' - 10));
}
WriteByte('\r');
WriteByte('\n');
}
void WriteSapHeader!(ASAPInfo info, int type, int init, int player)
throws ASAPConversionException
{
WriteString("SAP\r\n");
WriteTextSapTag("AUTHOR ", info.GetAuthor());
WriteTextSapTag("NAME ", info.GetTitle());
WriteTextSapTag("DATE ", info.GetDate());
if (info.GetSongs() > 1) {
WriteDecSapTag("SONGS ", info.GetSongs());
if (info.GetDefaultSong() > 0)
WriteDecSapTag("DEFSONG ", info.GetDefaultSong());
}
if (info.GetChannels() > 1)
WriteString("STEREO\r\n");
if (info.IsNtsc())
WriteString("NTSC\r\n");
WriteString("TYPE ");
WriteByte(type);
WriteByte('\r');
WriteByte('\n');
if (info.GetPlayerRateScanlines() != (type == 'S' ? 78 : 312) || info.IsNtsc())
WriteDecSapTag("FASTPLAY ", info.GetPlayerRateScanlines());
if (type == 'C')
WriteHexSapTag("MUSIC ", info.GetMusicAddress());
WriteHexSapTag("INIT ", init);
WriteHexSapTag("PLAYER ", player);
WriteHexSapTag("COVOX ", info.GetCovoxAddress());
for (int song = 0; song < info.GetSongs(); song++) {
if (info.GetDuration(song) < 0)
break;
WriteString("TIME ");
byte[MaxDurationLength] s;
WriteBytes(s, 0, DurationToString(s, info.GetDuration(song)));
if (info.GetLoop(song))
WriteString(" LOOP");
WriteByte('\r');
WriteByte('\n');
}
}
void WriteExecutableHeader!(int[]!? initAndPlayer, ASAPInfo info, int type, int init, int player)
throws ASAPConversionException
{
if (initAndPlayer == null)
WriteSapHeader(info, type, init, player);
else {
initAndPlayer[0] = init;
initAndPlayer[1] = player;
}
}
void WritePlaTaxLda0!()
throws ASAPConversionException
{
WriteByte(0x68);
WriteByte(0xaa);
WriteByte(0xa9);
WriteByte(0);
}
void WriteCmcInit!(int[]!? initAndPlayer, ASAPInfo info)
throws ASAPConversionException
{
if (initAndPlayer == null)
return; // to SAP
const int initCmc = 0xfe0; // cms.obx ends at 0xfbe
WriteWord(initCmc);
WriteWord(initCmc + 16);
WriteByte(0x48); // PHA
int music = info.GetMusicAddress();
WriteByte(0xa2); WriteByte(music & 0xff); // LDX #<MUSIC
WriteByte(0xa0); WriteByte(music >> 8); // LDY #>MUSIC
WriteByte(0xa9); WriteByte(0x70); // LDA #$70
WriteByte(0x20); WriteWord(initAndPlayer[1] + 3); // JSR PLAYER+3
WritePlaTaxLda0(); // PLA; TAX; LDA #0
WriteByte(0x4c); WriteWord(initAndPlayer[1] + 3); // JMP PLAYER+3
initAndPlayer[0] = initCmc;
initAndPlayer[1] += 6;
}
void WriteExecutableFromSap!(int[]! initAndPlayer, ASAPInfo info, int type, byte[] module, int moduleLen)
throws ASAPConversionException
{
WriteExecutableHeader(initAndPlayer, info, type, info.GetInitAddress(), info.Player);
WriteBytes(module, info.HeaderLen, moduleLen);
}
ushort WriteExecutableHeaderForSongPos!(int[]! initAndPlayer, ASAPInfo info, int player, int codeForOneSong, int codeForManySongs, int playerOffset)
throws ASAPConversionException
{
if (info.GetSongs() != 1) {
WriteExecutableHeader(initAndPlayer, info, 'B', player - codeForManySongs, player + playerOffset);
return player - codeForManySongs - info.GetSongs();
}
WriteExecutableHeader(initAndPlayer, info, 'B', player - codeForOneSong, player + playerOffset);
return player - codeForOneSong;
}
internal void WriteExecutable!(int[]!? initAndPlayer, ASAPInfo info, byte[] module, int moduleLen)
throws ASAPConversionException
{
byte[]? playerRoutine = ASAP6502.GetPlayerRoutine(info);
int player = -1;
int playerLastByte = -1;
int music = info.GetMusicAddress();
if (playerRoutine != null) {
player = ASAPInfo.GetWord(playerRoutine, 2);
playerLastByte = ASAPInfo.GetWord(playerRoutine, 4);
if (music <= playerLastByte)
throw ASAPConversionException("Module address conflicts with the player routine");
}
int startAddr;
switch (info.Type) {
case ASAPModuleType.SapB:
WriteExecutableFromSap(initAndPlayer, info, 'B', module, moduleLen);
break;
case ASAPModuleType.SapC:
WriteExecutableFromSap(initAndPlayer, info, 'C', module, moduleLen);
WriteCmcInit(initAndPlayer, info);
break;
case ASAPModuleType.SapD:
WriteExecutableFromSap(initAndPlayer, info, 'D', module, moduleLen);
break;
case ASAPModuleType.SapS:
WriteExecutableFromSap(initAndPlayer, info, 'S', module, moduleLen);
break;
case ASAPModuleType.Cmc:
case ASAPModuleType.Cm3:
case ASAPModuleType.Cmr:
case ASAPModuleType.Cms:
WriteExecutableHeader(initAndPlayer, info, 'C', -1, player);
WriteWord(0xffff); // some modules start with zeros
WriteBytes(module, 2, moduleLen);
WriteBytes(playerRoutine, 2, playerLastByte - player + 7);
WriteCmcInit(initAndPlayer, info);
break;
case ASAPModuleType.Dlt:
startAddr = WriteExecutableHeaderForSongPos(initAndPlayer, info, player, 5, 7, 0x103);
if (moduleLen == 0x2c06) {
// append zero to the module
WriteBytes(module, 0, 4);
WriteWord(0x4c00);
WriteBytes(module, 6, moduleLen);
WriteByte(0);
}
else
WriteBytes(module, 0, moduleLen);
WriteWord(startAddr);
WriteWord(playerLastByte);
if (info.GetSongs() != 1) {
WriteBytes(info.SongPos, 0, info.GetSongs());
WriteByte(0xaa); // TAX
WriteByte(0xbc); WriteWord(startAddr); // LDY SONG2POS,X
}
else {
WriteByte(0xa0); WriteByte(0); // LDY #0
}
WriteByte(0x4c); WriteWord(player + 0x100); // JMP PLAYER+$100
WriteBytes(playerRoutine, 6, playerLastByte - player + 7);
break;
case ASAPModuleType.Mpt:
startAddr = WriteExecutableHeaderForSongPos(initAndPlayer, info, player, 13, 17, 3);
WriteBytes(module, 0, moduleLen);
WriteWord(startAddr);
WriteWord(playerLastByte);
if (info.GetSongs() != 1) {
WriteBytes(info.SongPos, 0, info.GetSongs());
WriteByte(0x48); // PHA
}
WriteByte(0xa0); WriteByte(music & 0xff); // LDY #<MUSIC
WriteByte(0xa2); WriteByte(music >> 8); // LDX #>MUSIC
WriteByte(0xa9); WriteByte(0); // LDA #0
WriteByte(0x20); WriteWord(player); // JSR PLAYER
if (info.GetSongs() != 1) {
WriteByte(0x68); WriteByte(0xa8); // PLA; TAY
WriteByte(0xbe); WriteWord(startAddr); // LDX SONG2POS,Y
}
else {
WriteByte(0xa2); WriteByte(0); // LDX #0
}
WriteByte(0xa9); WriteByte(2); // LDA #2
WriteBytes(playerRoutine, 6, playerLastByte - player + 7);
break;
case ASAPModuleType.Rmt:
WriteExecutableHeader(initAndPlayer, info, 'B', ASAPInfo.RmtInit, 0x603);
WriteBytes(module, 0, ASAPInfo.GetWord(module, 4) - music + 7);
WriteWord(ASAPInfo.RmtInit);
if (info.GetSongs() != 1) {
WriteWord(ASAPInfo.RmtInit + 10 + info.GetSongs());
WriteByte(0xa8); // TAY
WriteByte(0xb9); WriteWord(ASAPInfo.RmtInit + 11); // LDA SONG2POS,Y
}
else {
WriteWord(ASAPInfo.RmtInit + 8);
WriteByte(0xa9); WriteByte(0); // LDA #0
}
WriteByte(0xa2); WriteByte(music & 0xff); // LDX #<MUSIC
WriteByte(0xa0); WriteByte(music >> 8); // LDY #>MUSIC
WriteByte(0x4c); WriteWord(0x600); // JMP PLAYER
if (info.GetSongs() != 1)
WriteBytes(info.SongPos, 0, info.GetSongs());
WriteBytes(playerRoutine, 2, playerLastByte - player + 7);
break;
case ASAPModuleType.Tmc:
int perFrame = module[0x25];
const int[4] tmcPlayerOffset = { 3, -9, -10, -10 };
int player2 = player + tmcPlayerOffset[perFrame - 1];
const int[4] tmcInitOffset = { -14, -16, -17, -17 };
startAddr = player2 + tmcInitOffset[perFrame - 1];
if (info.GetSongs() != 1)
startAddr -= 3;
WriteExecutableHeader(initAndPlayer, info, 'B', startAddr, player2);
WriteBytes(module, 0, moduleLen);
WriteWord(startAddr);
WriteWord(playerLastByte);
if (info.GetSongs() != 1)
WriteByte(0x48); // PHA
WriteByte(0xa0); WriteByte(music & 0xff); // LDY #<MUSIC
WriteByte(0xa2); WriteByte(music >> 8); // LDX #>MUSIC
WriteByte(0xa9); WriteByte(0x70); // LDA #$70
WriteByte(0x20); WriteWord(player); // JSR PLAYER
if (info.GetSongs() != 1)
WritePlaTaxLda0(); // PLA; TAX; LDA #0
else {
WriteByte(0xa9); WriteByte(0x60); // LDA #$60
}
switch (perFrame) {
case 2:
WriteByte(0x06); WriteByte(0); // ASL 0
WriteByte(0x4c); WriteWord(player); // JMP PLAYER
WriteByte(0xa5); WriteByte(0); // LDA 0
WriteByte(0xe6); WriteByte(0); // INC 0
WriteByte(0x4a); // LSR @
WriteByte(0x90); WriteByte(5); // BCC PLAYER+3
WriteByte(0xb0); WriteByte(6); // BCS PLAYER+6
break;
case 3:
case 4:
WriteByte(0xa0); WriteByte(1); // LDY #1
WriteByte(0x84); WriteByte(0); // STY 0
WriteByte(0xd0); WriteByte(10); // BNE PLAYER
WriteByte(0xc6); WriteByte(0); // DEC 0
WriteByte(0xd0); WriteByte(12); // BNE PLAYER+6
WriteByte(0xa0); WriteByte(perFrame); // LDY #3
WriteByte(0x84); WriteByte(0); // STY 0
WriteByte(0xd0); WriteByte(3); // BNE PLAYER+3
break;
default:
break;
}
WriteBytes(playerRoutine, 6, playerLastByte - player + 7);
break;
case ASAPModuleType.Tm2:
const int tm2Init = 0x1380;
WriteExecutableHeader(initAndPlayer, info, 'B', tm2Init, 0x803);
WriteBytes(module, 0, moduleLen);
WriteWord(tm2Init);
if (info.GetSongs() != 1) {
WriteWord(tm2Init + 16);
WriteByte(0x48); // PHA
}
else
WriteWord(tm2Init + 14);
WriteByte(0xa0); WriteByte(music & 0xff); // LDY #<MUSIC
WriteByte(0xa2); WriteByte(music >> 8); // LDX #>MUSIC
WriteByte(0xa9); WriteByte(0x70); // LDA #$70
WriteByte(0x20); WriteWord(0x800); // JSR PLAYER
if (info.GetSongs() != 1)
WritePlaTaxLda0(); // PLA; TAX; LDA #0
else {
WriteByte(0xa9); WriteByte(0); // LDA #0
WriteByte(0xaa); // TAX
}
WriteByte(0x4c); WriteWord(0x800); // JMP PLAYER
WriteBytes(playerRoutine, 2, playerLastByte - player + 7);
break;
case ASAPModuleType.Fc:
WriteExecutableHeader(initAndPlayer, info, 'B', player, player + 3);
WriteWord(0xffff);
WriteWord(music);
WriteWord(music + moduleLen - 1);
WriteBytes(module, 0, moduleLen);
WriteBytes(playerRoutine, 2, playerLastByte - player + 7);
break;
}
}
const int XexInfoCharactersPerLine = 32;
static int PadXexInfo(byte[]! dest, int offset, int endColumn)
{
while (offset % XexInfoCharactersPerLine != endColumn)
dest[offset++] = ' ';
return offset;
}
static int FormatXexInfoText(byte[]! dest, int destLen, int endColumn, string src, bool author)
{
int srcLen = src.Length;
for (int srcOffset = 0; srcOffset < srcLen; ) {
int c = src[srcOffset++];
if (c == ' ') {
if (author && srcOffset < srcLen && src[srcOffset] == '&') {
int authorLen;
for (authorLen = 1; srcOffset + authorLen < srcLen; authorLen++) {
if (src[srcOffset + authorLen] == ' ' && srcOffset + authorLen + 1 < srcLen && src[srcOffset + authorLen + 1] == '&')
break;
}
if (authorLen <= XexInfoCharactersPerLine && destLen % XexInfoCharactersPerLine + 1 + authorLen > XexInfoCharactersPerLine) {
destLen = PadXexInfo(dest, destLen, 1); // align author names after "by" and "&"
continue;
}
}
int wordLen;
for (wordLen = 0; srcOffset + wordLen < srcLen && src[srcOffset + wordLen] != ' '; wordLen++) {
}
if (wordLen <= XexInfoCharactersPerLine && destLen % XexInfoCharactersPerLine + 1 + wordLen > XexInfoCharactersPerLine) {
destLen = PadXexInfo(dest, destLen, 0);
continue;
}
}
dest[destLen++] = c;
}
return PadXexInfo(dest, destLen, endColumn);
}
void WriteXexInfoTextDl!(int address, int len, int verticalScrollAt)
throws ASAPConversionException
{
WriteByte(verticalScrollAt == 0 ? 0x62 : 0x42);
WriteWord(address);
for (int i = XexInfoCharactersPerLine; i < len; i += XexInfoCharactersPerLine)
WriteByte(i == verticalScrollAt ? 0x22 : 2);
}
void WriteXexInfo!(ASAPInfo info)
throws ASAPConversionException
{
byte[256] title;
int titleLen = FormatXexInfoText(title, 0, 0, info.GetTitle().Length == 0 ? "(untitled)" : info.GetTitle(), false);
byte[256] author;
int authorLen;
if (info.GetAuthor().Length > 0) {
author[0] = 'b';
author[1] = 'y';
author[2] = ' ';
authorLen = FormatXexInfoText(author, 3, 0, info.GetAuthor(), true);
}
else
authorLen = 0;
byte[256] other;
int otherLen = FormatXexInfoText(other, 0, XexInfoCharactersPerLine - 13, info.GetDate(), false);
otherLen = FormatXexInfoText(other, otherLen, XexInfoCharactersPerLine - 5, info.GetChannels() > 1 ? " STEREO" : " MONO", false);
int duration = info.GetDuration(info.GetDefaultSong());
if (duration > 0 && SecondsToString(other, otherLen, duration + 999)) // round up to full seconds
otherLen += 5;
else
otherLen = PadXexInfo(other, otherLen, 0);
const int xexInfoDl = 0xfc50; // must match xexinfo.asx
int totalCharacters = titleLen + authorLen + otherLen;
int totalLines = totalCharacters / XexInfoCharactersPerLine;
int otherAddress = xexInfoDl - otherLen;
#if HIDE_AUTHOR
int authorAddress = otherAddress - authorLen;
int hiddenAddress = authorAddress - authorLen;
int titleAddress = hiddenAddress - 8 - titleLen;
#else
int titleAddress = otherAddress - authorLen - 8 - titleLen;
#endif
WriteWord(titleAddress);
WriteBytes(resource<byte[]>("xexinfo.obx"), 4, 6);
WriteBytes(title, 0, titleLen);
for (int i = 0; i < 8; i++)
WriteByte(0x55);
#if HIDE_AUTHOR
if (authorLen > 0) {
WriteString("(press space to show author)");
for (int i = 28; i < authorLen; i++)
WriteByte(' ');
WriteBytes(author, 0, authorLen);
}
#else
WriteBytes(author, 0, authorLen);
#endif
WriteBytes(other, 0, otherLen);
for (int i = totalLines; i < 26; i++)
WriteByte(0x70);
WriteByte(0x30);
WriteXexInfoTextDl(titleAddress, titleLen, titleLen - XexInfoCharactersPerLine);
WriteByte(8);
WriteByte(0);
#if HIDE_AUTHOR
if (authorLen > 0)
WriteXexInfoTextDl(hiddenAddress, authorLen, -1);
WriteByte(0x10);
WriteXexInfoTextDl(otherAddress, otherLen, -1);
WriteByte(0x41);
WriteWord(xexInfoDl);
if (authorLen > 0) {
int dlAuthor = xexInfoDl + 32 - totalLines + titleLen / XexInfoCharactersPerLine;
WriteByte(0xa9); WriteByte(authorAddress & 0xff); // LDA #<author
WriteByte(0x8d); WriteWord(dlAuthor); // STA dl_author
WriteByte(0xa9); WriteByte(authorAddress >> 8); // LDA #>author
WriteByte(0x8d); WriteWord(dlAuthor + 1); // STA dl_author+1
}
else {
// pad two bytes because DL is shorter due to no LMS for author
// show_author is just RTS, pad with more RTSes
for (int i = 0; i < 12; i++)
WriteByte(0x60);
}
#else
for (int i = 0; i < authorLen; i += XexInfoCharactersPerLine)
WriteByte(2);
WriteByte(0x10);
for (int i = 0; i < otherLen; i += XexInfoCharactersPerLine)
WriteByte(2);
#endif
WriteBytes(resource<byte[]>("xexinfo.obx"), 6, resource<byte[]>("xexinfo.obx").Length);
}
void WriteNative!(ASAPInfo info, byte[] module, int moduleLen)
throws ASAPConversionException
{
ASAPNativeModuleWriter() nativeWriter;
nativeWriter.Writer = this;
nativeWriter.SourceModule = module;
ASAPModuleType type = info.Type;
switch (type) {
case ASAPModuleType.SapB:
case ASAPModuleType.SapC:
// SAP -> native
int offset = info.GetRmtSapOffset(module, moduleLen);
if (offset > 0) {
// RMT-generated SAP -> RMT
nativeWriter.SourceOffset = offset - 2;
nativeWriter.Write(info, ASAPModuleType.Rmt, moduleLen - offset + 2);
return;
}
nativeWriter.SourceOffset = info.HeaderLen;
int blockLen = nativeWriter.GetWord(4) - nativeWriter.GetWord(2) + 7;
if (blockLen < 7 || info.HeaderLen + blockLen >= moduleLen)
throw ASAPConversionException("Cannot extract module from SAP");
type = info.GetOriginalModuleType(module, moduleLen);
if (type == ASAPModuleType.Fc)
WriteBytes(module, info.HeaderLen + 6, info.HeaderLen + blockLen); // SAP -> FC
else
nativeWriter.Write(info, type, blockLen); // SAP -> native
break;
case ASAPModuleType.Fc:
// FC -> FC
WriteBytes(module, 0, moduleLen);
return;
default:
// native -> native
nativeWriter.SourceOffset = 0;
nativeWriter.Write(info, type, moduleLen);
break;
}
}
/// Writes the given module in a possibly different file format.
public uint Write!(
/// Output filename, used to determine the format.
string targetFilename,
/// File information got from the source file with data updated for the output file.
ASAPInfo info,
/// Contents of the source file.
byte[] module,
/// Length of the source file.
int moduleLen,
/// Display information (xex output only).
bool tag)
throws ASAPConversionException
{
int destExt = ASAPInfo.GetPackedExt(targetFilename);
switch (destExt) {
case ASAPInfo.PackExt("SAP"):
// * -> SAP
WriteExecutable(null, info, module, moduleLen);
return OutputOffset;
case ASAPInfo.PackExt("XEX"):
// * -> XEX
{
int[2] initAndPlayer;
WriteExecutable(initAndPlayer, info, module, moduleLen);
switch (info.Type) {
case ASAPModuleType.SapD:
if (info.GetPlayerRateScanlines() != 312)
throw ASAPConversionException("Impossible conversion");
WriteBytes(resource<byte[]>("xexd.obx"), 2, resource<byte[]>("xexd.obx").Length);
WriteWord(initAndPlayer[0]);
if (initAndPlayer[1] < 0) {
WriteByte(0x60); // RTS
WriteByte(0x60); // don't care
WriteByte(0x60); // don't care
}
else {
WriteByte(0x4c); // JMP
WriteWord(initAndPlayer[1]);
}
WriteByte(info.GetDefaultSong());
break;
case ASAPModuleType.SapS:
throw ASAPConversionException("Impossible conversion");
default:
WriteBytes(resource<byte[]>("xexb.obx"), 2, resource<byte[]>("xexb.obx").Length);
WriteWord(initAndPlayer[0]);
WriteByte(0x4c); // JMP
WriteWord(initAndPlayer[1]);
WriteByte(info.GetDefaultSong());
int fastplay = info.GetPlayerRateScanlines();
WriteByte(fastplay & 1);
WriteByte((fastplay >> 1) % 156);
WriteByte((fastplay >> 1) % 131);
WriteByte(fastplay / 312);
WriteByte(fastplay / 262);
break;
}
if (tag)
WriteXexInfo(info);
WriteWord(0x2e0);
WriteWord(0x2e1);
WriteWord(tag ? 0x100 : 0x124); // must match xexinfo.asx, xexb.asx, xexd.asx
FlashPack() flashPack;
flashPack.Compress(this);
return OutputOffset;
}
default:
string? possibleExt = info.GetOriginalModuleExt(module, moduleLen);
if (possibleExt != null) {
int packedPossibleExt = ASAPInfo.PackExt(possibleExt);
if (destExt == packedPossibleExt
|| (destExt == ASAPInfo.PackExt("TM8") && packedPossibleExt == ASAPInfo.PackExt("TMC"))) {
// * -> native
WriteNative(info, module, moduleLen);
return OutputOffset;
}
}
throw ASAPConversionException("Impossible conversion");
}
}
}