-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhello.asm
More file actions
1822 lines (1495 loc) · 49 KB
/
Copy pathhello.asm
File metadata and controls
1822 lines (1495 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
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
; ============================================================================
; Mecha Man - NES ROM
; ============================================================================
;
; Displays "HELLO WORLD!" on the background and a Mario character that
; can run left and right using the D-pad. Features:
; - Multi-tile metasprites (2x2 = 16x16 pixel character)
; - Standing and running animation
; - Horizontal flip for left/right facing
;
; CHR-ROM layout:
; Pattern Table 0 ($0000-$0FFF): Background tiles (font A-Z, etc.)
; Pattern Table 1 ($1000-$1FFF): Sprite tiles (Mario poses)
;
; ============================================================================
; ---------------------------------------------------------------------------
; PPU Register Definitions
; ---------------------------------------------------------------------------
PPUCTRL = $2000 ; PPU Control Register 1
; Bit 7: Generate NMI on VBlank (1 = enable)
; Bit 4: Background pattern table (0 = $0000, 1 = $1000)
; Bit 3: Sprite pattern table (0 = $0000, 1 = $1000)
; Bits 0-1: Base nametable address
PPUMASK = $2001 ; PPU Control Register 2
; Bit 3: Show background (1 = enable)
; Bit 4: Show sprites (1 = enable)
; Bit 1: Show background in leftmost 8 pixels
PPUSTATUS = $2002 ; PPU Status Register (read-only)
; Bit 7: VBlank has started (1 = yes)
; Reading this register resets the address latch.
OAMADDR = $2003 ; OAM Address Register
OAMDATA = $2004 ; OAM Data Register
PPUSCROLL = $2005 ; PPU Scroll Register (write twice: X, then Y)
PPUADDR = $2006 ; PPU Address Register (write twice: high, then low)
PPUDATA = $2007 ; PPU Data Register
OAMDMA = $4014 ; OAM DMA Register
JOYPAD1 = $4016 ; Controller 1 Port
JOYPAD2 = $4017 ; Controller 2 Port
; ---------------------------------------------------------------------------
; Constants
; ---------------------------------------------------------------------------
; PPUCTRL value: NMI enabled, BG uses pattern table 0, sprites use table 1
PPUCTRL_VAL = %10001000
; Animation timing (frames between animation ticks)
ANIM_SPEED_RUN = 6 ; ~10 fps run cycle at 60 Hz
MOVE_SPEED = 2 ; Pixels per frame
; Sprite attribute bits
FLIP_H = %01000000 ; Horizontal flip
; World bounds (accounting for 16x16 metasprite)
; Level is 2 screens wide (512 pixels)
LEVEL_WIDTH_LO = $00 ; Low byte of 512
LEVEL_WIDTH_HI = $02 ; High byte of 512
WORLD_LEFT_LO = $02 ; Left world bound
WORLD_LEFT_HI = $00
WORLD_RIGHT_LO = $EE ; Right world bound (512 - 16 - 2 = 494 = $01EE)
WORLD_RIGHT_HI = $01
; Camera constants
CAMERA_LEFT_EDGE = $50 ; Player screen X for left edge of dead zone (80)
CAMERA_RIGHT_EDGE = $A0 ; Player screen X for right edge of dead zone (160)
; Physics constants
GRAVITY = 1 ; Added to vel_y each frame
JUMP_VELOCITY = $F4 ; -12 in two's complement (upward)
GROUND_Y = 184 ; Y position of the floor (row 13 metatile = tile row 26 = 208px, minus 24px sprite height)
TERMINAL_VEL = 5 ; Maximum falling speed
; Screen transition / palette fade
FADE_SPEED = 10 ; Frames per fade step
FADE_STEPS = 4 ; Max fade step (0=full color, 4=black)
; ---------------------------------------------------------------------------
; iNES Header
; ---------------------------------------------------------------------------
.segment "HEADER"
.byte "NES",$1A ; Magic number
.byte $01 ; 1 x 16KB PRG-ROM bank
.byte $01 ; 1 x 8KB CHR-ROM bank
.byte $01 ; Flags 6: Mapper 0 (NROM), vertical mirroring
.byte $00 ; Flags 7: Mapper 0, NES 1.0
.byte $00,$00,$00 ; Flags 8-10
.byte $00,$00,$00,$00,$00 ; Padding
; ---------------------------------------------------------------------------
; Zero Page Variables
; ---------------------------------------------------------------------------
; The 6502 zero page ($0000-$00FF) provides fast access (1 byte shorter,
; 1 cycle faster). We use it for all frequently-accessed game state.
.segment "ZEROPAGE"
sprite_x: .res 1 ; Metasprite anchor X position
sprite_y: .res 1 ; Metasprite anchor Y position
controller: .res 1 ; Current controller button state
; Bit 7: A Bit 3: Up
; Bit 6: B Bit 2: Down
; Bit 5: Sel Bit 1: Left
; Bit 4: Start Bit 0: Right
; Animation state
facing_dir: .res 1 ; 0 = facing right, 1 = facing left
anim_state: .res 1 ; 0 = idle/standing, 1 = running
anim_frame: .res 1 ; Current frame index within animation
anim_timer: .res 1 ; Frame counter until next animation tick
; Metasprite rendering
meta_ptr: .res 2 ; 16-bit pointer to current metasprite data (lo, hi)
; Level rendering temporaries
level_ptr: .res 2 ; 16-bit pointer into level data
temp: .res 1 ; General purpose temp
temp2: .res 1 ; Second temp
col_count: .res 1 ; Column counter for level init
; Physics state
vel_y: .res 1 ; Vertical velocity (signed: negative=up, positive=down)
on_ground: .res 1 ; 1 = on ground, 0 = in air
; Scrolling and Camera (16-bit world coordinates)
camera_x_lo: .res 1 ; Camera world X low byte (0-255)
camera_x_hi: .res 1 ; Camera world X high byte (0-1 for 2 screens)
player_world_x_lo: .res 1 ; Player world X low byte
player_world_x_hi: .res 1 ; Player world X high byte
scroll_x_hi: .res 1 ; Nametable select bit (0 or 1)
prev_scroll_col: .res 1 ; Last drawn column (for seam detection)
col_to_draw: .res 1 ; Next column to draw
seam_ready: .res 1 ; Flag: seam buffer ready to write
; Screen transition state
transition_state: .res 1 ; 0=play, 1=fade_out, 2=fade_in
fade_timer: .res 1 ; Frames until next fade step
fade_step: .res 1 ; Current fade level (0=full color, 4=black)
current_screen: .res 1 ; 0 or 1 (which screen we're on)
fade_ready: .res 1 ; Flag: pending palette color write to PPU
fade_color: .res 1 ; Sky color byte to write to $3F00
; Metatile collision scratch
mt_col: .res 1 ; Column for GetMetatile lookup (0-31)
mt_row: .res 1 ; Row for GetMetatile lookup (0-14)
; ---------------------------------------------------------------------------
; BSS (Uninitialized RAM at $0300+)
; ---------------------------------------------------------------------------
; Note: $0200-$02FF is reserved for OAM sprite buffer
.segment "BSS"
seam_buffer: .res 30 ; One column of tiles for seam update
; ---------------------------------------------------------------------------
; Main Code
; ---------------------------------------------------------------------------
.segment "CODE"
; ===== RESET: Entry point on power-on/reset =====
Reset:
sei
cld
ldx #$FF
txs
; Disable PPU during init
lda #$00
sta PPUCTRL
sta PPUMASK
; Wait for first VBlank
WaitVBlank1:
bit PPUSTATUS
bpl WaitVBlank1
; Clear all RAM
lda #$00
ldx #$00
ClearRAM:
sta $0000, x
sta $0100, x
sta $0200, x
sta $0300, x
sta $0400, x
sta $0500, x
sta $0600, x
sta $0700, x
inx
bne ClearRAM
; Wait for second VBlank
WaitVBlank2:
bit PPUSTATUS
bpl WaitVBlank2
; Initialize APU for sound effects
jsr SoundInit
; ==================================================================
; PPU is ready. Set up graphics.
; ==================================================================
; --- Load color palette ---
bit PPUSTATUS
lda #$3F
sta PPUADDR
lda #$00
sta PPUADDR
ldx #$00
LoadPalette:
lda PaletteData, x
sta PPUDATA
inx
cpx #$20
bne LoadPalette
; --- Draw level to both nametables ---
jsr DrawLevel
; --- Initialize player state ---
lda #GROUND_Y ; Start on the ground
sta sprite_y
lda #120 ; Screen X position (centered)
sta sprite_x
; World position starts at (120, 200)
lda #120
sta player_world_x_lo
lda #$00
sta player_world_x_hi
lda #$00
sta facing_dir ; Face right
sta anim_state ; Idle
sta anim_frame ; Frame 0
sta anim_timer ; Timer at 0
sta vel_y ; No vertical velocity
; Camera starts at world X = 0
sta camera_x_lo
sta camera_x_hi
sta scroll_x_hi ; Start on nametable 0
sta seam_ready ; No seam to write yet
sta prev_scroll_col ; Leftmost column is 0 at camera_x=0
; Transition/fade state
sta transition_state
sta fade_timer
sta fade_step
sta current_screen
sta fade_ready
lda #$01
sta on_ground ; Start on ground
; --- Draw initial metasprite to OAM buffer ---
lda #<MetaStand
sta meta_ptr
lda #>MetaStand
sta meta_ptr+1
jsr DrawMetasprite
; --- Enable rendering ---
bit PPUSTATUS
lda #$00
sta PPUSCROLL
sta PPUSCROLL
lda #PPUCTRL_VAL
sta PPUCTRL
lda #%00011110 ; Show sprites + background, leftmost 8px
sta PPUMASK
; Main loop: NMI does all the work
Forever:
jmp Forever
; ===== NMI: Called every VBlank (~60 Hz) =====
; This is the game loop heartbeat.
;
; CRITICAL: Vblank is limited! Do PPU writes first:
; 1. OAM DMA
; 2. Seam column write (if ready)
; 3. Set scroll and PPUCTRL
; Then do game logic (can run outside vblank).
NMI:
pha
txa
pha
tya
pha
; ==========================================
; VBLANK-CRITICAL SECTION - PPU writes only
; ==========================================
; --- Step 1: OAM DMA (must be first) ---
lda #$00
sta OAMADDR
lda #$02
sta OAMDMA
; --- Step 2: Write seam column if ready ---
lda seam_ready
beq @SkipSeam
jsr WriteSeam
lda #$00
sta seam_ready
@SkipSeam:
; --- Step 2b: Write fade palette color if ready ---
lda fade_ready
beq @SkipFade
jsr WriteFadePalette
lda #$00
sta fade_ready
@SkipFade:
; --- Step 3: Apply scroll to PPU (must be last PPU write) ---
bit PPUSTATUS
lda camera_x_lo
sta PPUSCROLL ; X scroll (low 8 bits)
lda #$00
sta PPUSCROLL ; Y scroll (fixed at 0)
; Set PPUCTRL with nametable select bit
lda #PPUCTRL_VAL
ora scroll_x_hi ; Add nametable bit (0 or 1)
sta PPUCTRL
; ==========================================
; GAME LOGIC SECTION - Can run outside vblank
; ==========================================
; --- Step 4: Read controller ---
jsr ReadControllerSub
; --- Check transition state: skip gameplay while fading ---
lda transition_state
beq @GameplayActive
jsr UpdateTransition
jmp @GameDone
@GameplayActive:
; --- Step 5: Update facing direction ---
lda controller
and #%00000001 ; Right
beq @CheckLeftFace
lda #$00
sta facing_dir
jmp @FaceDone
@CheckLeftFace:
lda controller
and #%00000010 ; Left
beq @FaceDone
lda #$01
sta facing_dir
@FaceDone:
; --- Step 6: Move player (left/right only) ---
jsr MovePlayer
; --- Step 7: Handle jumping and gravity ---
jsr HandleJump
jsr ApplyGravity
; --- Step 8: Update camera/scroll ---
jsr UpdateCamera
; --- Step 9: Detect and prepare seam ---
jsr PrepareSeam
; --- Step 10: Check for screen transition trigger ---
jsr CheckTransition
; --- Step 11: Update animation and draw metasprite ---
jsr UpdateAnimation
@GameDone:
pla
tay
pla
tax
pla
rti
; ===== IRQ =====
IRQ:
rti
; ---------------------------------------------------------------------------
; Subroutines
; ---------------------------------------------------------------------------
; --- ReadControllerSub ---
; Reads controller 1 and packs button state into 'controller'.
; Bit layout: A B Sel Start Up Down Left Right (bits 7..0)
ReadControllerSub:
lda #$01
sta JOYPAD1
lda #$00
sta JOYPAD1
ldx #$08
@Loop:
lda JOYPAD1
lsr a
rol controller
dex
bne @Loop
rts
; --- MovePlayer ---
; Moves the player's world position based on left/right input.
; Movement speed: MOVE_SPEED pixels per frame.
; After moving, sprite_x is calculated from world position - camera position.
MovePlayer:
; Check LEFT (bit 1)
lda controller
and #%00000010
beq @CheckRight
; Check left world bound (16-bit compare)
lda player_world_x_hi
cmp #WORLD_LEFT_HI
bcc @CheckRight ; High byte less = at bound
bne @DoLeft ; High byte greater = can move
lda player_world_x_lo
cmp #WORLD_LEFT_LO
bcc @CheckRight ; At left bound
beq @CheckRight
@DoLeft:
; Subtract MOVE_SPEED from world X (16-bit)
lda player_world_x_lo
sec
sbc #MOVE_SPEED
sta player_world_x_lo
lda player_world_x_hi
sbc #$00
sta player_world_x_hi
@CheckRight:
lda controller
and #%00000001
beq @Done
; Check right world bound (16-bit compare)
lda player_world_x_hi
cmp #WORLD_RIGHT_HI
bcc @DoRight ; High byte less = can move
bne @Done ; High byte greater = at bound
lda player_world_x_lo
cmp #WORLD_RIGHT_LO
bcs @Done ; At right bound
@DoRight:
; Add MOVE_SPEED to world X (16-bit)
lda player_world_x_lo
clc
adc #MOVE_SPEED
sta player_world_x_lo
lda player_world_x_hi
adc #$00
sta player_world_x_hi
@Done:
rts
; --- HandleJump ---
; Initiates a jump when A is pressed and player is on ground.
HandleJump:
; Check if on ground
lda on_ground
beq @Done ; Not on ground, can't jump
; Check if A button pressed (bit 7)
lda controller
bpl @Done ; A not pressed (bit 7 = 0)
; Start jump: set upward velocity, leave ground
lda #JUMP_VELOCITY
sta vel_y
lda #$00
sta on_ground
jsr SFX_Jump
@Done:
rts
; --- ApplyGravity ---
; Applies gravity and velocity to sprite_y.
; When on_ground, verifies the metatile below is still solid (walk-off detection).
; When airborne, checks for metatile landing on any solid tile (ground or platform).
; Pit death: if sprite_y exceeds screen bottom, respawn player.
ApplyGravity:
lda on_ground
beq @ApplyGrav ; Already airborne: apply gravity
; Verify still on solid ground (walk-off-edge detection)
jsr CalcMetatilePos
jsr GetMetatile
cmp #METATILE_SKY
bne @Done ; Still solid, stay grounded
; Tile gone — fell off edge, start falling
lda #$00
sta on_ground
@ApplyGrav:
; Apply gravity: vel_y += GRAVITY
lda vel_y
clc
adc #GRAVITY
sta vel_y
; Clamp to terminal velocity (positive = falling)
bmi @ApplyVelocity ; Negative = rising, skip clamp
cmp #TERMINAL_VEL
bcc @ApplyVelocity
beq @ApplyVelocity
lda #TERMINAL_VEL
sta vel_y
@ApplyVelocity:
lda sprite_y
clc
adc vel_y
sta sprite_y ; A = new sprite_y
; Pit death: fell below the screen
cmp #220
bcc @CheckLand
jsr RespawnPlayer
jmp @Done
@CheckLand:
; Only land on solid tiles when falling (vel_y >= 0)
lda vel_y
bmi @Done
jsr CalcMetatilePos
jsr GetMetatile
cmp #METATILE_SKY
beq @Done
; Hit solid tile — snap to top of metatile row and land
lda mt_row
asl a
asl a
asl a
asl a ; mt_row * 16 = pixel Y of tile top
sec
sbc #24 ; subtract sprite height offset (feet = sprite_y + 24)
sta sprite_y
lda #$00
sta vel_y
lda #$01
sta on_ground
jsr SFX_Land
@Done:
rts
; --- UpdateCamera ---
; Updates camera position to follow player with dead zone.
; Also calculates sprite_x (screen position) from world position.
UpdateCamera:
; First, calculate player's screen X = world_x - camera_x
; This is 16-bit subtraction, but screen X is 8-bit
lda player_world_x_lo
sec
sbc camera_x_lo
sta sprite_x ; Low byte is screen X (assuming camera tracks well)
; Check if player is outside dead zone and adjust camera
; Check if player screen X < CAMERA_LEFT_EDGE (need to scroll left)
lda sprite_x
cmp #CAMERA_LEFT_EDGE
bcs @CheckRightEdge
; Player is left of dead zone - move camera left
; camera_x -= (CAMERA_LEFT_EDGE - sprite_x)
; Simplified: camera_x = player_world_x - CAMERA_LEFT_EDGE
lda player_world_x_lo
sec
sbc #CAMERA_LEFT_EDGE
sta camera_x_lo
lda player_world_x_hi
sbc #$00
; Clamp camera to 0 if it went negative
bpl @StoreCameraHi
lda #$00
sta camera_x_lo
sta camera_x_hi
jmp @UpdateScreenX
@StoreCameraHi:
sta camera_x_hi
jmp @UpdateScreenX
@CheckRightEdge:
; Check if player screen X > CAMERA_RIGHT_EDGE (need to scroll right)
lda sprite_x
cmp #CAMERA_RIGHT_EDGE
bcc @UpdateScreenX
; Player is right of dead zone - move camera right
; camera_x = player_world_x - CAMERA_RIGHT_EDGE
lda player_world_x_lo
sec
sbc #CAMERA_RIGHT_EDGE
sta camera_x_lo
lda player_world_x_hi
sbc #$00
sta camera_x_hi
; Clamp camera to max (LEVEL_WIDTH - 256 = 256 = $0100)
lda camera_x_hi
cmp #$01
bcc @UpdateScreenX ; High byte < 1, ok
bne @ClampCameraMax ; High byte > 1, clamp
lda camera_x_lo
cmp #$00
bcc @UpdateScreenX ; At exactly $0100 or less, ok
beq @UpdateScreenX
@ClampCameraMax:
lda #$00
sta camera_x_lo
lda #$01
sta camera_x_hi
@UpdateScreenX:
; Recalculate screen X with clamped camera
lda player_world_x_lo
sec
sbc camera_x_lo
sta sprite_x
; Set scroll_x_hi from camera_x high byte (nametable select)
lda camera_x_hi
and #$01
sta scroll_x_hi
rts
; --- PrepareSeam ---
; Detects when a new column has scrolled into view and prepares the seam buffer.
; Called every frame after UpdateCamera.
;
; Tracks the leftmost visible column. When it changes (scroll right),
; draws the new rightmost column.
; Note: Left scrolling works because level is pre-drawn; no dynamic update needed.
PrepareSeam:
; Calculate current leftmost tile column
; left_col = (camera_x_hi << 5) | (camera_x_lo >> 3)
lda camera_x_lo
lsr a
lsr a
lsr a ; A = camera_x_lo >> 3 (0-31)
ldx camera_x_hi
beq @NoHighAdd
ora #$20 ; If camera_x_hi = 1, set bit 5 (add 32)
@NoHighAdd:
sta temp ; temp = current leftmost column (0-63)
; Check if leftmost column changed from previous frame
cmp prev_scroll_col
beq @NothingToDraw
; Column changed! Update tracking
sta prev_scroll_col
; Calculate seam column (rightmost + 1 = leftmost + 32)
clc
adc #32
and #$3F ; Mask to 64 columns
sta col_to_draw
; Calculate which metatile column this tile column is in
; metatile_col = tile_col >> 1 (each metatile is 2 tiles wide)
lsr a
tax ; X = metatile column index (0-31)
; Calculate level data pointer: Level1Data + (metatile_col * 15)
; We need to multiply X by 15
lda #$00
sta level_ptr+1
txa
; Multiply by 15 = multiply by 16, subtract original
asl a ; *2
asl a ; *4
asl a ; *8
asl a ; *16
sta level_ptr
bcc @NoCarry1
inc level_ptr+1
@NoCarry1:
txa ; Get original back
sta temp
lda level_ptr
sec
sbc temp ; *16 - 1 = *15
sta level_ptr
lda level_ptr+1
sbc #$00
sta level_ptr+1
; Add base address of level data
lda level_ptr
clc
adc #<Level1Data
sta level_ptr
lda level_ptr+1
adc #>Level1Data
sta level_ptr+1
; Determine if we're drawing left or right tile column of metatile
; If col_to_draw is even, draw left tiles; if odd, draw right tiles
lda col_to_draw
and #$01
sta temp ; 0 = left column, 1 = right column
; Fill seam_buffer with 30 tiles (15 metatiles * 2 tiles each)
; Use Y for (level_ptr),y indexing, X for seam_buffer index
ldy #$00 ; Index into level column (0-14)
ldx #$00 ; Index into seam_buffer (0-29)
@FillLoop:
; Get metatile index at this row
lda (level_ptr), y ; A = metatile index
sty temp2 ; Save Y (level index)
asl a
asl a ; A = metatile index * 4 (offset into MetatileDefs)
tay ; Y = offset into MetatileDefs
; Check if left or right column
lda temp
bne @RightTiles
; Left tiles: TL at +0, BL at +2
lda MetatileDefs, y
sta seam_buffer, x
inx
lda MetatileDefs+2, y
sta seam_buffer, x
inx
jmp @NextMetatile
@RightTiles:
; Right tiles: TR at +1, BR at +3
lda MetatileDefs+1, y
sta seam_buffer, x
inx
lda MetatileDefs+3, y
sta seam_buffer, x
inx
@NextMetatile:
ldy temp2 ; Restore Y (level index)
iny
cpy #15 ; 15 metatiles per column
bne @FillLoop
; Mark seam as ready for writing
lda #$01
sta seam_ready
@NothingToDraw:
rts
; --- WriteSeam ---
; Writes the seam_buffer to the appropriate nametable column.
; Must be called during vblank.
;
; The column to write is col_to_draw (0-63).
; Columns 0-31 go to nametable 0, columns 32-63 go to nametable 1.
WriteSeam:
; Calculate PPU address for this column
; NT0 base = $2000, NT1 base = $2400
; Column within NT = col_to_draw & $1F
lda col_to_draw
and #$20 ; Check bit 5: 0 = NT0, 1 = NT1
beq @UseNT0Seam
lda #$24 ; Nametable 1
jmp @SetSeamNT
@UseNT0Seam:
lda #$20 ; Nametable 0
@SetSeamNT:
sta temp2 ; High byte of PPU address
lda col_to_draw
and #$1F ; Column within nametable (0-31)
sta temp ; Low byte of PPU address
; Set PPU address
bit PPUSTATUS
lda temp2
sta PPUADDR
lda temp
sta PPUADDR
; Set PPUCTRL for vertical increment (+32 per write)
lda #%10001100 ; NMI on, BG PT0, Sprites PT1, vert increment
sta PPUCTRL
; Write 30 tiles from seam_buffer
ldx #$00
@WriteLoop:
lda seam_buffer, x
sta PPUDATA
inx
cpx #30
bne @WriteLoop
; Restore PPUCTRL to horizontal increment
lda #PPUCTRL_VAL
sta PPUCTRL
rts
; --- WriteFadePalette ---
; Writes fade_color to PPU $3F00 (universal background / sky color).
; Must be called during vblank.
WriteFadePalette:
bit PPUSTATUS
lda #$3F
sta PPUADDR
lda #$00
sta PPUADDR
lda fade_color
sta PPUDATA
rts
; --- CheckTransition ---
; Triggers a fade-out when the player reaches the right world boundary.
; Only triggers when not already transitioning.
CheckTransition:
; Already transitioning?
lda transition_state
bne @Done
; Check if player is at the right world edge (16-bit compare)
lda player_world_x_hi
cmp #WORLD_RIGHT_HI
bcc @Done ; High byte less = not there yet
lda player_world_x_lo
cmp #WORLD_RIGHT_LO
bcc @Done ; Not at right edge yet
; Start fade out
lda #$01
sta transition_state
lda #$00
sta fade_step
sta fade_timer
@Done:
rts
; --- UpdateTransition ---
; Advances the fade timer and updates the sky palette color each step.
; Handles fade-out (state 1) and fade-in (state 2).
; Calls SwitchScreen when fully black.
UpdateTransition:
; Advance fade timer
inc fade_timer
lda fade_timer
cmp #FADE_SPEED
bcc @Done ; Not yet time for next step
lda #$00
sta fade_timer
lda transition_state
cmp #$01
beq @FadeOut
@FadeIn:
; Decrement fade step toward 0 (full color)
lda fade_step
beq @FadeInDone
dec fade_step
jmp @PrepareWrite
@FadeInDone:
; Reached full color - transition complete
lda #$00
sta transition_state
jmp @Done ; Color already written last step
@FadeOut:
; Increment fade step toward 4 (black)
inc fade_step
lda fade_step
cmp #FADE_STEPS + 1
bcc @PrepareWrite
; Reached fully black - switch screen, begin fade-in
jsr SwitchScreen
lda #$02
sta transition_state
lda #FADE_STEPS
sta fade_step
; Fall through to @PrepareWrite
@PrepareWrite:
; Look up sky color for current_screen at current fade_step
ldy fade_step
lda current_screen
beq @UseScreen1
lda Screen2_SkyFade, y
jmp @StoreColor
@UseScreen1:
lda Screen1_SkyFade, y
@StoreColor:
sta fade_color
lda #$01
sta fade_ready
@Done:
rts
; --- SwitchScreen ---
; Toggles current_screen, resets player and camera to left side.
; Called at the fully-black midpoint of a transition.
SwitchScreen:
; Toggle screen
lda current_screen
eor #$01
sta current_screen
; Reset player world position to left edge
lda #$08
sta player_world_x_lo
lda #$00
sta player_world_x_hi
; Reset camera to left edge
lda #$00
sta camera_x_lo
sta camera_x_hi
sta scroll_x_hi
sta prev_scroll_col
; Reset sprite screen position
lda #$08
sta sprite_x
; Reset player state
lda #GROUND_Y
sta sprite_y
lda #$00
sta vel_y
lda #$01
sta on_ground
lda #$00
sta anim_state
sta anim_frame
sta anim_timer