; overworld.asm

TileDefinitions:
include "include/tileset.asm"

; draw tile a at hl
DrawTile:
    push hl
    ld hl, TileDefinitions
    ld bc, $0004
    call AddNTimes	; pointer to tile data stored at hl
    pop de

    ld a,[hli]
    ld [de], a
    inc de
    ld a,[hli]
    ld [de], a
    push hl
    push de
    pop hl
    ld bc, $0020 - 1
    add hl, bc
    push hl
    pop de
    pop hl
    ld a,[hli]
    ld [de], a
    inc de
    ld a,[hl]
    ld [de], a
    ret

M_OverworldInit:
    xor a
    ld [wUpdateSpritesEnabled], a

    ; fall through (probably)

M_OverworldLoop:


    ; get input
    ld a, [wPlayerWalkDir]
    and a
    jr nz, .noInput
    call JoypadLowSensitivity
    ld a, [$FFB4] ;hJoy5
    and %11110001 ; dont care about start, select, or b
    and a
    jr z, .noInput
    bit 7, a
    jr nz, .downPressed
    bit 6, a
    jr nz, .upPressed
    bit 5, a
    jr nz, .leftPressed
    bit 4, a
    jr nz, .rightPressed
    jr .noInput
    
.upPressed
    ld a, [wPlayerYTile]
    dec a
    ld [wPlayerYTile], a
    jr .noInput
.downPressed
    ld a, [wPlayerYTile]
    inc a
    ld [wPlayerYTile], a
    jr .noInput
.leftPressed
    ld a, [wPlayerXTile]
    dec a
    ld [wPlayerXTile], a
    jr .noInput
.rightPressed
    ld a, [wPlayerXTile]
    inc a
    ld [wPlayerXTile], a
    
.noInput

    ; update voam (every frame?)
    	;ld a, [wPlayerYTile]
    	;ld [wOAMBuffer], a
    	;ld a, [wPlayerXTile]
    	;ld [wOAMBuffer+1], a
    ld a, [wPlayerYTile]
    call MultBy8
    ld c, a
    ld a, [wPlayerXTile]
    call MultBy8
    ld b, a
    xor a
    ld de, $0203
    call UpdateSpritePos
    push af
    ld a, $18
    ld b, a
    pop af
    call UpdateSpriteTiles
    
    
    call DelayFrame
    jp M_OverworldLoop


; a - topleft sprite index in oam
; bc - position to set to
; de - size
UpdateSpritePos:
    push af
    push de
    push bc
    ld hl, wOAMBuffer
    ld bc, $0004
    call AddNTimes
    pop bc
.bigLoop
    push bc
.rowLoop
    ld a, c
    ld [hli], a
    ld a, b
    ld [hli], a
    inc hl
    inc hl
    ld a, b
    add 8
    ld b, a
    dec d
    jr nz, .rowLoop
    pop bc
    dec e
    jr z, .done
    ld a, e
    pop de
    push de
    ld e, a
    ld a, c
    add 8
    ld c, a
    jr .bigLoop
.done
    pop de
    pop af
    ret
    
; a - topleft sprite index in oam
; b - topleft graphic
; de - size
UpdateSpriteTiles:
    push bc
    ld hl, wOAMBuffer+2
    ld bc, $0004
    call AddNTimes
    pop bc
    xor a
.sizeLoop
    add d
    dec e
    jr nz, .sizeLoop
    ld d, a
    ld a, b
.writeLoop
    ld [hli], a
    inc a
    inc hl
    inc hl
    inc hl
    dec d
    jr nz, .writeLoop
    ret
    
MultBy8:
    push bc
    ld c, 7
    ld b, a
.loop
    add b
    dec c
    jr nz, .loop
    pop bc
    ret
    

    