#!/usr/bin/python
from pygame.locals import *;
from OpenGL.GL import *;
from OpenGL.GLU import *;
from ac3d import *;
import random;
import menu;
import pygame;
import sys;
import font;
import texture;
import common;
import rengine;
import gengine;
import object;
import smoke;
import map;
import os;

class Game:
	def __init__( self ):
		self.init( );

		self.timInterval=10.0
		self.curTime=0
		self.prevTime=0
		#loading models and textures
		rengine.loadModels( );
		self.font = font.Font(os.path.join("textures","Font.tga"));
		self.obj = texture.loadTexture(os.path.join("textures","menuback.tga"));
		self.mmen = menu.MenuPage( self.font, self.obj, ["ABOUT", "START", "CREDITS", "EXIT"] );
		self.mmen.mpageText.append("       POWER SAVER");
		self.abtmen = menu.MenuPage( self.font, self.obj, ["BACK"] );
		self.abtmen.mpageText.append("YOU ARE THE MOST CAPABLE PERSON IN");
		self.abtmen.mpageText.append("THIS COUNTRY FOR THIS JOB SAVE ");
		self.abtmen.mpageText.append("THE POWER PLANT FROM THE ENEMIES");
		self.abtmen.mpageText.append("THIS POWER PLANT IS VERY IMPORTANT");
		self.abtmen.fontsize = 6;
		
		self.credits = menu.MenuPage( self.font, self.obj, ["BACK"] );
		self.credits.fontsize = 6;
		self.credits.mpageText.append("SAVE POWER FOR PYWEEK");
		self.credits.mpageText.append("DESIGNED USING PYTHON AND OPENGL");
		self.credits.mpageText.append("CODERS:");
		self.credits.mpageText.append("     VAMSI");
		self.credits.mpageText.append("     KEDAR");

		self.optsmen = menu.MenuPage( self.font, self.obj, ["MISSION1", "MISSION2", "BACK" ] );
		self.menu = self.mmen;
		self.angle = 0;	
		self.frame = 0;	
		self.Timebase = 0;
		self.Time = 0;
		self.TimerEvent = USEREVENT+1;
		self.hudText = "PROTECT THE POWER PLANT";
		self.finalMesg = "";

		#loading sounds
		try :
		    common.Global_soundList['explosion'] = pygame.mixer.Sound(os.path.join("sounds","explosion.wav"));
		    common.Global_soundList['alarm'] = pygame.mixer.Sound(os.path.join("sounds","alarm.wav"));
		    common.Global_soundList['pick'] = pygame.mixer.Sound(os.path.join("sounds","pick.wav"));
		    common.Global_soundList['switch'] = pygame.mixer.Sound(os.path.join("sounds","weaponchange.wav"));
		    pygame.mixer.music.load(os.path.join("sounds","background"+random.choice(['0','1'])+".ogg"));
		    common.Global_soundEnabled = True;
		except:
		    print "Could not initialize sound system";
		    common.Global_soundEnabled = False;

#		if( len(sys.argv) > 1 ):
#			self.obj.load( sys.argv[1] );
#		else:
#			self.obj.load( os.path.join("models","gameairenemy.ac") );
		pygame.time.set_timer( self.TimerEvent, 70 );

	def timerFunc( self ):
	    smoke.Global_SmokeVar.animate( 0.05 );
	    if self.menu.done and self.finalMesg =="":
	#	if common.Global_EnemyCount == 0 and common.Global_MaxEnemyCount == 0:
	#	    self.finalMesg = "GAME WON";
		if common.Global_objArray[0].health <= 0:
		    self.finalMesg = "GAME OVER";
		for obj in common.Global_objArray:
		    obj.animate( );
		if  common.Global_objArray[0].health<500 and common.Global_objArray[0].health>0:
		    common.Global_objArray[0].health+=common.Global_healthIncr;
		gengine.collisionDetect( );
		self.curTime+=0.1;
		if self.curTime-self.prevTime > self.timInterval:
		    if self.timInterval > 1:
			self.timInterval-=0.01
			map.genEnemy();
			map.genAmmo( );
		    #if common.Global_MaxEnemyCount > 0:
		    self.prevTime=self.curTime

	def init( self ):
		glEnable( GL_TEXTURE_2D );
		glEnable( GL_DEPTH_TEST );
		glCullFace( GL_BACK );
		glViewport( 0, 0, 640, 480 );
		#glClearColor( 0.45,0.535,0.879, 1.0 );
		glClearColor( 1, 1, 1, 1.0 );
		glMatrixMode( GL_PROJECTION );
		glLoadIdentity( );
		glOrtho( -100, 100, -100, 100, -50, 50 );
		glMatrixMode( GL_MODELVIEW );
		glLoadIdentity( );
		glAlphaFunc( GL_GEQUAL, 0 );
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable( GL_BLEND );
		glDepthFunc( GL_LEQUAL);
		glEnable( GL_LIGHTING );
		glEnable( GL_LIGHT0 );
	   	position = [ 0, 40, 0, 0 ];
   		specular = [1.0, 1.0, 1.0, 1.0];
   		shininess = [100.0];
		glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, specular );
		glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, specular );
		glMaterialfv( GL_FRONT_AND_BACK, GL_SHININESS, shininess );
		glLightfv( GL_LIGHT0, GL_SPECULAR, specular );
		glLightfv( GL_LIGHT0, GL_AMBIENT, specular );
		glLightfv( GL_LIGHT0, GL_POSITION, position );
		
	def draw( self ):	
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

		#check if menu input is done
		if( self.menu.done ):
			#if done render game
			view3D( );
			rengine.render( );
			common.Global_Camera.Update()
			#render the hud
			view2D( );
			#self.hudText = "";
			glColor3f( .5, .4, .1 );
			glDisable(GL_LIGHTING);
			self.font.drawString( self.finalMesg, -80, 0, 20, 20 );
			glColor3f( 0, 0, 0 );
			self.font.drawString( self.hudText, -120, 80, 5, 5 );
			self.font.drawString( "PPLANT", 100, -90, 5, 5 );
			self.font.drawString( "SCORE:", 70, -70, 5, 5 );
			self.font.drawString( str(common.Global_ammoRockets), 25, -75, 5, 5 );
			self.font.drawString( str(common.Global_scoreCount), 100, -70, 5, 5 ); 
			rengine.drawHud( );
			glEnable(GL_LIGHTING);
		else:
			view3D( );
			self.menu.render( );

		glFlush( );
		self.frame+=1;
		self.Time = pygame.time.get_ticks( );
		if( self.Time - self.Timebase > 1000 ):
		#	print self.frame*1000.0/(self.Time-self.Timebase);
			self.Timebase = self.Time;
			self.frame = 0;

