.include "joysticks.s"
; Characters for view
.include "bitmap_font.s"

zp_res TEMP

.macro load_ppu_addr addr
	lda #.hibyte(addr)
	sta PPUADDR
	lda #.lobyte(addr)
	sta PPUADDR ; Load $2000
.endmacro

init_view:
	; Init PPU
	bit PPUSTATUS
vwait1:
	bit PPUSTATUS
	bpl vwait1
vwait2:
	bit PPUSTATUS
	bpl vwait2

	lda #$00
	sta PPUCTRL ; NMI off, PPU slave, Small sprites, 0 addresses

	; Fill NT0
	load_ppu_addr $2000
	ldx #$00
	ldy #$04
	lda #EMPTY
fill_loop:
	sta PPUDATA
	dex
	bne fill_loop
	dey
	bne fill_loop

	load_ppu_addr $23C0
	ldx #$C0
	lda #$00
palette_loop:
	sta PPUDATA
	dex
	bne palette_loop

	load_ppu_addr $3F00
	lda #$0f
	sta PPUDATA
	lda #$20
	sta PPUDATA
	sta PPUDATA
	sta PPUDATA
	lda #$0f
	sta PPUDATA
	lda #$09
	sta PPUDATA
	sta PPUDATA
	sta PPUDATA
	rts

enable_rendering:
	lda #$00
	sta PPUSCROLL
	sta PPUSCROLL
	lda #%00001110
	sta PPUMASK 
	lda #$80
	sta PPUCTRL ; NMI on, PPU slave, Small sprites, 0 addresses
	rts

nmi:
	lda PPUSTATUS
	lda #%00000110
	sta PPUMASK ; Force blank

	jsr read_joy1
	jsr audio_nmi
	
.macro bit_lsr val
.scope
	lsr
	bcs carry_set
	ldx #EMPTY
	jmp carry_clear
	carry_set:
	ldx val
	carry_clear:
	stx PPUDATA
.endscope
.endmacro
	load_ppu_addr $2008
	lda JOYTEMP
	bit_lsr #RIGHT
	bit_lsr #LEFT
	bit_lsr #DOWN
	bit_lsr #UP
	bit_lsr #PILL
	bit_lsr #PILL
	bit_lsr #$0B
	bit_lsr #$0A

	lda #$00
	sta PPUSCROLL
	sta PPUSCROLL

	lda #%00001110
	sta PPUMASK ; Enable rendering
	rti
