-
Notifications
You must be signed in to change notification settings - Fork 4
/
asmgen.py
executable file
·1697 lines (1404 loc) · 58.4 KB
/
asmgen.py
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
#!/usr/bin/env python
# system packages
import sys
import os
import argparse
import re
# external packages
import png # package name is "pypng" on pypi.python.org
import numpy as np
def slugify(s):
"""Simplifies ugly strings into something that can be used as an assembler
label.
>>> print slugify("[Some] _ Article's Title--")
SOME_ARTICLES_TITLE
From https://gist.github.com/dolph/3622892#file-slugify-py
"""
# "[Some] _ Article's Title--"
# "[SOME] _ ARTICLE'S TITLE--"
s = s.upper()
# "[SOME] _ ARTICLE'S_TITLE--"
# "[SOME]___ARTICLE'S_TITLE__"
for c in [' ', '-', '.', '/']:
s = s.replace(c, '_')
# "[SOME]___ARTICLE'S_TITLE__"
# "SOME___ARTICLES_TITLE__"
s = re.sub('\W', '', s)
# "SOME___ARTICLES_TITLE__"
# "SOME ARTICLES TITLE "
s = s.replace('_', ' ')
# "SOME ARTICLES TITLE "
# "SOME ARTICLES TITLE "
s = re.sub('\s+', ' ', s)
# "SOME ARTICLES TITLE "
# "SOME ARTICLES TITLE"
s = s.strip()
# "SOME ARTICLES TITLE"
# "SOME_ARTICLES_TITLE"
s = s.replace(' ', '_')
return s
class AssemblerSyntax(object):
extension = "s"
comment_char = ";"
comma_string = ", "
use_16_bit = False
def asm(self, text):
return "\t%s" % text
def comment(self, text):
return "\t%s %s" % (self.comment_char, text)
def label(self, text):
return text
def byte(self, text):
return self.asm(".byte %s" % text)
def word(self, text):
return self.asm(".word %s" % text)
def address(self, text):
return self.asm(".addr %s" % text)
def origin(self, text):
return self.asm("*= %s" % text)
def include(self, text):
return self.asm(".include \"%s\"" % text)
def binary_constant(self, value):
try:
# already a string
_ = len(value)
return "#%%%s" % value
except TypeError:
return "#%%%s" % format(value, "08b")
class Mac65(AssemblerSyntax):
def address(self, text):
return self.asm(".word %s" % text)
def binary_constant(self, value):
try:
# a string
value = int(value, 2)
except TypeError:
pass
return "#~%s" % format(value, "08b")
class CC65(AssemblerSyntax):
extension = "s"
def label(self, text):
return "%s:" % text
class CSource(AssemblerSyntax):
extension = "c"
use_16_bit = True
def label(self, text):
return f"{text} = "
class Merlin(AssemblerSyntax):
extension = "S"
comma_string = ","
def byte(self, text):
return self.asm("db %s" % text)
def word(self, text):
return self.asm("dw %s" % text)
def address(self, text):
return self.asm("da %s" % text)
def origin(self, text):
return self.asm("org %s" % text)
def include(self, text):
return self.asm("PUT %s" % text)
class Listing(object):
def __init__(self, assembler, slug="asmgen-driver"):
self.assembler = assembler
self.lines = []
self.current = None
self.desired_count = 1
self.stash_list = []
self.slug = slug
def __str__(self):
self.flush_stash()
return "\n".join(self.lines) + "\n"
def add_listing(self, other):
self.lines.extend(other.lines)
def get_filename(self, basename):
return "%s-%s.%s" % (basename, self.slug.lower(), self.assembler.extension)
def write(self, basename, disclaimer):
filename = self.get_filename(basename)
print(f"Writing to {filename}")
with open(filename, "w") as fh:
fh.write(disclaimer + "\n\n")
fh.write(str(self))
return filename
def out(self, line=""):
self.flush_stash()
self.lines.append(line)
def out_append_last(self, line):
self.lines[-1] += line
def pop_asm(self, cmd=""):
self.flush_stash()
if cmd:
search = self.assembler.asm(cmd)
i = -1
while self.lines[i].strip().startswith(self.assembler.comment_char):
i -= 1
if self.lines[i] == search:
self.lines.pop(i)
else:
self.lines.pop(-1)
def label(self, text):
self.out(self.assembler.label(text))
def comment(self, text):
self.out_append_last(self.assembler.comment(text))
def comment_line(self, text):
self.out(self.assembler.comment(text))
def asm(self, text):
self.out(self.assembler.asm(text))
def addr(self, text):
self.out(self.assembler.address(text))
def include(self, text):
self.out(self.assembler.include(text))
def flush_stash(self):
if self.current is not None and len(self.stash_list) > 0:
self.lines.append(self.current(self.assembler.comma_string.join(self.stash_list)))
self.current = None
self.stash_list = []
self.desired_count = 1
def stash(self, desired, text, per_line):
if self.current is not None and (self.current != desired or per_line == 1):
self.flush_stash()
if per_line > 1:
if self.current is None:
self.current = desired
self.desired_count = per_line
self.stash_list.append(text)
if len(self.stash_list) >= self.desired_count:
self.flush_stash()
else:
self.out(desired(text))
def binary_constant(self, value):
return self.assembler.binary_constant(value)
def byte(self, text, per_line=1):
self.stash(self.assembler.byte, text, per_line)
def word(self, text, per_line=1):
self.stash(self.assembler.word, text, per_line)
class Sprite(Listing):
backing_store_sizes = set()
def __init__(self, slug, pngdata, assembler, screen, xdraw=False, use_mask=False, backing_store=False, clobber=False, double_buffer=False, damage=False, processor="any"):
Listing.__init__(self, assembler)
self.slug = slug
self.screen = screen
self.xdraw = xdraw
self.use_mask = use_mask
self.backing_store = backing_store
self.clobber = clobber
self.double_buffer = double_buffer
self.damage = damage
self.processor = processor
self.width = pngdata[0]
self.height = pngdata[1]
self.pixel_data = list(pngdata[2])
self.jump_table()
for i in range(self.screen.num_shifts):
self.blit_shift(i)
def jump_table(self):
# Prologue
self.label("%s" % self.slug)
self.comment("%d bytes per row" % self.screen.byte_width(self.width))
if self.processor == "any":
self.out(".ifpC02")
self.jump65C02()
self.out(".else")
self.jump6502()
self.out(".endif")
elif self.processor == "65C02":
self.jump65C02()
elif self.processor == "6502":
self.jump6502()
else:
raise RuntimeError("Processor %s not supported" % self.processor)
def save_axy_65C02(self):
self.asm("pha")
self.asm("phx")
self.asm("phy")
def restore_axy_65C02(self):
self.asm("ply")
self.asm("plx")
self.asm("pla")
def save_axy_6502(self):
self.asm("pha")
self.asm("txa")
self.asm("pha")
self.asm("tya")
self.asm("pha")
def restore_axy_6502(self):
self.asm("pla")
self.asm("tay")
self.asm("pla")
self.asm("tax")
self.asm("pla")
def jump65C02(self):
if not self.clobber:
self.save_axy_65C02()
self.asm("ldy param_x")
self.asm("ldx MOD%d_%d,y" % (self.screen.num_shifts, self.screen.bits_per_pixel))
self.asm("jmp (%s_JMP,x)\n" % (self.slug))
offset_suffix = ""
# Bit-shift jump table for 65C02
self.label("%s_JMP" % (self.slug))
for shift in range(self.screen.num_shifts):
self.addr("%s_SHIFT%d" % (self.slug, shift))
def jump6502(self):
if not self.clobber:
self.save_axy_6502()
self.asm("ldy param_x")
self.asm("ldx MOD%d_%d,y" % (self.screen.num_shifts, self.screen.bits_per_pixel))
# Fast jump table routine; faster and smaller than self-modifying code
self.asm("lda %s_JMP+1,x" % (self.slug))
self.asm("pha")
self.asm("lda %s_JMP,x" % (self.slug))
self.asm("pha")
self.asm("rts\n")
# Bit-shift jump table for generic 6502
self.label("%s_JMP" % (self.slug))
for shift in range(self.screen.num_shifts):
self.addr("%s_SHIFT%d-1" % (self.slug,shift))
def blit_shift(self, shift):
# Blitting functions
self.out("\n")
# Track cycle count of the blitter. We start with fixed overhead:
# SAVE_AXY + RESTORE_AXY + rts + sprite jump table
cycle_count = 9 + 12 + 6 + 3 + 4 + 6
baselabel = "%s_SHIFT%d" % (self.slug,shift)
self.label(baselabel)
color_streams = self.screen.byte_streams_from_pixels(shift, self)
mask_streams = self.screen.byte_streams_from_pixels(shift, self, True)
for c, m in zip(color_streams, mask_streams):
self.comment_line(str(c) + " " + str(m))
self.out("")
if self.backing_store:
byte_width = len(color_streams[0])
self.asm("jsr savebg_%dx%d" % (byte_width, self.height))
self.backing_store_sizes.add((byte_width, self.height))
cycle_count += 6
cycle_count, optimization_count = self.generate_blitter(color_streams, mask_streams, cycle_count, baselabel)
if not self.clobber:
if self.processor == "any":
self.out(".ifpC02")
self.restore_axy_65C02()
self.out(".else")
self.restore_axy_6502()
self.out(".endif")
elif self.processor == "65C02":
self.restore_axy_65C02()
elif self.processor == "6502":
self.restore_axy_6502()
else:
raise RuntimeError("Processor %s not supported" % self.processor)
if self.damage:
# the caller knows param_x and param_y for location, so no need
# to report those again. But the size varies by sprite (and perhaps
# by shift amount?) so store it here
byte_width = len(color_streams[0])
self.asm("lda #%d" % byte_width)
self.asm("sta DAMAGE_W")
self.asm("lda #%d" % self.height)
self.asm("sta DAMAGE_H")
self.out()
self.asm("rts")
self.comment("Cycle count: %d, Optimized %d rows." % (cycle_count,optimization_count))
def generate_blitter(self, color_streams, mask_streams, base_cycle_count, baselabel):
byte_width = len(color_streams[0])
cycle_count = base_cycle_count
optimization_count = 0
order = list(range(self.height))
for row in order:
cycle_count += self.row_start_calculator_code(row, baselabel)
byte_splits = color_streams[row]
mask_splits = mask_streams[row]
byte_count = len(byte_splits)
# number of trailing iny to remove due to unchanged bytes at the
# end of the row
skip_iny = 0
# Generate blitting code
for index, (value, mask) in enumerate(zip(byte_splits, mask_splits)):
if index > 0:
self.asm("iny")
cycle_count += 2
# Optimization
if mask == "01111111":
optimization_count += 1
self.comment_line("byte %d: skipping! unchanged byte (mask = %s)" % (index, mask))
skip_iny += 1
else:
value = self.binary_constant(value)
skip_iny = 0
# Store byte into video memory
if self.xdraw:
self.asm("lda (scratch_addr),y")
self.asm("eor %s" % value)
self.asm("sta (scratch_addr),y");
cycle_count += 5 + 2 + 6
elif self.use_mask:
if mask == "00000000":
# replacing all the bytes; no need for and/or!
self.asm("lda %s" % value)
self.asm("sta (scratch_addr),y");
cycle_count += 2 + 5
else:
mask = self.binary_constant(mask)
self.asm("lda (scratch_addr),y")
self.asm("and %s" % mask)
self.asm("ora %s" % value)
self.asm("sta (scratch_addr),y");
cycle_count += 5 + 2 + 2 + 6
else:
self.asm("lda %s" % value)
self.asm("sta (scratch_addr),y");
cycle_count += 2 + 6
while skip_iny > 0:
self.pop_asm("iny")
skip_iny -= 1
cycle_count -= 2
return cycle_count, optimization_count
def row_start_calculator_code(self, row, baselabel):
self.out()
self.comment_line("row %d" % row)
if row == 0:
self.asm("ldx param_y")
cycles = 3
else:
cycles = 0
self.asm("lda HGRROWS_H1+%d,x" % row)
cycles += 4
if self.double_buffer:
# HGRSELECT must be set to $00 or $60. The eor then turns the high
# byte of page 1 into either page1 or page 2 by flipping the 5th
# and 6th bit
self.asm("eor HGRSELECT")
cycles += 3
self.asm("sta scratch_addr+1")
self.asm("lda HGRROWS_L+%d,x" % row)
self.asm("sta scratch_addr")
cycles += 3 + 4 + 3
if row == 0:
self.asm("ldy param_x")
self.asm("lda DIV%d_%d,y" % (self.screen.num_shifts, self.screen.bits_per_pixel))
self.asm("sta scratch_col") # save the mod lookup; it doesn't change
self.asm("tay")
cycles += 3 + 4 + 3 + 2
else:
self.asm("ldy scratch_col")
cycles += 2
return cycles;
def shift_string_right(string, shift, bits_per_pixel, filler_bit):
if shift==0:
return string
shift *= bits_per_pixel
result = ""
for i in range(shift):
result += filler_bit
result += string
return result
class ScreenFormat(object):
num_shifts = 8
bits_per_pixel = 1
screen_width = 320
screen_height = 192
def __init__(self):
self.offsets = self.generate_row_offsets()
self.numX = self.screen_width // self.bits_per_pixel
def byte_width(self, png_width):
return (png_width * self.bits_per_pixel + self.num_shifts - 1) // self.num_shifts + 1
def bits_for_color(self, pixel):
raise NotImplementedError
def bits_for_mask(self, pixel):
raise NotImplementedError
def pixel_color(self, pixel_data, row, col):
raise NotImplementedError
def generate_row_offsets(self):
offsets = [40 * y for y in range(self.screen_height)]
return offsets
def generate_row_addresses(self, base_addr):
addrs = [base_addr + offset for offset in self.offsets]
return addrs
class HGR(ScreenFormat):
num_shifts = 7
bits_per_pixel = 2
screen_width = 280
black,magenta,green,orange,blue,white,key = list(range(7))
def bits_for_color(self, pixel):
if pixel == self.black or pixel == self.key:
return "00"
else:
if pixel == self.white:
return "11"
else:
if pixel == self.green or pixel == self.orange:
return "01"
# blue or magenta
return "10"
def bits_for_mask(self, pixel):
if pixel == self.key:
return "11"
return "00"
def bits_for_bw(self, pixel, pixel_index=0):
# if pixel == self.green or pixel == self.orange:
# pair = "01"
# elif pixel == self.blue or pixel == self.magenta:
# pair = "10"
# elif pixel == self.white:
if pixel == self.white:
return "1"
else:
return "0"
return pair[pixel_index & 1]
def bits_for_bw_mask(self, pixel):
if pixel == self.key:
return "1"
return "0"
def high_bit_for_color(self, pixel):
# Note that we prefer high-bit white because blue fringe is less noticeable than magenta.
high_bit = "0"
if pixel == self.orange or pixel == self.blue or pixel == self.white:
high_bit = "1"
return high_bit
def high_bit_for_mask(self, pixel):
return "0"
def get_rgb(self, pixel_data, row, col):
r = pixel_data[row][col*3]
g = pixel_data[row][col*3+1]
b = pixel_data[row][col*3+2]
return r, g, b
def pixel_color(self, pixel_data, row, col):
r, g, b = self.get_rgb(pixel_data, row, col)
rhi = r == 255
rlo = r == 0
ghi = g == 255
glo = g == 0
bhi = b == 255
blo = b == 0
if rhi and ghi and bhi:
color = self.white
elif rlo and glo and blo:
color = self.black
elif rhi and bhi:
color = self.magenta
elif rhi and g > 0:
color = self.orange
elif bhi:
color = self.blue
elif ghi:
color = self.green
else:
# anything else is chroma key
color = self.key
return color
def byte_streams_from_pixels(self, shift, source, mask=False):
byte_streams = ["" for x in range(source.height)]
byte_width = self.byte_width(source.width)
if mask:
bit_delegate = self.bits_for_mask
high_bit_delegate = self.high_bit_for_mask
filler_bit = "1"
else:
bit_delegate = self.bits_for_color
high_bit_delegate = self.high_bit_for_color
filler_bit = "0"
for row in range(source.height):
bit_stream = ""
high_bit = "0"
high_bit_found = False
# Compute raw bitstream for row from PNG pixels
for pixel_index in range(source.width):
pixel = self.pixel_color(source.pixel_data,row,pixel_index)
bit_stream += bit_delegate(pixel)
# Determine palette bit from first non-black pixel on each row
if not high_bit_found and pixel != self.black and pixel != self.key:
high_bit = high_bit_delegate(pixel)
high_bit_found = True
# Shift bit stream as needed
bit_stream = shift_string_right(bit_stream, shift, self.bits_per_pixel, filler_bit)
bit_stream = bit_stream[:byte_width*8]
# Split bitstream into bytes
bit_pos = 0
byte_splits = [0 for x in range(byte_width)]
for byte_index in range(byte_width):
remaining_bits = len(bit_stream) - bit_pos
bit_chunk = ""
if remaining_bits < 0:
bit_chunk = filler_bit * 7
else:
if remaining_bits < 7:
bit_chunk = bit_stream[bit_pos:]
bit_chunk += filler_bit * (7-remaining_bits)
else:
bit_chunk = bit_stream[bit_pos:bit_pos+7]
bit_chunk = bit_chunk[::-1]
byte_splits[byte_index] = high_bit + bit_chunk
bit_pos += 7
byte_streams[row] = byte_splits;
return byte_streams
def generate_row_offsets(self):
offsets = []
for y in range(self.screen_height):
# From Apple Graphics and Arcade Game Design
a = y // 64
d = y - (64 * a)
b = d // 8
c = d - 8 * b
offsets.append((1024 * c) + (128 * b) + (40 * a))
return offsets
class HGRBW(HGR):
bits_per_pixel = 1
def bits_for_color(self, pixel):
return self.bits_for_bw(pixel)
def bits_for_mask(self, pixel):
return self.bits_for_bw_mask(pixel)
def pixel_color(self, pixel_data, row, col):
r, g, b = self.get_rgb(pixel_data, row, col)
color = self.black
if abs(r - g) < 16 and abs(g - b) < 16 and r!=0 and r!=255: # Any grayish color is chroma key
color = self.key
elif r>25 or g>25 or b>25: # pretty much all other colors are white
color = self.white
else:
color = self.black
return color
class RowLookup(Listing):
def __init__(self, assembler, screen):
Listing.__init__(self, assembler)
self.slug = "hgrrows"
if assembler.use_16_bit:
self.generate_raw(screen)
else:
self.generate_y(screen)
def generate_raw(self, screen):
self.label("lines_page1")
for addr in screen.generate_row_addresses(0x2000):
self.word("0x%04x" % addr, 8)
self.out("\n")
self.label("lines_page2")
for addr in screen.generate_row_addresses(0x4000):
self.word("0x%04x" % addr, 8)
def generate_y(self, screen):
self.label("HGRROWS_H1")
for addr in screen.generate_row_addresses(0x2000):
self.byte("$%02x" % (addr // 256), 8)
self.out("\n")
self.label("HGRROWS_H2")
for addr in screen.generate_row_addresses(0x4000):
self.byte("$%02x" % (addr // 256), 8)
self.out("\n")
self.label("HGRROWS_L")
for addr in screen.generate_row_addresses(0x2000):
self.byte("$%02x" % (addr & 0xff), 8)
class ColLookup(Listing):
def __init__(self, assembler, screen):
Listing.__init__(self, assembler)
self.slug = "hgrcols-%dx%d" % (screen.num_shifts, screen.bits_per_pixel)
self.generate_x(screen)
def generate_x(self, screen):
self.out("\n")
self.label("DIV%d_%d" % (screen.num_shifts, screen.bits_per_pixel))
for pixel in range(screen.numX):
self.byte("$%02x" % ((pixel * screen.bits_per_pixel) // screen.num_shifts), screen.num_shifts)
self.out("\n")
self.label("MOD%d_%d" % (screen.num_shifts, screen.bits_per_pixel))
for pixel in range(screen.numX):
# This is the index into the jump table, so it's always multiplied
# by 2
self.byte("$%02x" % ((pixel % screen.num_shifts) * 2), screen.num_shifts)
class BackingStore(Listing):
# Each entry in the stack includes:
# 2 bytes: address of restore routine
# 1 byte: x coordinate
# 1 byte: y coordinate
# nn: x * y bytes of data, in lists of rows
def __init__(self, assembler, byte_width, row_height):
Listing.__init__(self, assembler)
self.byte_width = byte_width
self.row_height = row_height
self.save_label = "savebg_%dx%d" % (byte_width, row_height)
self.restore_label = "restorebg_%dx%d" % (byte_width, row_height)
self.space_needed = self.compute_size()
self.create_save()
self.out()
self.create_restore()
self.out()
def compute_size(self):
return 2 + 1 + 1 + (self.byte_width * self.row_height)
def create_save(self):
self.label(self.save_label)
# reserve space in the backing store stack
self.asm("sec")
self.asm("lda bgstore")
self.asm("sbc #%d" % self.space_needed)
self.asm("sta bgstore")
self.asm("lda bgstore+1")
self.asm("sbc #0")
self.asm("sta bgstore+1")
# save the metadata
self.asm("ldy #0")
self.asm("lda #<%s" % self.restore_label)
self.asm("sta (bgstore),y")
self.asm("iny")
self.asm("lda #>%s" % self.restore_label)
self.asm("sta (bgstore),y")
self.asm("iny")
self.asm("lda param_x")
self.asm("sta (bgstore),y")
self.asm("iny")
self.asm("lda param_y")
# Note that we can't clobber param_y like the restore routine can
# because this is called in the sprite drawing routine and these
# values must be retained to draw the sprite in the right place!
self.asm("sta scratch_addr")
self.asm("sta (bgstore),y")
self.asm("iny")
# The unrolled code is taken from Quinn's row sweep backing store
# code in a previous version of HiSprite
loop_label, col_label = self.smc_row_col(self.save_label, "scratch_addr")
for c in range(self.byte_width):
self.label(col_label % c)
self.asm("lda $2000,x")
self.asm("sta (bgstore),y")
self.asm("iny")
if c < self.byte_width - 1:
# last loop doesn't need this
self.asm("inx")
self.asm("inc scratch_addr")
self.asm("cpy #%d" % self.space_needed)
self.asm("bcc %s" % loop_label)
self.asm("rts")
def smc_row_col(self, label, row_var):
# set up smc for hires column, because the starting column doesn't
# change when moving to the next row
self.asm("ldx param_x")
self.asm("lda DIV7_1,x")
smc_label = "%s_smc1" % label
self.asm("sta %s+1" % smc_label)
loop_label = "%s_line" % label
# save a line, starting from the topmost and working down
self.label(loop_label)
self.asm("ldx %s" % row_var)
self.asm("lda HGRROWS_H1,x")
col_label = "%s_col%%s" % label
for c in range(self.byte_width):
self.asm("sta %s+2" % (col_label % c))
self.asm("lda HGRROWS_L,x")
for c in range(self.byte_width):
self.asm("sta %s+1" % (col_label % c))
self.label(smc_label)
self.asm("ldx #$ff")
return loop_label, col_label
def create_restore(self):
# bgstore will be pointing right to the data to be blitted back to the
# screen, which is 4 bytes into the bgstore array. Everything before
# the data will have already been pulled off by the driver in order to
# figure out which restore routine to call. Y will be 4 upon entry,
# and param_x and param_y will be filled with the x & y values.
#
# also, no need to save registers because this is being called from a
# driver that will do all of that.
self.label(self.restore_label)
# we can clobber the heck out of param_y because we're being called from
# the restore driver and when we return we are just going to load it up
# with the next value anyway.
loop_label, col_label = self.smc_row_col(self.restore_label, "param_y")
for c in range(self.byte_width):
self.asm("lda (bgstore),y")
self.label(col_label % c)
self.asm("sta $2000,x")
self.asm("iny")
if c < self.byte_width - 1:
# last loop doesn't need this
self.asm("inx")
self.asm("inc param_y")
self.asm("cpy #%d" % self.space_needed)
self.asm("bcc %s" % loop_label)
self.asm("rts")
class BackingStoreDriver(Listing):
# Driver to restore the screen using all the saved data.
# The backing store is a stack that grows downward in order to restore the
# chunks in reverse order that they were saved.
#
# variables used:
# bgstore: (lo byte, hi byte) 1 + the first byte of free memory.
# I.e. points just beyond the last byte
# param_x: (byte) x coord
# param_y: (byte) y coord
#
# everything else is known because the sizes of each erase/restore
# routine are hardcoded because this is a sprite *compiler*.
#
# Note that sprites of different sizes will have different sized entries in
# the stack, so the entire list has to be processed in order. But you want
# that anyway, so it's not a big deal.
#
# The global variable 'bgstore' is used as the stack pointer. It must be
# initialized to a page boundary, the stack grows downward from there.
# starting from the last byte on the previous page. E.g. if the initial
# value is $c000, the stack grows down using $bfff as the highest address,
# the initial bgstore value must point to 1 + the last usable byte
#
# All registers are clobbered because there's no real need to save them
# since this will be called from the main game loop.
def __init__(self, assembler, sizes):
Listing.__init__(self, assembler)
self.slug = "backing-store"
self.add_driver()
for byte_width, row_height in sizes:
code = BackingStore(assembler, byte_width, row_height)
self.add_listing(code)
def add_driver(self):
# Initialization routine needs to be called once at the beginning
# of the program so that the savebg_* functions will have a valid
# bgstore
self.label("restorebg_init")
self.asm("lda #0")
self.asm("sta bgstore")
self.asm("lda #BGTOP")
self.asm("sta bgstore+1")
self.asm("rts")
self.out()
# Driver routine to loop through the bgstore stack and copy the
# data back to the screen
self.label("restorebg_driver")
self.asm("ldy #0")
self.asm("lda (bgstore),y")
self.asm("sta restorebg_jsr_smc+1")
self.asm("iny")
self.asm("lda (bgstore),y")
self.asm("sta restorebg_jsr_smc+2")
self.asm("iny")
self.asm("lda (bgstore),y")
self.asm("sta param_x")
self.asm("iny ")
self.asm("lda (bgstore),y")
self.asm("sta param_y")
self.asm("iny")
self.label("restorebg_jsr_smc")
self.asm("jsr $ffff")
self.asm("clc")
self.asm("tya") # y contains the number of bytes processed
self.asm("adc bgstore")
self.asm("sta bgstore")
self.asm("lda bgstore+1")
self.asm("adc #0")
self.asm("sta bgstore+1")
self.asm("cmp #BGTOP")
self.asm("bcc restorebg_driver")
self.asm("rts")
self.out()
class FastFont(Listing):
def __init__(self, assembler, screen, font, double_buffer, byte_width=1, byte_height=8):
Listing.__init__(self, assembler)
self.slug = "fastfont"
self.row_slug = "TransposedFontRow"
self.generate_table(screen, "H1", 0x2000, byte_width, byte_height)
if double_buffer:
self.generate_table(screen, "H2", 0x4000, byte_width, byte_height)
self.generate_transposed_font(screen, font, byte_width, byte_height)
def generate_table(self, screen, suffix, hgrbase, byte_width, byte_height):
label = "FASTFONT_%s" % suffix
self.label(label)
# Have to use self-modifying code because assembler may not allow
# taking the hi/lo bytes of an address - 1
self.comment("A = character, X = column, Y = row; A is clobbered, X&Y are not")
self.asm("pha")
self.asm(f"lda {label}_JMP_HI,y")
self.asm(f"sta {label}_JMP+2")
self.asm(f"lda {label}_JMP_LO,y")
self.asm(f"sta {label}_JMP+1")
self.asm("sty scratch_0")
self.asm("pla")