;; This file is part of Moonsters
;;  Copyright (C) 2021 Dam Studios
;;
;;     Moonsters 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 3 of the License, or
;;     (at your option) any later version.
;; 
;;     SHOOT TO MOVE 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 Moonsters  If not, see <https://www.gnu.org/licenses/>.



;;
;; PHYSICS SYSTEM
;;

.include "man/entity_manager.h.s"
.include "sys/render.h.s"

sys_physics_update:

	ld hl, #sys_physics_one_entity
    call man_entity_forall
    ret

sys_physics_one_entity:

	;;cambiamos la x
    	ld a, e_x(ix)
    	ld e_oldX(ix), a
    	ld b, e_vx(ix)
    	add a,b
    	ld e_x(ix), a

    	;;cambiamos la y
    	ld a, e_y(ix)
    	ld e_oldY(ix), a
    	ld b, e_vy(ix)
    	add a,b
    	ld e_y(ix), a

    
    call sys_render_getScroll
    ld b, a
    add a, b
    ld b, a
    ld a, e_x(ix)
    sub a, b
    jr c, left    ;; if (e_x(iy) + e_w(iy) - e_x(ix) < 0) __no_collision
    add #1
    jr nc, no_left    ;; if (e_x(iy) + e_w(iy) - e_x(ix) < 0) __no_collision

left:
    call out_of_bounds
    ret
no_left:

    ;;comprobamos si estan mas a la derecha
    call sys_render_getScroll
    ld b, a
    add a, b
    ld b, #81
    add a, b
    ld b, a
    ld a, e_x(ix)
    ld c, e_w(ix)
    add a, c
    sub b
    jr c, inside_screen
    ;ld e_type(ix), #e_type_destroy  ;Pruebas para el destructor 
    call out_of_bounds
    ret
inside_screen:

    call inside_screen_2
	
	ret


out_of_bounds:

    ;;Depende del tipo hacemos una cosa u otra

    ld a, e_type(ix)
    cp #e_type_bullet
    jr z, bullet
    cp #e_type_bullet_enemy
    jr z, bullet
    jr no_bullet

bullet:
    ;;si es una bala la destruimos
    ld e_type(ix), #e_type_destroy  
    ld d, e_oldVideo_l(ix)
    ld e, e_oldVideo_h(ix) ;;cargamos la posicion antigua
    ld a, #0x00
    ld b, e_h(ix)
    ld c, e_w(ix)
    call cpct_drawSolidBox_asm ;;Borramos lo antiguo

no_bullet:

    cp #e_type_default
    jr nz, no_player
player_border:
    ld a, e_oldX(ix)
    ld e_x(ix), a    

no_player:


    cp #e_type_enemy
    jr nz, no_alien
alien:
    ld a, e_render(ix)
    cp #e_render_notVisible
    jr z, no_alien
    ld a, #e_render_notVisibleFirst
    ld e_render(ix), a  

no_alien:


    ret


inside_screen_2:

        ;;Depende del tipo hacemos una cosa u otra

    ld a, e_type(ix)
    cp #e_type_enemy
    jr nz, no_alien_in

    ld a, #e_render_visible
    ld e_render(ix), a  

no_alien_in:


    ret