#		for obj in common.Global_objArray:
#		    obj.animate( );

		pygame.display.flip( );
	
	#event handling
	def procEvents( self, event ):
	
		if event.type == self.TimerEvent:
			#self.obj.animate(0.05);
			self.timerFunc( );
			self.menu.animate( );

		#processing menu events
		if( not(self.menu.done) ):
			txt = self.menu.keyEvents( event );
			if txt == 'EXIT':
				sys.exit(0);
			elif txt == 'MISSION1':
				self.menu.done = 1;	
				map.loadMap(os.path.join("maps","mission1.map"));
				self.hudText = "";
				self.finalMesg = "";
			elif txt == 'START':
				self.menu = self.optsmen;
			elif txt == 'CREDITS':
				self.menu = self.credits;
			elif txt == 'ABOUT':
				self.menu = self.abtmen;
			#handling back button
			elif txt == 'BACK':
				self.menu = self.mmen;

		#processing game events
		elif event.type is KEYDOWN:
			if event.key == K_ESCAPE:
			#	sys.exit(0);
				self.menu.done = 0;
			if event.key == K_UP or event.key== K_w:
			    common.Global_Camera.upPressed=True;	
			if event.key == K_DOWN or event.key== K_s:
			    common.Global_Camera.downPressed=True;	
			if event.key == K_LEFT or event.key== K_a:
			    common.Global_Camera.leftPressed=True;	
			if event.key == K_RIGHT or event.key== K_d:
			    common.Global_Camera.rightPressed=True;
			if event.key == K_1:
			    common.Global_curGun = "flareGun";
			if event.key == K_2:
			    common.Global_curGun = "rocketGun";

		elif event.type is MOUSEBUTTONDOWN:
		    #mouse button pressed, add rocket to that direction.		    
		    campos = common.Global_Camera.m_vPosition;
		    camlook = common.Global_Camera.m_vView;
		    velvec =  [camlook.x-campos.x, camlook.y-campos.y, camlook.z-campos.z];
		    rotangle = map.rot(velvec[0], velvec[2] );
		    rengine.Normalize(velvec);

		    if common.Global_curGun == "flareGun":
			velvec[0]*=20;
			velvec[1]*=20;
			velvec[2]*=20;
			obtype = "flare";
		    if common.Global_curGun == "rocketGun":
			velvec[0]*=20
			velvec[1]*=20
			velvec[2]*=20
			obtype = "rocket";
#		    else:
#			velvec[0]*=30
#			velvec[1]*=30
#			velvec[2]*=30
#			obtype ="default" 
		    newobj = object.gameObject( [campos.x, campos.y, campos.z], velvec, obtype );
		    newobj.rotAngle = 180+rotangle;
		    
		    #limited ammo for flare and rockets	    
		    if ( obtype == "flare" ):
			    common.Global_objMovArray.append(newobj);

		    if ( obtype == "rocket" and common.Global_ammoRockets > 0 ):
			    common.Global_objMovArray.append(newobj);
			    common.Global_ammoRockets-= 1;
		    else:
			    self.hudText = "OUT OF AMMO "+obtype.upper( );

		elif event.type is KEYUP:
			if event.key == K_ESCAPE:
			#	sys.exit(0);
				self.menu.done = 0;
			if event.key == K_UP or event.key== K_w:
			    common.Global_Camera.upPressed=False;	
			if event.key == K_DOWN or event.key == K_s:
			    common.Global_Camera.downPressed=False;	
			if event.key == K_LEFT or event.key == K_a:
			    common.Global_Camera.leftPressed=False;	
			if event.key == K_RIGHT or event.key == K_d:
			    common.Global_Camera.rightPressed=False;	

if __name__=="__main__":
	pygame.init( );
	pygame.display.set_mode((640,480),OPENGL|DOUBLEBUF)
	pygame.mouse.set_visible(False);
#	soundList[0].play( )
	myGame = Game( );
	while 1:
	    event = pygame.event.poll( );
	
	    if event.type is QUIT:
		sys.exit(0);
	    myGame.draw( );
	    myGame.procEvents( event );
	    if not pygame.mixer.music.get_busy():
	        pygame.mixer.music.rewind()
	        pygame.mixer.music.play()

