
#include <math.h>

#include "allegro.h"
#include "game.h"
#include "sound2.h"
#include "log.h"

static GAME *game;

/* Plays a sound at the specified location. Paramters are the same as for
 * play_sample(). Panning and volume are calculated depending on the angle
 * and distance of the sound's origin compared to the player's coordinates.
 */
int play_sound(SAMPLE *sample, float x, float y, float z, int vol, int freq, int loop) {

	OUTPUTDEV *dev;
	float tvol = 0, rvol = 0;
	int pan;

	if (!game)
		return play_sample(sample, vol, 128, freq, loop);

	dev = game->output;

	while (dev) {
		/* Compute player->source vector */
		if (dev->player && dev->player->sprite) {
			SPRITE *spr = dev->player->sprite;

			float vx = x - dev->player->sprite->x,
				  vy = y - dev->player->sprite->y,
				  vz = z - dev->player->sprite->z;
			float d = SQDIST3(vx, vy, vz);
			float xr;

			if (d < 0.01)
				xr = 0.5;
			else
				xr = 0.5 + (vx * cos(spr->th) + vy * sin(spr->th)) / (2.0 * sqrt(d));

			//set zr to volume, according to inverse square law
			//the constant means samples at full volume up to distance 3
			if (d < 9.0)
				d = vol;
			else
				d = vol * 9.0 / d;
			//0 <= xr <= 1
			//update tvol (total volume) and rvol (right volume)
			tvol += d;
			rvol += d * xr;
		}
		dev = dev->next;
	}
	if (tvol >= 255)
		vol = 255;
	else 
		vol = (int)tvol;

	pan = 255.0 * rvol / tvol;
	pan = MID(0, pan, 255);

	LOG("Player sound at (%f, %f, %f), final volume: %i, final pan: %i loop: %i\n", x, y, z, vol, pan, loop);

	return play_sample(sample, vol, pan, freq, loop);
}

/* Use this function to select which game will be used for the sound
 * controls. Remember to set it to NULL when you're done or the game
 * ended.
 */
void sound_select_game(GAME *g) {
	game = g;
}


