// OpenALDemo.cpp : Defines the entry point for the console application.
//

#include <math.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <al\alut.h>

#define NUM_BUFFERS 2
#define NUM_SOURCES 16
#define NUM_ENVIRONMENTS 1

ALfloat listenerPos[]={0.0,0.0,0.0};
ALfloat listenerVel[]={0.0,0.0,0.0};
ALfloat	listenerOri[]={0.0,0.0,1.0, 0.0,1.0,0.0};

ALfloat source0Pos[]={ 0.0, 0.0, 1.0};
ALfloat source0Vel[]={ 0.0, 0.0, 1.0};

ALfloat source1Pos[]={ 2.0, 0.0,-1.0};
ALfloat source1Vel[]={ 0.0, 0.0, 1.0};

ALuint	buffer[NUM_BUFFERS];
ALuint	source[NUM_SOURCES];
ALuint  environment[NUM_ENVIRONMENTS];

int main(int argc, char* argv[])
{
	ALsizei size,freq;
	ALenum format;
	ALvoid *data;
	int ch,i;
 
	printf("OpenAL demonstration application\n\n");

	alutInit(&argc,argv);
	
	alListenerfv(AL_POSITION,listenerPos);
	alListenerfv(AL_VELOCITY,listenerVel);
	alListenerfv(AL_ORIENTATION,listenerOri);

	alGenBuffers(NUM_BUFFERS,buffer);
	for (i=0;i<NUM_BUFFERS;i++)
	{
		if (!alIsBuffer(buffer[i]))
		{
			printf("- Error creating buffers !!\n");
			exit(1);
		}
	}

	alutLoadWAVFile("test0.wav",&format,&data,&size,&freq);
	alBufferData(buffer[0],format,data,size,freq);
	alutUnloadWAV(format,data,size,freq);

	alutLoadWAVFile("shot.wav",&format,&data,&size,&freq);
	alBufferData(buffer[1],format,data,size,freq);
	alutUnloadWAV(format,data,size,freq);

	alGenSources(NUM_SOURCES,source);
	for (i=0;i<NUM_SOURCES;i++)
	{
		if (!alIsSource(source[i]))
		{
			printf("- Error creating sources !!\n");
			exit(2);
		}
	}

	alSourcef(source[0],AL_PITCH,1.0f);
	alSourcef(source[0],AL_GAIN,1.0f);
	alSourcefv(source[0],AL_POSITION,source0Pos);
	alSourcefv(source[0],AL_VELOCITY,source0Vel);
	alSourcei(source[0],AL_BUFFER,buffer[0]);
	alSourcei(source[0],AL_LOOPING,AL_TRUE);

	alSourcef(source[1],AL_PITCH,1.0f);
	alSourcef(source[1],AL_GAIN,1.0f);
	alSourcefv(source[1],AL_POSITION,source1Pos);
	alSourcefv(source[1],AL_VELOCITY,source1Vel);
	alSourcei(source[1],AL_BUFFER,buffer[1]);
	alSourcei(source[1],AL_LOOPING,AL_FALSE);

	do
	{
		ch = _getch();
		ch = toupper( ch );
		switch (ch)
		{
			case '1':alSourcePlay(source[0]);
					 break;
			case '2':alSourcePlay(source[1]);
					 break;
			case '3':alSourceStop(source[0]);
					 break;
			case '4':alSourceStop(source[1]);
					 break;
		}
	} while (ch != 'Q');

	alSourceStop(source[1]);
	alSourceStop(source[0]);

	alutExit();

	return 0;
}

