;sfx code

;start SFX mode
.player_SFX_Start
	ld DE,(current_sfx_bank)
	call PLY_SFX_Init
	ret

;stop a SFX channel
; A = channel
.player_SFX_Stop
	call PLY_SFX_Stop
	ret
	
;stop all SFX
.player_SFX_StopAll
	call PLY_SFX_StopAll
	ret
	
;set chan_force mode
; 1 = 1 channel - 0 = 3 channels
.Player_SFX_SetChanForce
	ld (chan_force),A
	ld B,0
	or A
	jr nz,Player_SFX_SetChanForce1Channel
	ld B,4
.Player_SFX_SetChanForce1Channel
	ld A,B
	ld (SFX_PriorityPosA),A
	ld (SFX_PriorityPosB),A
	ret
	
;set SFX force channel mode
.Player_SFX_SetForcedChannel
	ld (SFX_ForcedChannel),A
	ret
	
;play SFX 
; A = SFX
.player_SFX_Play
;first off all , get SFX address in IX
	ld L,A
	ld H,0
	ld E,A
	ld D,H
	add HL,HL	;2
	add HL,HL	;4
	add HL,DE	;4+1 = 5
	;add HL,HL	;8
	ex DE,HL
	ld IX,sfx_table
	add IX,DE
	
;check priority bit 7 , if chan_force mode so exit
	ld A,(chan_force)
	or A
	jr z,SFX_PlayNoForceChannel
	
	bit 7,(IX+0)	;is bit 7 set ?
	ret nz			;it is a 3 channels only sound so exit
	
.SFX_PlayNoForceChannel
	
;get playing channel
SFX_ForcedChannel	EQU $+1
	ld HL,1		;forced channel
	ld A,(chan_force)
	or A
	jr nz,SFX_Play_ForceChannel
	ld L,(IX+1)	
.SFX_Play_ForceChannel
	
;save channel
	push HL
	
;get channel on table
	add HL,HL	;*2
	ld DE,arkos_channel_table
	add HL,DE
;get address
	ld E,(HL)
	inc HL
	ld D,(HL)
	ex DE,HL
	
;check if we are playing a sfx
	ld A,(HL)
	inc HL
	or (HL)
	
	jr z,SFX_PlayChannelNotPlaying
	
	pop DE	;get current channel in HL
	push DE
	
	ld HL,chan_state
	add HL,DE
	
	ld A,(HL)	;priority ?
	;cp (IX+0)
SFX_PriorityPosA	EQU $+2
	ld E,(IX+0)	;remove bit 7
	res 7,E
	cp E
	;is lower than wanted sfx ?
	jr nc,SFX_PlayChannelNotPlaying	;no ? so play sfx
	;jr z,SFX_PlayChannelNotPlaying	;if equal too
	
	;else , don't play SFX
	pop DE
	ret
	
.SFX_PlayChannelNotPlaying
	pop DE
;now start serious thingies :D
	;A = No Channel (0,1,2)
	;L = SFX Number (>0)
	;H = Volume (0...F)
	;E = Note (0...143) (0 is the lowest, 143 the highest)
	;D = Speed (0 = As original, 1...255 = new Speed (1 is the fastest))
	;BC = Inverted Pitch (-&FFFF -> &FFFF). 0 is no pitch (=the original sound). The higher the pitch, the lower the sound.
	
;get priority first
	ld L,E
	ld H,D
	ld BC,chan_state	
	add HL,BC

SFX_PriorityPosB	EQU $+2	
	ld A,(IX)
	and 127	;remove the bit 7 !
	ld (HL),A	;write it

;save channel
	ld A,E
	ex AF,AF'	
;compute note
	ld E,(IX+3)
;compute speed
	;ld D,(IX+4)
	ld D,0
;volume
	ld A,(SFX_volume)
	ld H,A
;sfx
	ld L,(IX+2)
;pitch
	ld BC,0
;channel
	ex AF,AF'
	
	call PLY_SFX_Play

	ret
	
	
;if 0 , 3 channels SFX else 1 channel
.chan_force	
	db 1
	
.SFX_volume
	db 15
	
;arkos tracker channel table
.arkos_channel_table
	dw PLY_SFX_Track1_Instrument + 1
	dw PLY_SFX_Track2_Instrument + 1
	dw PLY_SFX_Track3_Instrument + 1
	
;channels info
chan_size	EQU 1
.chan_state	
	db	0
	db	0
	db	0
	
;SFX table
read "sfx_table.asm"