예제 #1
0
/* Calculate projection matrix */
static void dlCameraCalculateProjectionMatrix( dlCamera *object )
{
   CALL("%p", object);

   kmMat4PerspectiveProjection( &object->projection, object->fov, object->aspect,
                                object->zNear, object->zFar );
}
예제 #2
0
파일: EGLView.cpp 프로젝트: hgl888/DialogGl
void EGLView::setProjection(ccDirectorProjection kProjection)
{
	CCSize size = m_obDesignResolutionSize;

	setViewPortInPoints(0, 0, m_obDesignResolutionSize.width, m_obDesignResolutionSize.height);

	switch (kProjection)
	{
	case kCCDirectorProjection2D:
		{
			kmGLMatrixMode(KM_GL_PROJECTION);
			kmGLLoadIdentity();
			kmMat4 orthoMatrix;
			kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, size.height, 0, -1024, 1024 );
			kmGLMultMatrix(&orthoMatrix);
			kmGLMatrixMode(KM_GL_MODELVIEW);
			kmGLLoadIdentity();
		}
		break;

	case kCCDirectorProjection3D:
		{
			float zeye = m_obDesignResolutionSize.height / 1.1566f;

			kmMat4 matrixPerspective, matrixLookup;

			kmGLMatrixMode(KM_GL_PROJECTION);
			kmGLLoadIdentity();

			// issue #1334
			kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, zeye*2);
			// kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, 1500);

			kmGLMultMatrix(&matrixPerspective);

			kmGLMatrixMode(KM_GL_MODELVIEW);
			kmGLLoadIdentity();
			kmVec3 eye, center, up;
			kmVec3Fill( &eye, size.width/2, size.height/2, zeye );
			kmVec3Fill( &center, size.width/2, size.height/2, 0.0f );
			kmVec3Fill( &up, 0.0f, 1.0f, 0.0f);
			kmMat4LookAt(&matrixLookup, &eye, &center, &up);
			kmGLMultMatrix(&matrixLookup);
		}
		break;
	default:
		CCLOG("cocos2d: Director: unrecognized projection");
		break;
	}

	m_eProjection = kProjection;
	ccSetProjectionMatrixDirty();
}
예제 #3
0
int main(int argc, char** argv)
{
    // Get width and height
    if (argc > 1)
    {
        width = atoi(argv[1]);
        if (argc > 2)
            height = atoi(argv[2]);
    }

    // Set up the rasteriser
    srInitParams params;
    params.width = width;
    params.height = height;
    params.outputContext = SR_CTX_SDL;
    srInit(&params);
    width = srGetWidth();
    height = srGetHeight();
    srSetMaxFPS(60);
    // srSetRenderState(SR_WIREFRAME, SR_TRUE);

    // Set projectino matrix
    float aspect = (float)width / height;
    kmMat4PerspectiveProjection(&proj, 60.0f, aspect, 0.1f, 100.0f);

    // Initialise the scene
    init();

    // Enter rendering loop
    kmVec3 eye;
    kmVec3 centre;
    kmVec3 up;
    float angle = 0.0f;
    while (srContextActive())
    {
        // Calculate view matrix
        kmMat4LookAt(&view, kmVec3Fill(&eye, 0.0f, 0.0f, 3.0f),
                     kmVec3Fill(&centre, 0.0f, 0.0f, 0.0f), kmVec3Fill(&up, 0.0f, 1.0f, 0.0f));

        // Draw scene
        srBegin(0);
        render(angle);
        srEnd();

        // Update rotation
        angle += M_PI / 2.0f * 0.01f;
    }

    // Clean-up
    cleanup();
    srShutdown();
    return 0;
}
void window_size_callback(GLFWwindow* window, int w, int h)
{
	width=w;height=h;

    glViewport(0, 0, width, height);

    // projection matrix, as distance increases
    // the way the model is drawn is effected
    kmMat4Identity(&projection);
    kmMat4PerspectiveProjection(&projection, 45,
                                (float)width / height, 0.1, 1000);

	reProjectGlPrint(width,height); // updates the projection matrix used by glPrint
	reProjectSprites(width,height); // updates the projection matrix used by the sprites
	resizePointCloudSprites((float)width/24.0);

}
예제 #5
0
//设置一下观察与投影矩阵
void	C3DLayer::UpdateViewProjMatrix()
{
	//观察矩阵的设置
	Vec3 tEyeResult = Vec3(0,0,-2);
	Vec3 tLookAtResult = Vec3(0,0,0);
	Vec3 tUpResult = Vec3(0,1,0);
	Mat4 tViewMatrix;
	kmMat4LookAt(&tViewMatrix, &tEyeResult, &tLookAtResult, &tUpResult);
    
	kmGLMatrixMode(KM_GL_MODELVIEW);
	kmGLLoadIdentity();
	kmGLMultMatrix(&tViewMatrix);
    
	//投影矩阵的设置
	Mat4 matrixPerspective;
	kmGLMatrixMode(KM_GL_PROJECTION);
	kmGLLoadIdentity();
	CCSize size =  CCDirector::sharedDirector()->getVisibleSize();
	kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, 500.0f);
	kmGLMultMatrix(&matrixPerspective);
	
}
예제 #6
0
void cxEngineLayout(cxInt width,cxInt height)
{
    CX_LOGGER("openGL layout width=%d height=%d",width,height);
    cxEngine engine = cxEngineInstance();
    engine->winsize = cxSize2fv(width, height);
    cxViewSetSize(engine->window, engine->winsize);
    if(!cxSize2Zero(engine->dessize)){
        engine->scale = cxVec2fv(engine->winsize.w/engine->dessize.w, engine->winsize.h/engine->dessize.h);
    }
    //
    if(!engine->isInit){
        cxOpenGLCheckFeature();
        cxEngineMain(engine);
    }
    //
    cxFloat zeye = engine->winsize.h / 1.1566f;
    kmMat4 perspective={0};
    kmGLMatrixMode(KM_GL_PROJECTION);
    kmGLLoadIdentity();
    //
    kmMat4PerspectiveProjection(&perspective, 60.0f, engine->winsize.w / engine->winsize.h, 0.0f, zeye * 2);
    kmGLMultMatrix(&perspective);
    kmGLMatrixMode(KM_GL_MODELVIEW);
    kmGLLoadIdentity();
    //
    cxOpenGLViewport(cxBox4fv(0, engine->winsize.w, 0, engine->winsize.h));
    //
    cxMatrix4f matrix;
    cxEngineLookAt(&matrix,cxVec2fv(0, 0));
    kmGLMultMatrix(&matrix);
    //
    engine->lastTime = cxTimestamp();
    if(!engine->isInit){
        cxViewEnter(engine->window);
    }
    cxViewLayout(engine->window);
    engine->isInit = true;
}
예제 #7
0
파일: camera.c 프로젝트: Cloudef/glhck
/* \brief calculate projection matrix */
static void _glhckCameraProjectionMatrix(glhckCamera *object)
{
   kmScalar w, h, distanceFromTarget;
   kmVec3 toTarget;

   CALL(2, "%p", object);
   assert(object);
   assert(object->view.viewport.w > 0.0f && object->view.viewport.h > 0.0f);

   switch(object->view.projectionType) {
      case GLHCK_PROJECTION_ORTHOGRAPHIC:
	 w = object->view.viewport.w > object->view.viewport.h ? 1 :
	    object->view.viewport.w / object->view.viewport.h;
	 h = object->view.viewport.w < object->view.viewport.h ? 1 :
	    object->view.viewport.h / object->view.viewport.w;

	 kmVec3Subtract(&toTarget, &object->object->view.translation, &object->object->view.target);
	 distanceFromTarget = kmVec3Length(&toTarget);

	 w *= (distanceFromTarget+object->view.near)/2;
	 h *= (distanceFromTarget+object->view.near)/2;

	 kmMat4OrthographicProjection(&object->view.projection,
	       -w, w, -h, h, object->view.near, object->view.far);
	 break;

      case GLHCK_PROJECTION_PERSPECTIVE:
      default:
	 kmMat4PerspectiveProjection(
	       &object->view.projection,
	       object->view.fov,
	       (float)object->view.viewport.w/(float)object->view.viewport.h,
	       object->view.near, object->view.far);
	 break;
   }
}
int main()
{

    lightDir.x=0.5;
    lightDir.y=.7;
    lightDir.z=-0.5;
    kmVec3Normalize(&lightDir,&lightDir);

    // creates a window and GLES context
    // create a window and GLES context
	if (!glfwInit())
		exit(EXIT_FAILURE);

	window = glfwCreateWindow(width, height, "I N V A D E R S ! ! !", NULL, NULL);
	if (!window) {
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	glfwSetWindowSizeCallback(window,window_size_callback);	
	glfwMakeContextCurrent(window);



    // all the shaders have at least texture unit 0 active so
    // activate it now and leave it active
    glActiveTexture(GL_TEXTURE0);

    // The obj shapes and their textures are loaded
    cubeTex = loadPNG("resources/textures/dice.png");
    loadObj(&cubeObj, "resources/models/cube.gbo",
            "resources/shaders/textured.vert", "resources/shaders/textured.frag");


    shipTex = loadPNG("resources/textures/shipv2.png");
    loadObjCopyShader(&shipObj,"resources/models/ship.gbo",&cubeObj);

    alienTex = loadPNG("resources/textures/alien.png");
    loadObjCopyShader(&alienObj, "resources/models/alien.gbo", &cubeObj);

    shotTex = loadPNG("resources/textures/shot.png");
    loadObjCopyShader(&shotObj, "resources/models/shot.gbo", &cubeObj);

    expTex = loadPNG("resources/textures/explosion.png");


    playerPos.x = 0;
    playerPos.y = 0;
    playerPos.z = 0;

    kmMat4Identity(&view);

    pEye.x = 0;
    pEye.y = 2;
    pEye.z = 4;
    pCenter.x = 0;
    pCenter.y = 0;
    pCenter.z = -5;
    pUp.x = 0;
    pUp.y = 1;
    pUp.z = 0;

    kmMat4LookAt(&view, &pEye, &pCenter, &pUp);

    // projection matrix, as distance increases
    // the way the model is drawn is effected
    kmMat4Identity(&projection);
    kmMat4PerspectiveProjection(&projection, 45,
                                (float)width/ height, 0.1, 1000);

    glViewport(0, 0, width,height);

    // these two matrices are pre combined for use with each model render
    kmMat4Assign(&vp, &projection);
    kmMat4Multiply(&vp, &vp, &view);

    // initialises glprint's matrix shader and texture
    initGlPrint(width,height);

	font1=createFont("resources/textures/font.png",0,256,16,16,16);
	font2=createFont("resources/textures/bigfont.png",32,512,9.5,32,48);

    glCullFace(GL_BACK);
    glEnable(GL_CULL_FACE);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_BLEND);	// only used by glprintf
    glEnable(GL_DEPTH_TEST);


    int num_frames = 0;

    bool quit = false;

    resetAliens();

    for (int n = 0; n < MAX_PLAYER_SHOTS; n++) {
        playerShots[n].alive = false;
    }


    initPointClouds("resources/shaders/particle.vert",
                    "resources/shaders/particle.frag",(float)width/24.0);



    for (int n = 0; n < MAX_ALIENS; n++) {
        aliens[n].explosion=createPointCloud(40);
        resetExposion(aliens[n].explosion); // sets initials positions
    }

	glClearColor(0, .5, 1, 1);

    while (!quit) {		// the main loop

        clock_gettime(0,&ts);  // note the time BEFORE we start to render the current frame
		glfwPollEvents();


        if (glfwGetKey(window,GLFW_KEY_ESCAPE)==GLFW_PRESS || glfwWindowShouldClose(window))
            quit = true;

        float rad;		// radians rotation based on frame counter

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        frame++;
        rad = frame * (0.0175f * 2);

        //kmMat4Identity(&model);
        kmMat4Translation(&model, playerPos.x, playerPos.y, playerPos.z);
        playerCroll +=
            (PIDcal(playerRoll, playerCroll, &playerPre_error, &playerIntegral)
             / 2);
//        kmMat4RotationPitchYawRoll(&model, 0, 3.1416, playerCroll * 3);	//
		kmMat4RotationYawPitchRoll(&rot,0,3.1416,-playerCroll*3);
        kmMat4Multiply(&model, &model, &rot);
        
        kmMat4Assign(&mvp, &vp);
        kmMat4Multiply(&mvp, &mvp, &model);

        kmMat4Assign(&mv, &view);
        kmMat4Multiply(&mv, &mv, &model);

        glBindTexture(GL_TEXTURE_2D, shipTex);
        drawObj(&shipObj, &mvp, &mv, lightDir, viewDir);

        glPrintf(50 + sinf(rad) * 16, 240 + cosf(rad) * 16,
                 font2,"frame=%i", frame);

        kmVec3 tmp;

        playerFireCount--;

        if (glfwGetKey(window,GLFW_KEY_LEFT_CONTROL)==GLFW_PRESS && playerFireCount < 0) {

            struct playerShot_t *freeShot;
            freeShot = getFreeShot();
            if (freeShot != 0) {
                playerFireCount = 15;
                freeShot->alive = true;
                kmVec3Assign(&freeShot->pos, &playerPos);
            }
        }

        for (int n = 0; n < MAX_PLAYER_SHOTS; n++) {
            if (playerShots[n].alive) {
                playerShots[n].pos.z -= .08;
                if (playerShots[n].pos.z < -10)
                    playerShots[n].alive = false;

                //kmMat4Identity(&model);
                kmMat4Translation(&model, playerShots[n].pos.x,
                                  playerShots[n].pos.y,
                                  playerShots[n].pos.z);
                //kmMat4RotationPitchYawRoll(&model, rad * 4, 0,
                //                           -rad * 4);
				kmMat4RotationYawPitchRoll(&rot,rad*4,0,-rad*4);
				kmMat4Multiply(&model,&model,&rot);
                kmMat4Assign(&mvp, &vp);
                kmMat4Multiply(&mvp, &mvp, &model);

                kmMat4Assign(&mv, &view);
                kmMat4Multiply(&mv, &mv, &model);

                glBindTexture(GL_TEXTURE_2D, shotTex);
                drawObj(&shotObj, &mvp, &mv, lightDir, viewDir);
            }
        }

        playerRoll = 0;
        if (glfwGetKey(window,GLFW_KEY_LEFT)==GLFW_PRESS && playerPos.x > -10) {
            playerPos.x -= 0.1;
            playerRoll = .2;
        }
        if (glfwGetKey(window,GLFW_KEY_RIGHT)==GLFW_PRESS && playerPos.x < 10) {
            playerPos.x += 0.1;
            playerRoll = -.2;
        }
        pEye.x = playerPos.x * 1.25;

        pCenter.x = playerPos.x;
        pCenter.y = playerPos.y + 1;
        pCenter.z = playerPos.z;

        int deadAliens;

        deadAliens = 0;

        for (int n = 0; n < MAX_ALIENS; n++) {
            if (aliens[n].alive == true) {

                //kmMat4Identity(&model);
                kmMat4Translation(&model, aliens[n].pos.x,
                                  aliens[n].pos.y, aliens[n].pos.z);
                //kmMat4RotationPitchYawRoll(&model, -.4, 0, 0);
				kmMat4RotationYawPitchRoll(&rot,.2,0,0);
				kmMat4Multiply(&model,&model,&rot);

                kmMat4Assign(&mvp, &vp);
                kmMat4Multiply(&mvp, &mvp, &model);

                kmMat4Assign(&mv, &view);
                kmMat4Multiply(&mv, &mv, &model);

                glBindTexture(GL_TEXTURE_2D, alienTex);
                drawObj(&alienObj, &mvp, &mv, lightDir, viewDir);

                kmVec3 d;
                for (int i = 0; i < MAX_PLAYER_SHOTS; i++) {
                    kmVec3Subtract(&d, &aliens[n].pos,
                                   &playerShots[i].pos);
                    if (kmVec3Length(&d) < .7
                            && playerShots[i].alive) {
                        aliens[n].alive = false;
                        playerShots[i].alive = false;
                        aliens[n].exploding = true;
                        resetExposion(aliens[n].explosion);
                    }
                }
            } 

            if (aliens[n].alive != true && aliens[n].exploding != true) {
                    deadAliens++;
                
            }
        }

        if (deadAliens == MAX_ALIENS) {
            resetAliens();
        }

		// draw explosions after ALL aliens
        for (int n = 0; n < MAX_ALIENS; n++) {
			if (aliens[n].exploding==true) {
				kmMat4Identity(&model);
				kmMat4Translation(&model, aliens[n].pos.x,
								  aliens[n].pos.y, aliens[n].pos.z);

				kmMat4Assign(&mvp, &vp);
				kmMat4Multiply(&mvp, &mvp, &model);
				glBindTexture(GL_TEXTURE_2D, expTex);
				drawPointCloud(aliens[n].explosion, &mvp);
				aliens[n].explosion->tick=aliens[n].explosion->tick+0.05;
				if (aliens[n].explosion->tick>1.25) {
					aliens[n].exploding=false;                   	
				} else {
					// update the explosion
					
					for (int i=0; i<aliens[n].explosion->totalPoints; i++) {
				
						float t;
						t=aliens[n].explosion->tick;
						if (i>aliens[n].explosion->totalPoints/2) t=t/2.0;
						aliens[n].explosion->pos[i*3]=aliens[n].explosion->vel[i*3] * t;
						aliens[n].explosion->pos[i*3+1]=aliens[n].explosion->vel[i*3+1] * t;
						aliens[n].explosion->pos[i*3+2]=aliens[n].explosion->vel[i*3+2] * t;
				
					}
				}
			}
		}

        // move camera
        kmMat4LookAt(&view, &pEye, &pCenter, &pUp);

        kmMat4Assign(&vp, &projection);
        kmMat4Multiply(&vp, &vp, &view);

        kmVec3Subtract(&viewDir,&pEye,&pCenter);
        kmVec3Normalize(&viewDir,&viewDir);

        // dump values
        glPrintf(100, 280, font1,"eye    %3.2f %3.2f %3.2f ", pEye.x, pEye.y, pEye.z);
        glPrintf(100, 296, font1,"centre %3.2f %3.2f %3.2f ", pCenter.x, pCenter.y,
                 pCenter.z);
        glPrintf(100, 340, font1,"frame %i %i ", frame, frame % 20);



        glfwSwapBuffers(window);

        ts.tv_nsec+=20000000;  // 1000000000 / 50 = 50hz less time to render the frame
        //thrd_sleep(&ts,NULL); // tinycthread
        usleep(20000); // while I work out why tinycthread that was working isnt.... :/

    }

	glfwDestroyWindow(window);
	glfwTerminate();

    return 0;
}
예제 #9
0
파일: camera.cpp 프로젝트: chenbk85/KGLT
void Camera::set_perspective_projection(double fov, double aspect, double near, double far) {
    kmMat4PerspectiveProjection(&projection_matrix_, fov, aspect, near, far);
    update_frustum();
}
예제 #10
0
int process_inputs()
{
	// Get mouse position
        double xpos, ypos;
        glfwGetCursorPos(mainWindow, &xpos, &ypos);

        // Reset mouse position for next frame
        glfwSetCursorPos(mainWindow, SCREEN_WIDTH/2, SCREEN_HEIGHT/2);

        // Compute new orientation
        horizontalAngle += mouseSpeed * (float)( SCREEN_WIDTH/2 - xpos );
        verticalAngle   += mouseSpeed * (float)( SCREEN_HEIGHT/2 - ypos );
	/* If F1, reload */
	if (glfwGetKey(mainWindow, GLFW_KEY_F1)) {
		Engine_Reload();
	}
	/* If F2, reset view */
	if (glfwGetKey(mainWindow, GLFW_KEY_F2)) {
		printf("Camera reset.\n");
		Camera_Reset();
	}
	/* If tab, change lookat to next mesh */
	if (glfwGetKey(mainWindow, GLFW_KEY_TAB)) {
		//Camera_LookAtNext();
	}
	/* Move closer */
	//if (glfwGetKey(mainWindow, GLFW_KEY_W)) {
	//	ypos = 100;
	//}
	/* Move further */
	//if (glfwGetKey(mainWindow, GLFW_KEY_S)) {
	//	ypos = -100;
	//}
	/* Move left */
	//if (glfwGetKey(mainWindow, GLFW_KEY_A)) {
	//	xpos = 100;
	//}
	/* Move right */
	//if (glfwGetKey(mainWindow, GLFW_KEY_D)) {
	//	xpos = -100;
	//}

	// Compute new orientation
	//horizontalAngle += mouseSpeed * (float)(1024/2 - xpos );
	//verticalAngle   += mouseSpeed * (float)( 768/2 - ypos );
	horizontalAngle += mouseSpeed * xpos;
	verticalAngle += mouseSpeed * ypos;
	//printf("horizontalAngle is %f,	and verticalAngle is %f.\n", horizontalAngle, verticalAngle);

	// Direction : Spherical coordinates to Cartesian coordinates conversion
	float temp1 = cos(verticalAngle) * sin(horizontalAngle);
	float temp2 = sin(verticalAngle);
	float temp3 = cos(verticalAngle) * cos(horizontalAngle);
	kmVec3 direction = {temp1, temp2, temp3};
	
	// Right vector
	kmVec3 right = {
		sin(horizontalAngle - 3.14f/2.0f), 
		0,
		cos(horizontalAngle - 3.14f/2.0f)
	};
	
	// Up vector
	kmVec3 up = *kmVec3Cross(&up, &right, &direction );

	// Move forward
	if (glfwGetKey( mainWindow, GLFW_KEY_UP ) == GLFW_PRESS){
		kmVec3Add(&position, &position, kmVec3Scale(&position, &direction, deltaTime * speed));
	}
	// Move backward
	if (glfwGetKey( mainWindow, GLFW_KEY_DOWN ) == GLFW_PRESS){
		kmVec3Subtract(&position, &position, kmVec3Scale(&position, &direction, deltaTime * speed));
	}
	// Strafe right
	if (glfwGetKey( mainWindow, GLFW_KEY_RIGHT ) == GLFW_PRESS){
		kmVec3Add(&position, &position, kmVec3Scale(&position, &right, deltaTime * speed));
	}
	// Strafe left
	if (glfwGetKey( mainWindow, GLFW_KEY_LEFT ) == GLFW_PRESS){
		kmVec3Subtract(&position, &position, kmVec3Scale(&position, &right, deltaTime * speed));
	}

	float FoV = initialFoV;

	kmMat4PerspectiveProjection(&ProjectionMatrix, FoV, (16.0f / 8.0f), 0.1f, 100.0f);
	// Camera matrix
	//ViewMatrix       = glm::lookAt(
	//							position,           // Camera is here
	//							position+direction, // and looks here : at the same position, plus "direction"
	//							up                  // Head is up (set to 0,-1,0 to look upside-down)
	//					   );

	kmVec3 p_eye;
	p_eye = position;

	kmVec3 p_ctr;
	p_ctr = *kmVec3Add(&p_ctr, &position, &direction);

	kmVec3 p_up;
	p_up = up;
	kmMat4LookAt(&ViewMatrix, &p_eye, &p_ctr, &p_up);
	kmMat4Identity(&ModelMatrix);
	kmMat4 temp_mat;
	kmMat4Multiply(&temp_mat, &ViewMatrix, &ModelMatrix);
	kmMat4Multiply(&MVP, &ProjectionMatrix, &temp_mat );

	//printf("Matrix contains:\n");
	//printf("%f, %f, %f, %f\n", MVP.mat[0], MVP.mat[1], MVP.mat[2], MVP.mat[3]);
	//printf("%f, %f, %f, %f\n", MVP.mat[4], MVP.mat[5], MVP.mat[6], MVP.mat[7]);
	//printf("%f, %f, %f, %f\n", MVP.mat[8], MVP.mat[9], MVP.mat[10], MVP.mat[11]);
	//printf("%f, %f, %f, %f\n", MVP.mat[12], MVP.mat[13], MVP.mat[14], MVP.mat[15]);
	
	return 0;
}
예제 #11
0
int main()
{




    lightDir.x=0.5;
    lightDir.y=.7;
    lightDir.z=-0.5;
    kmVec3Normalize(&lightDir,&lightDir);

    // creates a window and GLES context
    if (makeContext() != 0)
        exit(-1);

    // all the shaders have at least texture unit 0 active so
    // activate it now and leave it active
    glActiveTexture(GL_TEXTURE0);

    // The obj shapes and their textures are loaded
    cubeTex = loadPNG("resources/textures/dice.png");
    loadObj(&cubeObj, "resources/models/cube.gbo",
            "resources/shaders/textured.vert", "resources/shaders/textured.frag");


    shipTex = loadPNG("resources/textures/shipv2.png");
    loadObjCopyShader(&shipObj,"resources/models/ship.gbo",&cubeObj);

    alienTex = loadPNG("resources/textures/alien.png");
    loadObjCopyShader(&alienObj, "resources/models/alien.gbo", &cubeObj);

    shotTex = loadPNG("resources/textures/shot.png");
    loadObjCopyShader(&shotObj, "resources/models/shot.gbo", &cubeObj);

    expTex = loadPNG("resources/textures/explosion.png");





    playerPos.x = 0;
    playerPos.y = 0;
    playerPos.z = 0;

    kmMat4Identity(&view);

    pEye.x = 0;
    pEye.y = 2;
    pEye.z = 4;
    pCenter.x = 0;
    pCenter.y = 0;
    pCenter.z = -5;
    pUp.x = 0;
    pUp.y = 1;
    pUp.z = 0;

    kmMat4LookAt(&view, &pEye, &pCenter, &pUp);

    // projection matrix, as distance increases
    // the way the model is drawn is effected
    kmMat4Identity(&projection);
    kmMat4PerspectiveProjection(&projection, 45,
                                (float)getDisplayWidth() / getDisplayHeight(), 0.1, 100);

    glViewport(0, 0, getDisplayWidth(), getDisplayHeight());

    // these two matrices are pre combined for use with each model render
    kmMat4Assign(&vp, &projection);
    kmMat4Multiply(&vp, &vp, &view);

    // initialises glprint's matrix shader and texture
    initGlPrint(getDisplayWidth(), getDisplayHeight());

	font1=createFont("resources/textures/font.png",0,256,16,16,16);
	font2=createFont("resources/textures/bigfont.png",32,512,9.5,32,48);

    glCullFace(GL_BACK);
    glEnable(GL_CULL_FACE);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_BLEND);	// only used by glprintf
    glEnable(GL_DEPTH_TEST);

    struct timeval t, ta, t1, t2;	// fps stuff
    gettimeofday(&t1, NULL);
    int num_frames = 0;

    bool quit = false;

    mouse = getMouse();
    keys = getKeys();

    resetAliens();

    for (int n = 0; n < MAX_PLAYER_SHOTS; n++) {
        playerShots[n].alive = false;
    }


    initPointClouds("resources/shaders/particle.vert",
                    "resources/shaders/particle.frag",(float)getDisplayWidth()/24.0);


    for (int n = 0; n < MAX_ALIENS; n++) {
        aliens[n].explosion=createPointCloud(40);
        resetExposion(aliens[n].explosion); // sets initials positions
    }



    while (!quit) {		// the main loop

        doEvents();	// update mouse and key arrays

        // mask of 4 is right mouse
        if (keys[KEY_ESC])
            quit = true;

        glClearColor(0, .5, 1, 1);

        // render between two gettimeofday calls so
        // we can sleep long enough to roughly sync
        // to ~60fps but not on the pi!

        // TODO find something a tad more elegent

        long i;
        gettimeofday(&t, NULL);
        i = t.tv_sec * 1e6 + t.tv_usec;

//        render();
        float rad;		// radians rotation based on frame counter

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        frame++;
        rad = frame * (0.0175f * 2);

        kmMat4Identity(&model);
        kmMat4Translation(&model, playerPos.x, playerPos.y, playerPos.z);

        playerCroll +=
            (PIDcal(playerRoll, playerCroll, &playerPre_error, &playerIntegral)
             / 2);
        kmMat4RotationPitchYawRoll(&model, 0, 3.1416, playerCroll * 3);	//

        kmMat4Assign(&mvp, &vp);
        kmMat4Multiply(&mvp, &mvp, &model);

        kmMat4Assign(&mv, &view);
        kmMat4Multiply(&mv, &mv, &model);

        glBindTexture(GL_TEXTURE_2D, shipTex);
        drawObj(&shipObj, &mvp, &mv, lightDir, viewDir);

        glPrintf(50 + sinf(rad) * 16, 240 + cosf(rad) * 16,
                 font2,"frame=%i fps=%3.2f", frame, lfps);

        kmVec3 tmp;

        playerFireCount--;

        if (keys[KEY_LCTRL] && playerFireCount < 0) {

            struct playerShot_t *freeShot;
            freeShot = getFreeShot();
            if (freeShot != 0) {
                playerFireCount = 15;
                freeShot->alive = true;
                kmVec3Assign(&freeShot->pos, &playerPos);
            }
        }

        for (int n = 0; n < MAX_PLAYER_SHOTS; n++) {
            if (playerShots[n].alive) {
                playerShots[n].pos.z -= .08;
                if (playerShots[n].pos.z < -10)
                    playerShots[n].alive = false;

                kmMat4Identity(&model);
                kmMat4Translation(&model, playerShots[n].pos.x,
                                  playerShots[n].pos.y,
                                  playerShots[n].pos.z);
                kmMat4RotationPitchYawRoll(&model, rad * 4, 0,
                                           -rad * 4);

                kmMat4Assign(&mvp, &vp);
                kmMat4Multiply(&mvp, &mvp, &model);

                kmMat4Assign(&mv, &view);
                kmMat4Multiply(&mv, &mv, &model);

                glBindTexture(GL_TEXTURE_2D, shotTex);
                drawObj(&shotObj, &mvp, &mv, lightDir, viewDir);
            }
        }

        playerRoll = 0;
        if (keys[KEY_CURSL] && playerPos.x > -10) {
            playerPos.x -= 0.1;
            playerRoll = .2;
        }
        if (keys[KEY_CURSR] && playerPos.x < 10) {
            playerPos.x += 0.1;
            playerRoll = -.2;
        }
        pEye.x = playerPos.x * 1.25;

        pCenter.x = playerPos.x;
        pCenter.y = playerPos.y + 1;
        pCenter.z = playerPos.z;

        int deadAliens;

        deadAliens = 0;

        for (int n = 0; n < MAX_ALIENS; n++) {
            if (aliens[n].alive == true) {

                kmMat4Identity(&model);
                kmMat4Translation(&model, aliens[n].pos.x,
                                  aliens[n].pos.y, aliens[n].pos.z);
                kmMat4RotationPitchYawRoll(&model, -.4, 0, 0);

                kmMat4Assign(&mvp, &vp);
                kmMat4Multiply(&mvp, &mvp, &model);

                kmMat4Assign(&mv, &view);
                kmMat4Multiply(&mv, &mv, &model);

                glBindTexture(GL_TEXTURE_2D, alienTex);
                drawObj(&alienObj, &mvp, &mv, lightDir, viewDir);

                kmVec3 d;
                for (int i = 0; i < MAX_PLAYER_SHOTS; i++) {
                    kmVec3Subtract(&d, &aliens[n].pos,
                                   &playerShots[i].pos);
                    if (kmVec3Length(&d) < .7
                            && playerShots[i].alive) {
                        aliens[n].alive = false;
                        playerShots[i].alive = false;
                        aliens[n].exploding = true;
                        resetExposion(aliens[n].explosion);
                    }
                }
            } 

            if (aliens[n].alive != true && aliens[n].exploding != true) {
                    deadAliens++;
                
            }
        }

        if (deadAliens == MAX_ALIENS) {
            resetAliens();
        }

		// draw explosions after ALL aliens
        for (int n = 0; n < MAX_ALIENS; n++) {
			if (aliens[n].exploding==true) {
				kmMat4Identity(&model);
				kmMat4Translation(&model, aliens[n].pos.x,
								  aliens[n].pos.y, aliens[n].pos.z);

				kmMat4Assign(&mvp, &vp);
				kmMat4Multiply(&mvp, &mvp, &model);
				glBindTexture(GL_TEXTURE_2D, expTex);
				drawPointCloud(aliens[n].explosion, &mvp);
				aliens[n].explosion->tick=aliens[n].explosion->tick+0.05;
				if (aliens[n].explosion->tick>1.25) {
					aliens[n].exploding=false;                   	
				} else {
					// update the explosion
					
					for (int i=0; i<aliens[n].explosion->totalPoints; i++) {
				
						float t;
						t=aliens[n].explosion->tick;
						if (i>aliens[n].explosion->totalPoints/2) t=t/2.0;
						aliens[n].explosion->pos[i*3]=aliens[n].explosion->vel[i*3] * t;
						aliens[n].explosion->pos[i*3+1]=aliens[n].explosion->vel[i*3+1] * t;
						aliens[n].explosion->pos[i*3+2]=aliens[n].explosion->vel[i*3+2] * t;
				
					}
				}
			}
		}

        // move camera
        kmMat4LookAt(&view, &pEye, &pCenter, &pUp);

        kmMat4Assign(&vp, &projection);
        kmMat4Multiply(&vp, &vp, &view);

        kmVec3Subtract(&viewDir,&pEye,&pCenter);
        kmVec3Normalize(&viewDir,&viewDir);

        // dump values
        glPrintf(100, 280, font1,"eye    %3.2f %3.2f %3.2f ", pEye.x, pEye.y, pEye.z);
        glPrintf(100, 296, font1,"centre %3.2f %3.2f %3.2f ", pCenter.x, pCenter.y,
                 pCenter.z);
        glPrintf(100, 320, font1,"mouse %i,%i %i ", mouse[0], mouse[1], mouse[2]);
        glPrintf(100, 340, font1,"frame %i %i ", frame, frame % 20);



        swapBuffers();

        gettimeofday(&ta, NULL);
        long j = (ta.tv_sec * 1e6 + ta.tv_usec);

        i = j - i;
        if (i < 0)
            i = 1000000;	// pass through - slower that 60fps
        if (i < 16000)
            usleep(16000 - i);

        // every 10 frames average the time taken and store
        // fps value for later printing with glprintf
        if (++num_frames % 10 == 0) {
            gettimeofday(&t2, NULL);
            float dtf =
                t2.tv_sec - t1.tv_sec + (t2.tv_usec -
                                         t1.tv_usec) * 1e-6;
            lfps = num_frames / dtf;
            num_frames = 0;
            t1 = t2;
        }
    }

    closeContext();

    return 0;
}