// File: coins.agc
// Created: 20-05-06
// File: pickups.agc
// Created: 20-05-05

global gCoins as tPath

function ProcessCoins(vehicle ref as tVehicle, cell ref as tCell, env ref as tEnvironment)
	i as integer
	d as float
	x as integer
	
	if cell.coins.length < 0
		exitfunction
	endif
	
	d = (GetObjectDepth(vehicle.hit) * 0.5) + (GetObjectWidth(env.coin.id) * 0.5)
	
	for i=0 to cell.coins.length
		if DistanceXZ(GetObjectPos(vehicle.hit), GetObjectPos(cell.coins[i])) < d
			for x=0 to gCoins.nodes.length
				if gCoins.nodes[x].id = cell.coins[i]
					gCoins.nodes.remove(x)
					exit
				endif
			next
			PlayCrash(vehicle, env.coin.sound, TRUE)
			DeleteObject(cell.coins[i])
			cell.coins.remove(i)
			inc vehicle.coins
			inc vehicle.velocity.max, SCALE_3D * 0.5
			
			SetObject3DPhysicsMaxLinearVelocity( vehicle.hit, vehicle.velocity.max ) 			
			exit
		endif
	next
	
endfunction

function RotateCoins()
	i as integer
	for i=0 to gCoins.nodes.length
		RotateObjectLocalY(gCoins.nodes[i].id, 2)
	next
endfunction

function LoadCoins(env as tEnvironment)
	i 		as integer
	fnode	as tNode
	tnode	as tNode	
	d		as tPoint
	look	as integer
	coin	as integer
	cell	as tCell
	g		as tPoint
	new		as tPath
	
	gCoins = FindPathByName("coins")
	
	if gCoins.name = "bad"
		gCoins = new
		exitfunction
	endif
				
	for i=0 to gCoins.nodes.length
		fnode = gCoins.nodes[i]
		
		if mod(i,3) = 0 and (i + 2) =< gCoins.nodes.length			
			g.x = round(fnode.pos.x / TO_TILE_X) - gGrid.offset.x
			g.y = round(fnode.pos.y / TO_TILE_Y) - gGrid.offset.y
			g.z = round(fnode.pos.z / TO_TILE_Z) - gGrid.offset.z
			
			cell = gGrid.cells[round(g.z), round(g.x), round(g.y)]
			
			tNode = gCoins.nodes[i + 2]
			d.x = abs(tNode.pos.x - fNode.pos.x)
			d.z = abs(tNode.pos.z - fNode.pos.z)			
			if d.x > d.z
				d.x = 0 : d.z = fNode.pos.z
			else
				d.z = 0 : d.x = fNode.pos.x
			endif
		endif
					
		coin = CloneObject(env.coin.id)
		SetObjectVisible(coin, 1)
		
		fnode.id = coin
		
		fnode.pos.y = fnode.pos.y + GetObjectHeight(coin) * .8
		
		if d.x <> 0
			fnode.pos.x = d.x
		else
			fnode.pos.z = d.z
		endif
		
		SetObjectPos(coin, fnode.pos)
		
		gCoins.nodes[i] = fnode
		
		cell.coins.insert(coin)
		
		gGrid.cells[round(g.z), round(g.x), round(g.y)] = cell
	next
	
endfunction