bool ROSMain_features() {
	CoSLAM& coSLAM = MyApp::coSLAM;
	/////////////////////////1.GPU initilization/////////////////////////
	//initialization for CG;
	glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
	glutCreateWindow(" ");
	glutHideWindow();

	glewInit();

	V3D_GPU::Cg_ProgramBase::initializeCg();

	//////////////////////////2.read video information//////////////////
	try {
//		for(int c = 0; c < coSLAM.numCams; c++){
//			coSLAM.slam[c].videoReader = &MyApp::aviReader[c];
//		}

		coSLAM.init(false);
		MyApp::bInitSucc = true;
		logInfo("Loading video sequences.. OK!\n");
	} catch (SL_Exception& e) {
		logInfo(e.what());
#ifdef WIN32
		wxMessageBox(e.what());
#endif
		return 0;
	}

	//notify the GUI thread to create GUIs
	MyApp::broadcastCreateGUI();

	//wait for the accomplishment of creating GUIs
	MyApp::waitCreateGUI();

	for (int i = 0; i < coSLAM.numCams; i++){
		MyApp::videoWnd[i]->setSLAMData(i, &coSLAM);
		vector<float> reprojErrStatic, reprojErrDynamic;
		vector<int> frameNumber;
		MyApp::s_reprojErrDynamic.push_back(reprojErrStatic);
		MyApp::s_reprojErrStatic.push_back(reprojErrDynamic);
		MyApp::s_frameNumber.push_back(frameNumber);
	}


	MyApp::modelWnd1->setSLAMData(&coSLAM);
	MyApp::modelWnd2->setSLAMData(&coSLAM);
	MyApp::broadcastCreateGUI();

	//for measuring the timings
	Timings timingsPerStep;
	Timings timingsReadFrame;
	Timings timingsNewMapPonits;

	/* start the SLAM process*/
	try {
		coSLAM.readFrame();
		//copy the data to buffers for display
		updateDisplayData();
		//initialise the map points
		for (int i = 0; i < coSLAM.numCams; i++) {
			printf("slam[%d].m_camPos.size(): %d\n", i, coSLAM.slam[i].m_camPos.size());
		}
//		tic();
//		coSLAM.initMap();
//		toc();
		cout <<"debug\n";

//		redis->setPose(1, 2, 3.6);

		while (!MyApp::bExit){
			pthread_mutex_lock(&MyApp::_mutexImg);
			if (!coSLAM.grabReadFrame())
				pthread_cond_wait(&MyApp::_condImg, &MyApp::_mutexImg);
			pthread_mutex_unlock(&MyApp::_mutexImg);

//			//copy the data to buffers for display
			updateDisplayData();
			//printf("current frame: %d\n", coSLAM.curFrame);
			if (MyApp::bStartInit){
				MyApp::publishMapInit();
				printf("Start initializing map...\n");
				coSLAM.curFrame = 0;
				//initialise the map points
				if (coSLAM.initMap()){

					// Need this in real test
					coSLAM.calibGlobal2Cam();
//					return 0;

					for (int i = 0; i < coSLAM.numCams; i++)
						coSLAM.state[i] = SLAM_STATE_NORMAL;
					printf("Init map success!\n");
					break;
				}
				else{
					MyApp::bStartInit = false;
					MyApp::publishMapInit();
				}
			}
		}
		updateDisplayData();
//		coSLAM.pause();

		for (int i = 0; i < coSLAM.numCams; i++) {
			printf("slam[%d].m_camPos.size(): %d\n", i, coSLAM.slam[i].m_camPos.size());
			coSLAM.state[i] = SLAM_STATE_NORMAL;
		}

//		return 0;
//		coSLAM.pause();

		int endFrame = SLAMParam::nTotalFrame - SLAMParam::nSkipFrame
				- SLAMParam::nInitFrame - 10;
//		int endFrame = 500;

//		endFrame = 1500;

		int i = 0;
		// init estimation flag
		bool bEstPose[SLAM_MAX_NUM];
		for (int i = 0; i < SLAM_MAX_NUM; i++){
			bEstPose[i] = false;
		}

		vector<double> tmStepVec;


		vector<double> poseSent[SLAM_MAX_NUM];
//		vector<double> rosTime;

		while (!MyApp::bExit) {
//			while (MyApp::bStop) {/*stop*/
//			}

//			if (MyApp::_mergeable){
//				if (MyApp::_imgReady[0] && MyApp::_imgReady[1]){
//					coSLAM.grabReadFrame();
//					MyApp::_imgAvailableForMerge = true;
//				}
//				else
//					continue;
//			}

			i++;
			TimeMeasurer tmPerStep;
			tmPerStep.tic();


			if (!receiveFeatures){
				coSLAM.grabReadFrame();
				coSLAM.featureTracking();
			}
			else{
				coSLAM.featureReceiving();
				coSLAM.virtualReadFrame();
			}
			for (int i = 0; i < coSLAM.numCams; i++){
			cv::Mat cvImg(coSLAM.slam[i].m_img.rows, coSLAM.slam[i].m_img.cols, CV_8UC1,
								coSLAM.slam[i].m_img.data);
			MyApp::s_camFrames[i].push_back(cvImg.clone());
			CamPoseItem* cam = coSLAM.slam[i].m_camPos.current();
			double ts = cam->ts;
			MyApp::s_camFramesTS[i].push_back(ts);
			}

			if(!coSLAM.poseUpdate(bEstPose))
				break;
			//Use redis to send over the poses


//			for (int i = 0; i < coSLAM.numCams; i++){
//				double org[3];
////				getCamCenter(coSLAM.slam[i].m_camPos.current(), org);
//				coSLAM.transformCamPose2Global(coSLAM.slam[i].m_camPos.current(), org);
//
//				MyApp::redis[i]->setPose(org[0], org[1], org[2]);
//
//				double ts = coSLAM.slam[i].m_camPos.current()->ts;
//				poseSent[i].push_back(ts);
//				poseSent[i].push_back(org[0]);
//				poseSent[i].push_back(org[1]);
//				poseSent[i].push_back(org[2]);
//				rosTime.push_back(ts);
//			}
//			if (MyApp::bStartMove){
//				MyApp::redis_start->setCommand("go");
//				MyApp::bStartMove = false;
//			}

			//coSLAM.pause();
			coSLAM.cameraGrouping();
			//existing 3D to 2D points robust
			coSLAM.activeMapPointsRegister(Const::PIXEL_ERR_VAR);

			TimeMeasurer tmNewMapPoints;
			tmNewMapPoints.tic();

			if (receiveFeatures){
				coSLAM.genNewMapPoints_new();
				if (MyApp::_mergeable)
					MyApp::triggerClients();
			}
			else
			{
				bool merge = false;
				coSLAM.genNewMapPoints(merge);
			}
//
//			coSLAM.m_tmNewMapPoints = tmNewMapPoints.toc();
//			cout << "coSLAM.m_tmNewMapPoints" << coSLAM.m_tmNewMapPoints << endl;

			//point registration
			coSLAM.currentMapPointsRegister(Const::PIXEL_ERR_VAR,
					i % 50 == 0 ? true : false);

			coSLAM.storeDynamicPoints();

			updateDisplayData();
			redrawAllViews();

//			Sleep(50);

			if (i % 500 == 0) {
				//coSLAM.releaseFeatPts(coSLAM.curFrame - 500);
				coSLAM.releaseKeyPoseImgs(coSLAM.curFrame - 500);
				coSLAM.m_lastReleaseFrm = coSLAM.curFrame;
			}

			coSLAM.m_tmPerStep = tmPerStep.toc();
			tmStepVec.push_back(coSLAM.m_tmPerStep);

			//Send pose
			for (int i = 0; i < coSLAM.numCams; i++)
			{
				if (coSLAM.slam[i].m_camPos.size() > 0){

					double org[3], rpy[3];
					CamPoseItem* cam = coSLAM.slam[i].m_camPos.current();
					double ts = cam->ts;
					getCamCenter(cam, org);
					coSLAM.transformCamPose2Global(cam, org, rpy);

					double targetPos[3];
					targetPos[0] = targetPos[1] = targetPos[2] = 0;
					double theta = 0;
					if(coSLAM.dynObjPresent){
						coSLAM.transformTargetPos2Global(cam->currDynPos, targetPos);
						//printf("targetPos: %lf %lf %lf\n", targetPos[0], targetPos[1], targetPos[2]);
						coSLAM.slam[i].projectTargetToCam(cam, cam->currDynPos);
						theta = atan2(coSLAM.slam[i]._targetPosInCam[0], coSLAM.slam[i]._targetPosInCam[2]);
//							double H = targetPos[2] * 2;
//							double Z = coSLAM.slam[i]._targetPosInCam[2];
						MyApp::redis[i]->setPoseTarget(ts, 1, theta, org[0], org[1], rpy[2], targetPos[0], targetPos[1], 0.9);
//						MyApp::redis_dynObj->setDynObj(ts, targetPos[0], targetPos[1], 0.9);
//						printf("currDynPos: %lf %lf %lf\n", cam->currDynPos[0], cam->currDynPos[1], cam->currDynPos[2]);
					}
					else
						MyApp::redis[i]->setPoseTarget(ts, 0, theta, org[0], org[1], rpy[2], targetPos[0], targetPos[1], 0.9);

					MyApp::redis_dynObj->setDynObj(ts, 0.5, 2, 0.9);

					printf("targetPos: %lf %lf %lf\n", targetPos[0], targetPos[1], targetPos[2]);
					printf("org[2]: %lf %lf %lf\n", org[0], org[1], rpy[2]);
				}
			}
		}

		cout << " the result is saved at " << MyApp::timeStr << endl;
		coSLAM.exportResults(MyApp::timeStr);

		FILE* fid = fopen("/home/rui/coslamTime.txt","w");
		for (int i = 0; i < tmStepVec.size(); i++){
			fprintf(fid, "%lf\n", tmStepVec[i]);
		}
		fclose(fid);

//		FILE* fid = fopen("slam_timing.txt","w");
//		for (int i = 0; i < tmStepVec.size(); i++)
//			fprintf(fid, "%f\n", tmStepVec[i]);
//		fclose(fid);
//
//		fid = fopen("poseSent0.txt","w");
//		for (int i = 0; i < poseSent[0].size(); i = i + 4)
//			fprintf(fid, "%lf %lf %lf %lf\n", poseSent[0][i],
//					poseSent[0][i+1], poseSent[0][i+2], poseSent[0][i+3]);
//		fclose(fid);
//
//		fid = fopen("poseSent1.txt","w");
//		for (int i = 0; i < poseSent[1].size(); i = i + 4)
//			fprintf(fid, "%lf %lf %lf %lf\n", poseSent[1][i],
//					poseSent[1][i+1], poseSent[1][i+2], poseSent[1][i+3]);
//		fclose(fid);
//
//		FILE* fid = fopen("rosTime.txt","w");
//		for (int i = 0; i < rosTime.size(); i = i + coSLAM.numCams + 1){
//			for (int j = 0; j <= coSLAM.numCams; j++){
//				fprintf(fid, "%lf ", rosTime[i+j]);
//			}
//			fprintf(fid, "\n");
//		}
//		fclose(fid);

		logInfo("slam finished\n");
	} catch (SL_Exception& e) {
		logInfo(e.what());
	} catch (std::exception& e) {
#ifdef WIN32
		wxMessageBox(e.what());
#endif
		logInfo("%s\n", e.what());
		logInfo("slam failed!\n");
#ifdef WIN32
		wxMessageBox(e.what());
#endif
	}

	logInfo("\nslam stopped!\n");
	return 0;
}
Exemple #2
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen;
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL );
    if ( !screen ) {
        printf("Unable to set video mode: %s\n", SDL_GetError());
        return 1;
    }
    
    glClearColor( 0, 0, 0, 0 );
    glClear( GL_COLOR_BUFFER_BIT );

    // Fog

    glEnable(GL_FOG);
    glFogf(GL_FOG_START, 100);
    glFogf(GL_FOG_END, 2000);
    glFogi(GL_FOG_MODE, GL_LINEAR);
    GLfloat fogcolor[4] = { 0.9, 0.1, 0.35, 0 };
    glFogfv(GL_FOG_COLOR, fogcolor);

    // Create a texture

    GLuint texture;
    glGenTextures( 1, &texture );
    glBindTexture( GL_TEXTURE_2D, texture );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte textureData[16*16*4];
    for (int x = 0; x < 16; x++) {
      for (int y = 0; y < 16; y++) {
        *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8);
      }
    }
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, 
                  GL_RGBA, GL_UNSIGNED_BYTE, textureData );

    // Create a second texture

    GLuint texture2;
    glGenTextures( 1, &texture2 );
    glBindTexture( GL_TEXTURE_2D, texture2 );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte texture2Data[] = { 0xff,    0,    0, 0xff,
                                  0, 0xff,    0, 0xaa,
                                  0,    0, 0xff, 0x55,
                               0x80, 0x90, 0x70,    0 };
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0,
                  GL_RGBA, GL_UNSIGNED_BYTE, texture2Data );
    
    // BEGIN

#if USE_GLEW
    glewInit();
#endif

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048);
    glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048);
    glRotatef(-30, 1, 1, 1);
    //GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 };
    //glLoadMatrixf(pm);

    glMatrixMode(GL_MODELVIEW);
    GLfloat matrixData[] = { -1, 0, 0, 0,
                              0, 0,-1, 0,
                              0, 1, 0, 0,
                              0, 0, 0, 1 };
    glLoadMatrixf(matrixData);
    //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);

    glClear(GL_DEPTH_BUFFER_BIT);

    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glActiveTexture(GL_TEXTURE0);

    glEnableClientState(GL_VERTEX_ARRAY);

    GLuint arrayBuffer, elementBuffer;
    glGenBuffers(1, &arrayBuffer);
    glGenBuffers(1, &elementBuffer);

    GLubyte arrayData[] = {
/*
[0, 0,   0, 67] ==>  128 float
[0, 0, 128, 67] ==>  256 float
[0, 0,   0, 68] ==>  512 float
[0, 0, 128, 68] ==> 1024 float

[vertex x        ] [vertex y         ] [vertex z         ] [nr]                [texture u        ] [texture v        ] [lm u   ] [lm v   ] [color r,g,b,a    ] */
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,  11,   10,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  0
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,  23,   20,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  1
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  35,   30,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  2
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,  47,   40,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  3
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,  51,   50,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  4
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,  64,   60,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  5
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,  70,   70,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  6
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  89,   80,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  7
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,  94,   90,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  8
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  20,   10,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  9
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,  31,   20,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 10
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,  42,   30,   0,   0,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 11
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  53,   40,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 12
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,  64,   50,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 13
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,  75,   60,   0,   0,   0,   0, 128,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 14
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,  86,   70,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 15

  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128
    };
    assert(sizeof(arrayData) == 1408);
    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 };
    assert(sizeof(elementData) == 48);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);

    // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B
    glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound
    glTexCoordPointer(2, GL_FLOAT, 32, (void*)16);
    glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build
    glTexCoordPointer(2, GL_SHORT, 32, (void*)24);
    glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup
    glNormalPointer(GL_BYTE, 32, (void*)12);
    glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28);

    glBindTexture(GL_TEXTURE_2D, texture); // diffuse?
    glActiveTexture(GL_TEXTURE0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, texture2); // lightmap?
    glActiveTexture(GL_TEXTURE0);

    GLint ok;

    const char *vertexShader = "uniform vec4 texgenscroll;\n"
                               "void main(void)\n"
                               "{\n"
                               "    gl_Position = ftransform();\n"
                               "    gl_TexCoord[0].xy = gl_MultiTexCoord0.xy/10000.0 + (0.001*texgenscroll.xy) + gl_Normal.xy;\n" // added /100 here
                               "    gl_TexCoord[1].xy = gl_MultiTexCoord1.xy/100.0 * 3.051851e-05;\n"
                               "    gl_FogFragCoord = gl_Position.z;\n"
                               "}\n";
    const char *fragmentShader = "uniform vec4 colorparams;\n"
                                 "uniform sampler2D diffusemap, lightmap;\n"
                                 "void main(void)\n"
                                 "{\n"
                                 "    vec4 diffuse = texture2D(diffusemap, gl_TexCoord[0].xy);\n"
                                 "    vec4 lm = texture2D(lightmap, gl_TexCoord[1].xy);\n"
                                 "    diffuse *= colorparams;\n"
                                 "    vec4 color = diffuse * lm;\n"
                                 "    gl_FragColor.rgb = mix((gl_Fog.color).rgb, color.rgb, clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0));\n"
                                 //"    gl_FragColor.rgb = 0.0001 * color.rgb + ((gl_Fog.color).rgb * (1.0-clamp((gl_FogFragCoord)* 1.0/1000.0, 0.0, 1.0)));\n"
                                 "}\n";

    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, &vertexShader, NULL);
    glCompileShader(vs);
    glGetShaderiv(vs, GL_COMPILE_STATUS, &ok);
    assert(ok);

    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1, &fragmentShader, NULL);
    glCompileShader(fs);
    glGetShaderiv(fs, GL_COMPILE_STATUS, &ok);
    assert(ok);

    GLuint program = glCreateProgram();

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    assert(ok);

    glUseProgram(program);

    GLint lightmapLocation = glGetUniformLocation(program, "lightmap");
    assert(lightmapLocation >= 0);
    glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit?

    GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap");
    assert(diffusemapLocation >= 0);
    glUniform1i(diffusemapLocation, 0);

    GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll");
    assert(texgenscrollLocation >= 0);

    GLint colorparamsLocation = glGetUniformLocation(program, "colorparams");
    assert(colorparamsLocation >= 0);

    GLfloat texgenscrollData[] = { 0, 0, 0, 0 };
    glUniform4fv(texgenscrollLocation, 1, texgenscrollData);

    GLfloat colorparamsData[] = { 2, 2, 2, 1 };
    glUniform4fv(colorparamsLocation, 1, colorparamsData);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)12);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*) 0);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)24);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)36);

    // END

    SDL_GL_SwapBuffers();

#if !EMSCRIPTEN
    SDL_Delay(1500);
#endif

    SDL_Quit();
    
    return 0;
}
Exemple #3
0
int main( int argc, char **argv )
{
	// Parse the arguments
	if (argc < 3) {
		printf("Missing arguments ... use:\n");
		printf("./raycast [-u | -d] step_max <options>\n");
		return -1;
	}


	step_max = atoi(argv[2]); // maximum level of recursions

	// Optional arguments
	for(int i = 3; i < argc; i++)
	{
		if (strcmp(argv[i], "+s") == 0)	shadow_on = 1;
		if (strcmp(argv[i], "+p") == 0)	antialias_on = 1;
		if (strcmp(argv[i], "+r") == 0)	refract_on = 1;
		if (strcmp(argv[i], "+c") == 0)	check_on = 1;
		if (strcmp(argv[i], "+l") == 0)	reflect_on = 1;
		if (strcmp(argv[i], "+n") == 0)	save_on = 1;
		if (strcmp(argv[i], "+f") == 0)	stochdiff_on = 1;
	}

	if (strcmp(argv[1], "-u") == 0) {  // user defined scene
		set_up_user_scene();
	}else if (strcmp(argv[1], "-c") == 0) {  // user defined scene
		set_up_chess_scene();
	} else { // default scene
		set_up_default_scene();
	}

	//
	// ray trace the scene now
	//
	// we have used so many global variables and this function is
	// happy to carry no parameters
	//
	printf("Rendering scene using my fantastic ray tracer ...\n");
	ray_trace();

	if (save_on) {
		save_image();
		return 0;
	}
	// we want to make sure that intensity values are normalized
	//histogram_normalization();

	// Show the result in glut via texture mapping
	glutInit( &argc, argv );
	glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
	glutInitWindowSize( WIN_WIDTH, WIN_HEIGHT );
	glutCreateWindow( "Ray tracing" );
	glewInit();
	init();

	glutDisplayFunc( display );
	glutKeyboardFunc( keyboard );
	glutIdleFunc(idle);
	glutMainLoop();
	return 0;
}
	RenderingContext::RenderingContext(CML::CMWindow *window)
	{

		PIXELFORMATDESCRIPTOR pfd =
		{
			sizeof(PIXELFORMATDESCRIPTOR),
			1,
			PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,    //Flags
			PFD_TYPE_RGBA,            //The kind of framebuffer. RGBA or palette.
			24,                        //Colordepth of the framebuffer.		
			24,                        //Number of bits for the depthbuffer
			8,                        //Number of bits for the stencilbuffer
			0,                        //Number of Aux buffers in the framebuffer.
			PFD_MAIN_PLANE
		};
		WORD  nSize = sizeof(PIXELFORMATDESCRIPTOR);
		WORD  nVersion  = 1;
		DWORD dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
		pfd.iPixelType = PFD_TYPE_RGBA;
		pfd.cColorBits  = 24;
		pfd.cRedBits  = 0;
		pfd.cRedShift  = 0;
		pfd.cGreenBits  = 0;
		pfd.cGreenShift  = 0;
		pfd.cBlueBits  = 0;
		pfd.cBlueShift  = 0;
		pfd.cAlphaBits  = 0;
		pfd.cAlphaShift  = 0;
		pfd.cAccumBits  = 0;
		pfd.cAccumRedBits  = 0;
		pfd.cAccumGreenBits  = 0;
		pfd.cAccumBlueBits  = 0;
		pfd.cAccumAlphaBits  = 0;
		pfd.cDepthBits  = 24;
		pfd.cStencilBits  = 8;
		pfd.cAuxBuffers  = 0;
		pfd.iLayerType  = 0;
		pfd.bReserved  = 0;
		DWORD dwLayerMask  = NULL;
		DWORD dwVisibleMask  = NULL;
		DWORD dwDamageMask  = NULL;


		_window = window;
		HDC ourWindowHandleToDeviceContext = GetDC(window->CMWindowHandle());// 
		g_HDC = ourWindowHandleToDeviceContext;
		int  letWindowsChooseThisPixelFormat;
		letWindowsChooseThisPixelFormat = ChoosePixelFormat(ourWindowHandleToDeviceContext, &pfd);
		SetPixelFormat(ourWindowHandleToDeviceContext, letWindowsChooseThisPixelFormat, &pfd);

		renderingContext = wglCreateContext(ourWindowHandleToDeviceContext);
		wglMakeCurrent(ourWindowHandleToDeviceContext, renderingContext);


		glewInit();


		_program = glCreateProgram();

		createVertexShader();
		createFragmentShader();

		
	}
Exemple #5
0
void InitOpenGL(void){
  int type;
  int err;

  PRINTF("%s",_("Initializing OpenGL\n"));
  
  type = GLUT_RGB|GLUT_DEPTH;
  if(buffertype==GLUT_DOUBLE){
    type |= GLUT_DOUBLE;
  }
  else{
    type |= GLUT_SINGLE;
  }

//  glutInitDisplayMode(GLUT_STEREO);
  if(stereoactive==1){
    if(glutGet(GLUT_DISPLAY_MODE_POSSIBLE)==1){
      videoSTEREO=1;
      type |= GLUT_STEREO;
    }
    else{
      videoSTEREO=0;
      fprintf(stderr,"*** Error: video hardware does not support stereo\n");
    }
  }

#ifdef _DEBUG
  PRINTF("%s",_("   Initializing Glut display mode - "));
#endif
  glutInitDisplayMode(type);
#ifdef _DEBUG
  PRINTF("%s\n",_("initialized"));
#endif

  CheckMemory;
#ifdef _DEBUG
  PRINTF("%s\n",_("   creating window"));
#endif
  mainwindow_id=glutCreateWindow("");
#ifdef _DEBUG
  PRINTF("%s\n",_("   window created"));
#endif

#ifdef _DEBUG
  PRINTF("%s",_("   Initializing callbacks - "));
#endif
  glutSpecialUpFunc(specialkeyboard_up_CB);
  glutKeyboardUpFunc(keyboard_up_CB);
  glutKeyboardFunc(keyboard_CB);
  glutMouseFunc(mouse_CB);
  glutSpecialFunc(specialkeyboard_CB);
  glutMotionFunc(motion_CB);
  glutReshapeFunc(Reshape_CB);
  glutDisplayFunc(Display_CB);
  glutVisibilityFunc(NULL);
  glutMenuStatusFunc(MenuStatus_CB);
#ifdef _DEBUG
  PRINTF("%s\n",_("initialized"));
#endif

  opengl_version = get_opengl_version(opengl_version_label);

  err=0;  
 #ifdef pp_GPU
  err=glewInit();
  if(err==GLEW_OK){
    err=0;
  }
  else{
    PRINTF("   GLEW initialization failed\n");
    err=1;
  }
  if(err==0){
    if(disable_gpu==1){
      err=1;
    }
    else{
      err=init_shaders();
    }
#ifdef _DEBUG
    if(err==0){
      PRINTF("%s\n",_("   GPU shader initialization succeeded"));
    }
#endif
    if(err!=0){
      PRINTF("%s\n",_("   GPU shader initialization failed"));
    }
  }
#endif
#ifdef pp_CULL
  if(err==0){
    err=init_cull_exts();
#ifdef _DEBUG
    if(err==0){
      PRINTF("%s\n",_("   Culling extension initialization succeeded"));
    }
#endif
    if(err!=0){
      PRINTF("%s\n",_("   Culling extension initialization failed"));
    }
  }
#endif

  light_position0[0]=1.0f;
  light_position0[1]=1.0f;
  light_position0[2]=4.0f; 
  light_position0[3]=0.f;

  light_position1[0]=-1.0f;
  light_position1[1]=1.0f;
  light_position1[2]=4.0f;
  light_position1[3]=0.f;

  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  updateLights(light_position0,light_position1);

  {
    glGetIntegerv(GL_RED_BITS,&nredbits);    
    glGetIntegerv(GL_GREEN_BITS,&ngreenbits);
    glGetIntegerv(GL_BLUE_BITS,&nbluebits);

    nredshift = 8 - nredbits;
    if(nredshift<0)nredshift=0;
    ngreenshift = 8 - ngreenbits;
    if(ngreenshift<0)ngreenshift=0;
    nblueshift=8-nbluebits;
    if(nblueshift<0)nblueshift=0;
  }
  opengldefined=1;
  PRINTF("%s",_("OpenGL initialization completed\n\n"));
}
Exemple #6
0
int
main(int argc, char *argv[])
{
    int x,y,width, height;
    SDL_Window *win;
    SDL_GLContext glContext;
    NVGcontext *vg = NULL;

    int running = 1;
    unsigned int started;
    unsigned int dt;
    struct zr_user_font font;
    struct file_browser browser;
    const char *font_path;
    int icon_sheet;

    font_path = argv[1];
    if (argc < 2)
        die("missing argument!: <font> <icons>");

    /* SDL */
    SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_EVENTS);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    win = SDL_CreateWindow("File Explorer",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL|SDL_WINDOW_SHOWN);
    glContext = SDL_GL_CreateContext(win);
    SDL_GetWindowSize(win, &width, &height);
    SDL_GetWindowPosition(win, &x, &y);

    /* OpenGL */
    glewExperimental = 1;
    if (glewInit() != GLEW_OK)
        die("[GLEW] failed setup\n");
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

    /* nanovg */
    vg = nvgCreateGLES2(NVG_ANTIALIAS|NVG_DEBUG);
    if (!vg) die("[NVG]: failed to init\n");
    nvgCreateFont(vg, "fixed", font_path);
    nvgFontFace(vg, "fixed");
    nvgFontSize(vg, 14);
    nvgTextAlign(vg, NVG_ALIGN_LEFT|NVG_ALIGN_MIDDLE);

    /* GUI */
    memset(&browser, 0, sizeof browser);
    font.userdata.ptr = vg;
    nvgTextMetrics(vg, NULL, NULL, &font.height);
    font.width = font_get_width;
    file_browser_init(&browser, vg, &font, width, height);

    while (running) {
        /* Input */
        SDL_Event evt;
        started = SDL_GetTicks();
        zr_input_begin(&browser.input);
        while (SDL_PollEvent(&evt)) {
            if (evt.type == SDL_WINDOWEVENT) resize(&evt);
            else if (evt.type == SDL_QUIT) goto cleanup;
            else if (evt.type == SDL_KEYUP) key(&browser.input, &evt, zr_false);
            else if (evt.type == SDL_KEYDOWN) key(&browser.input, &evt, zr_true);
            else if (evt.type == SDL_MOUSEBUTTONDOWN) btn(&browser.input, &evt, zr_true);
            else if (evt.type == SDL_MOUSEBUTTONUP) btn(&browser.input, &evt, zr_false);
            else if (evt.type == SDL_MOUSEMOTION) motion(&browser.input, &evt);
            else if (evt.type == SDL_TEXTINPUT) text(&browser.input, &evt);
            else if (evt.type == SDL_MOUSEWHEEL) zr_input_scroll(&browser.input, evt.wheel.y);
        }
        zr_input_end(&browser.input);

        SDL_GetWindowSize(win, &width, &height);
        running = file_browser_run(&browser, width, height);

        /* Draw */
        glClearColor(0.4f, 0.4f, 0.4f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        draw(vg, &browser.queue, width, height);
        SDL_GL_SwapWindow(win);
    }

cleanup:
    /* Cleanup */
    free(browser.memory);
    nvgDeleteGLES2(vg);
    SDL_GL_DeleteContext(glContext);
    SDL_DestroyWindow(win);
    SDL_Quit();
    return 0;
}
Exemple #7
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	#ifdef _WINDOWS
		glewInit();
	#endif




	SDL_Event event;
	bool done = false;

	glViewport(0, 0, 640, 360);
	ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
	GLuint bluePaddleTexture = LoadTexture("blueRectangle.png");
	GLuint greenPaddleTexture = LoadTexture("greenRectangle.png");
	GLuint emojiTexture = LoadTexture("emoji3.png");
	GLuint greenBallTexture = LoadTexture("greenCircle2.png");
	Ball greenBall(0.25, 0.25);
	Paddle greenPaddle(-3.35,0.5);
	Paddle bluePaddle(3.35,0.5);
	Matrix projectionMatrix;
	Matrix modelMatrixbluePaddle;
	Matrix modelMatrixgreenPaddle;
	Matrix modelMatrixgreenBall;
	Matrix viewMatrix;

	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);
	Mix_Chunk *someSound;
	someSound = Mix_LoadWAV("ballSound.wav");
	Mix_Music *music;
	music = Mix_LoadMUS("music.mp3");

	
	bool ballDown = true;
	bool ballLeft = true;
	projectionMatrix.setOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f);
	glUseProgram(program.programID);

	float lastFrameTicks = 0.0f;

	Mix_PlayMusic(music, -1);
	
	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;

		const Uint8 *keys = SDL_GetKeyboardState(NULL);

		float vertices2[] = { 0, 0, 0.25, 0, 0.25, 0.25, 0, 0, 0.25, 0.25, 0, 0.25 };
		//GreenPaddle
		float vertices1[] = { -3.35f, -.5f, -3.2f, -.5f, -3.2f, .5f, -3.35f, -.5f, -3.2f, .5f, -3.35f, .5f };

		float shiftX = 0;
		float shiftY = 0;
		shiftX += 0.5f * elapsed;
		shiftY += 1.0f * elapsed;

		if (greenPaddle.y < 1.5){
			if (keys[SDL_SCANCODE_W]){
				modelMatrixgreenPaddle.Translate(0, shiftY, 0);
				greenPaddle.y += shiftY;
			}
		}
		if (greenPaddle.y > -1.5){
			if (keys[SDL_SCANCODE_S])
			{
				modelMatrixgreenPaddle.Translate(0, -shiftY, 0);
				greenPaddle.y -= shiftY;
			}
		}
		if (bluePaddle.y < 1.5){
			if (keys[SDL_SCANCODE_UP]){
				modelMatrixbluePaddle.Translate(0, shiftY, 0);
				bluePaddle.y += shiftY;
			}
		}
		if (bluePaddle.y > -1.5) {
			if (keys[SDL_SCANCODE_DOWN])
			{
				modelMatrixbluePaddle.Translate(0, -shiftY, 0);
				bluePaddle.y -= shiftY;
			}
		}
		if (keys[SDL_SCANCODE_R])
			modelMatrixgreenBall.setPosition(0.5, 0.5, 0);
		if (greenBall.y >= 1.5)
		{
			ballDown = true;
			Mix_PlayChannel(-1, someSound, 0);
		}
		if (greenBall.y <= -1.5)
		{
			ballDown = false;
			Mix_PlayChannel(-1, someSound, 0);
		}
		if (ballDown)
		{
			modelMatrixgreenBall.Translate(0, -.35*shiftY, 0);
			greenBall.y -= .35* shiftY;

		}
		else
		{
			modelMatrixgreenBall.Translate(0, .35*shiftY, 0);
			greenBall.y += .35*shiftY;
		}

		if (ballLeft && greenBall.x > -3.55)
		{
			modelMatrixgreenBall.Translate(-shiftX, 0, 0);
			greenBall.x -= shiftX;

		}
		
		
		if (greenBall.y > (greenPaddle.y - 1) && greenBall.y <= greenPaddle.y +.5 && greenBall.x <= -3.2)
		{
			Mix_PlayChannel(-1, someSound, 0);
			ballLeft = false;
		}
		if (!ballLeft && greenBall.x < 3.2)
		{
			modelMatrixgreenBall.Translate(shiftX, 0, 0);
			greenBall.x += shiftX;
		}
		if (greenBall.y >(bluePaddle.y - 1) && greenBall.y <= bluePaddle.y +.5  && greenBall.x >= 2.97)
		{
			Mix_PlayChannel(-1, someSound, 0);
			ballLeft = true;
		}
		if (greenBall.x >= 3.3 || greenBall.x <= -3.3)
		{
			modelMatrixgreenBall.setPosition(0, 0, 0);
			greenBall.x = 0;
			greenBall.y = 0;

		}
		

		glClear(GL_COLOR_BUFFER_BIT);

		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glColor3f(0.0f, 0.0f, 0.0f);

		
		
		//GREEN PADDLE
		program.setModelMatrix(modelMatrixgreenPaddle);

		glBindTexture(GL_TEXTURE_2D, greenPaddleTexture);

		
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices1);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords1[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords1);
		glEnableVertexAttribArray(program.texCoordAttribute);


		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);
		
		glBindTexture(GL_TEXTURE_2D, bluePaddleTexture);


		//BLUE PADDLE
		program.setModelMatrix(modelMatrixbluePaddle);

		float vertices3[] = { 3.35f, -.5f, 3.2f, -.5f, 3.2f, .5f, 3.35f, -.5f, 3.2f, .5f, 3.35f, .5f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices3);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords3[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords3);
		glEnableVertexAttribArray(program.texCoordAttribute);


		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		
		//GREEN BALL
		
		program.setModelMatrix(modelMatrixgreenBall);

		glBindTexture(GL_TEXTURE_2D, greenBallTexture);


		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords2[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords2);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);



		SDL_GL_SwapWindow(displayWindow);
	}

	SDL_Quit();
	return 0;
}
int main(int argc, char *argv[])
{
	//start context
	if (!glfwInit())
	{
		fprintf(stderr, "Error, could not start GLFW3\n");
		return 1;
	}
	else
	{
		fprintf(stderr, "GLFW initialized properly.");
	}

	//Forward compatibility from version 3.2.
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_SAMPLES, 4); //Anti aliasing (4 passes)
	
	//start logs
	Logger::restartLog(GL_LOG_FILE);
	glfwSetErrorCallback(glfwErrorCallback);

	GLFWmonitor* monitor = glfwGetPrimaryMonitor();
	const GLFWvidmode* mode = glfwGetVideoMode(monitor);

	//init window with primary monitor resolution
	//Set these modes for a fullscreen window and don't for classic fullscreen:
	/*glfwWindowHint(GLFW_RED_BITS, mode->redBits);
	glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
	glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
	glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);*/
	//------------------------------------------------

	//GLFWwindow * window = glfwCreateWindow(mode->width, mode->height, "Tutorial 1: Draw a triangle", monitor, NULL); //Fullscreen
	GLFWwindow * window = glfwCreateWindow(800, 600, "Tutorial 1: Draw a triangle", NULL, NULL); //Not Fullscreen

	//if window initialisation failed
	if (!window)
	{
		fprintf(stderr, "Could not open window with GLFW3\n");
		glfwTerminate();
		return 1;
	}

	glfwMakeContextCurrent(window);
	glfwSetWindowSizeCallback(window, glfwWindowSizeCallback);

	//start glew extension handler;
	glewExperimental = GL_TRUE;
	glewInit();

	//get version info
	const GLubyte * renderer = glGetString(GL_RENDERER);
	const GLubyte * version = glGetString(GL_VERSION);

	//Log informations
	Logger::printToLog(GL_LOG_FILE, "Starting GLFW: %s \n", glfwGetVersionString());
	logGlParams();

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);

	//draw triangle
	initTriangles();

	Shader vertex = Shader("vertex.vert", GL_VERTEX_SHADER);
	Shader frag_1 = Shader("frag1.frag", GL_FRAGMENT_SHADER);
	Shader frag_2 = Shader("frag2.frag", GL_FRAGMENT_SHADER);

	Shader shaders_1[2] = { vertex, frag_1 };
	Shader shaders_2[2] = { vertex, frag_2 };

	ShaderProgram shader_programme_1 = ShaderProgram(shaders_1, VERT_FRAG);
	ShaderProgram shader_programme_2 = ShaderProgram(shaders_2, VERT_FRAG);

	while (!glfwWindowShouldClose(window)) {
		updateFpsCounter(window);

		// wipe the drawing surface clear 
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport(0, 0, g_gl_width, g_gl_height);

		glClearColor(0.1f, 0.1f, 0.1f, 0.0f);

		glUseProgram(shader_programme_1.get_program());
		glBindVertexArray(vao_1);

		// draw points 0-5 from the currently bound VAO with current in-use shader 
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glUseProgram(shader_programme_2.get_program());
		glBindVertexArray(vao_2);

		// draw points 0-5 from the currently bound VAO with current in-use shader 
		glDrawArrays(GL_TRIANGLES, 0, 3);

		// update other events like input handling 
		glfwPollEvents();
		// put the stuff we've been drawing onto the display 
		glfwSwapBuffers(window);

		if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) 
		{
			glfwSetWindowShouldClose(window, 1);
		}
	}

	//close gl context and other glfw resources
	glfwTerminate();

	return 0;
}
Exemple #9
0
//============================================================
// <T>配置处理。</T>
//
// @return 处理结果
//============================================================
TResult FPoRenderDevice::Setup(){
   // 父配置处理
   TResult result = FRenderDevice::Setup();
   //............................................................
#ifdef _MO_WINDOWS
   // 初始化库
   GLenum initResult = glewInit();
   if(GLEW_OK != initResult){
      const GLubyte* pReason = glewGetErrorString(initResult);
      MO_FATAL("Initialize opengl glew library failure. (reason=%s)", pReason);
   }
   // 检查版本
   if(glewIsSupported("GL_VERSION_2_0")){
      MO_INFO("Initialize OpenGL library ready for OpenGL 2.0.");
   }else{
      MO_FATAL("Initialize OpenGL library not supported.");
   }
#endif // _MO_WINDOWS
   //............................................................
   // 获得描述
   const GLubyte* byteGlVersion = glGetString(GL_VERSION);  
   const GLubyte* byteGlVendor = glGetString(GL_VENDOR);  
   const GLubyte* byteGlRenderer = glGetString(GL_RENDERER);  
   const GLubyte* byteSLVersion = glGetString(GL_SHADING_LANGUAGE_VERSION);  
   const GLubyte* byteExtensions = glGetString(GL_EXTENSIONS);  
   MO_INFO("OpenGL setup. (Version    : %s)", byteGlVersion);
   MO_INFO("OpenGL setup. (Vendor     : %s)", byteGlVendor);
   MO_INFO("OpenGL setup. (Render     : %s)", byteGlRenderer);
   MO_INFO("OpenGL setup. (GLSL       : %s)", byteSLVersion);
   MO_INFO("OpenGL setup. (Extensions : %s)", byteExtensions);
   // 获得限制
   TInt vertexConstLimit = GlRenderGetInteger(GL_MAX_VERTEX_UNIFORM_VECTORS);
   TInt fragmentConstLimit = GlRenderGetInteger(GL_MAX_FRAGMENT_UNIFORM_VECTORS);
#ifndef _MO_ANDROID
   _pCapability->SetRenderTargetLimit(GlRenderGetInteger(GL_MAX_DRAW_BUFFERS));
   //_pCapability->SetVertexConstLimit(GlRenderGetInteger(GL_MAX_VERTEX_UNIFORM_COMPONENTS) / 4);
   //_pCapability->SetFragmentConstLimit(GlRenderGetInteger(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS) / 4);
#else
   //vertexConstLimit = MO_LIB_MIN(vertexConstLimit, 256);
   //fragmentConstLimit = MO_LIB_MIN(fragmentConstLimit, 256);
#endif // _MO_ANDROID
   _pCapability->SetVertexConstLimit(vertexConstLimit);
   _pCapability->SetVertexAttributeLimit(GlRenderGetInteger(GL_MAX_VERTEX_ATTRIBS));
   _pCapability->SetFragmentConstLimit(fragmentConstLimit);
   _pCapability->SetVaryingLimit(GlRenderGetInteger(GL_MAX_VARYING_VECTORS));
   _pCapability->SetSamplerLimit(GlRenderGetInteger(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS));
   _pCapability->SetSamplerSizeLimit(GlRenderGetInteger(GL_MAX_TEXTURE_SIZE));
   _pCapability->Track();
   //MO_INFO("GL_MAX_VARYING_FLOATS=%d", GlRenderGetInteger(GL_MAX_VARYING_FLOATS));
   MO_INFO("GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS=%d", GlRenderGetInteger(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS));
   MO_INFO("GL_MAX_TEXTURE_IMAGE_UNITS=%d", GlRenderGetInteger(GL_MAX_TEXTURE_IMAGE_UNITS));
   //MO_INFO("GL_MAX_DRAW_BUFFERS=%d", GlRenderGetInteger(GL_MAX_DRAW_BUFFERS));
   //MO_INFO("GL_MAX_TEXTURE_UNITS=%d", GlRenderGetInteger(GL_MAX_TEXTURE_UNITS));
   //............................................................
   // 设置数据
   TInt vertexConstTotal = sizeof(SFloat4) * _pCapability->VertexConstLimit();
   _pVertexConsts->ForceLength(vertexConstTotal);
   RMemory::Clear(_pVertexConsts->Memory(), _pVertexConsts->Length());
   TInt fragmentConstTotal = sizeof(SFloat4) * _pCapability->FragmentConstLimit();
   _pFragmentConsts->ForceLength(fragmentConstTotal);
   RMemory::Clear(_pFragmentConsts->Memory(), _pFragmentConsts->Length());
   //............................................................
   // 设置脚本处理器
   _shaderTransformer = FPoRenderShaderTransformer::InstanceCreate();
   _shaderOptimizer = FPoRenderShaderOptimizer::InstanceCreate();
   //............................................................
   // GL_CCW表示逆时针为背面
   // glFrontFace(GL_CCW);
   return ESuccess;
}
Exemple #10
0
void SplatRenderer::init(QGLWidget *qglw)
{
  mIsSupported = true;
  if(qglw)
    qglw->makeCurrent();
  glewInit();

  const char* rs = (const char*)glGetString(GL_RENDERER);
  QString rendererString("");
  if(rs)
    rendererString = QString(rs);
  mWorkaroundATI = rendererString.startsWith("ATI") || rendererString.startsWith("AMD");
  // FIXME: maybe some recent HW correctly supports floating point blending...
  mBuggedAtiBlending = rendererString.startsWith("ATI") || rendererString.startsWith("AMD");

  if (mWorkaroundATI && mDummyTexId==0)
  {
    glActiveTexture(GL_TEXTURE0);
    glGenTextures(1,&mDummyTexId);
    glBindTexture(GL_TEXTURE_2D, mDummyTexId);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 4, 4, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0);
  }

  // let's check the GPU capabilities
  mSupportedMask = DEPTH_CORRECTION_BIT | BACKFACE_SHADING_BIT;
  if (!QGLFramebufferObject::hasOpenGLFramebufferObjects ())
  {
    std::cout << "SplatRenderer: error OpenGL frame buffer objects are not supported. (please, try to update your drivers)\n";
    mIsSupported = false;
    return;
  }
  if (GLEW_ARB_texture_float)
    mSupportedMask |= FLOAT_BUFFER_BIT;
  else
    std::cout << "SplatRenderer: warning floating point textures are not supported.\n";

  if (GLEW_ARB_draw_buffers && (!mBuggedAtiBlending))
    mSupportedMask |= DEFERRED_SHADING_BIT;
  else
    std::cout << "SplatRenderer: warning deferred shading is not supported.\n";

  if (GLEW_ARB_shadow)
    mSupportedMask |= OUTPUT_DEPTH_BIT;
  else
    std::cerr << "SplatRenderer: warning copy of the depth buffer is not supported.\n";

  mFlags = mFlags & mSupportedMask;

  // load shader source
  mShaderSrcs[0] = loadSource("VisibilityVP","Raycasting.glsl");
  mShaderSrcs[1] = loadSource("VisibilityFP","Raycasting.glsl");
  mShaderSrcs[2] = loadSource("AttributeVP","Raycasting.glsl");
  mShaderSrcs[3] = loadSource("AttributeFP","Raycasting.glsl");
  mShaderSrcs[4] = "";
  mShaderSrcs[5] = loadSource("Finalization","Finalization.glsl");

  mCurrentPass = 2;
  mBindedPass = -1;
  mIsInitialized = true;
  GL_TEST_ERR
}
Exemple #11
0
int main(int argc, char **argv) {
    srand(time(NULL));
    rand();
    if (argc == 2 || argc == 3) {
        char *hostname = argv[1];
        int port = DEFAULT_PORT;
        if (argc == 3) {
            port = atoi(argv[2]);
        }
        db_disable();
        client_enable();
        client_connect(hostname, port);
        client_start();
    }
    if (!glfwInit()) {
        return -1;
    }
    create_window();
    if (!window) {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(VSYNC);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetKeyCallback(window, on_key);
    glfwSetMouseButtonCallback(window, on_mouse_button);
    glfwSetScrollCallback(window, on_scroll);

    #ifndef __APPLE__
        if (glewInit() != GLEW_OK) {
            return -1;
        }
    #endif

    if (db_init()) {
        return -1;
    }

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LINE_SMOOTH);
    glLogicOp(GL_INVERT);
    glClearColor(0.53, 0.81, 0.92, 1.00);

    GLuint texture;
    glGenTextures(1, &texture);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    load_png_texture("texture.png");

    GLuint block_program = load_program(
        "shaders/block_vertex.glsl", "shaders/block_fragment.glsl");
    GLuint matrix_loc = glGetUniformLocation(block_program, "matrix");
    GLuint camera_loc = glGetUniformLocation(block_program, "camera");
    GLuint sampler_loc = glGetUniformLocation(block_program, "sampler");
    GLuint timer_loc = glGetUniformLocation(block_program, "timer");
    GLuint position_loc = glGetAttribLocation(block_program, "position");
    GLuint normal_loc = glGetAttribLocation(block_program, "normal");
    GLuint uv_loc = glGetAttribLocation(block_program, "uv");

    GLuint line_program = load_program(
        "shaders/line_vertex.glsl", "shaders/line_fragment.glsl");
    GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix");
    GLuint line_position_loc = glGetAttribLocation(line_program, "position");

    GLuint item_position_buffer = 0;
    GLuint item_normal_buffer = 0;
    GLuint item_uv_buffer = 0;
    int previous_block_type = 0;

    Chunk chunks[MAX_CHUNKS];
    int chunk_count = 0;

    Player players[MAX_PLAYERS];
    int player_count = 0;

    FPS fps = {0, 0};
    float matrix[16];
    float x = (rand_double() - 0.5) * 10000;
    float z = (rand_double() - 0.5) * 10000;
    float y = 0;
    float dy = 0;
    float rx = 0;
    float ry = 0;
    double px = 0;
    double py = 0;

    int loaded = db_load_state(&x, &y, &z, &rx, &ry);
    ensure_chunks(chunks, &chunk_count, x, y, z, 1);
    if (!loaded) {
        y = highest_block(chunks, chunk_count, x, z) + 2;
    }

    glfwGetCursorPos(window, &px, &py);
    double previous = glfwGetTime();
    while (!glfwWindowShouldClose(window)) {
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);

        update_fps(&fps, SHOW_FPS);
        double now = glfwGetTime();
        double dt = MIN(now - previous, 0.2);
        previous = now;

        if (exclusive && (px || py)) {
            double mx, my;
            glfwGetCursorPos(window, &mx, &my);
            float m = 0.0025;
            rx += (mx - px) * m;
            ry -= (my - py) * m;
            if (rx < 0) {
                rx += RADIANS(360);
            }
            if (rx >= RADIANS(360)){
                rx -= RADIANS(360);
            }
            ry = MAX(ry, -RADIANS(90));
            ry = MIN(ry, RADIANS(90));
            px = mx;
            py = my;
        }
        else {
            glfwGetCursorPos(window, &px, &py);
        }

        int sz = 0;
        int sx = 0;
        ortho = glfwGetKey(window, 'F');
        fov = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) ? 15.0 : 65.0;
        if (glfwGetKey(window, 'Q')) break;
        if (glfwGetKey(window, 'W')) sz--;
        if (glfwGetKey(window, 'S')) sz++;
        if (glfwGetKey(window, 'A')) sx--;
        if (glfwGetKey(window, 'D')) sx++;
        float m = dt * 1.0;
        if (glfwGetKey(window, GLFW_KEY_LEFT)) rx -= m;
        if (glfwGetKey(window, GLFW_KEY_RIGHT)) rx += m;
        if (glfwGetKey(window, GLFW_KEY_UP)) ry += m;
        if (glfwGetKey(window, GLFW_KEY_DOWN)) ry -= m;
        float vx, vy, vz;
        get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz);
        if (glfwGetKey(window, GLFW_KEY_SPACE)) {
            if (flying) {
                vy = 1;
            }
            else if (dy == 0) {
                dy = 8;
            }
        }
        if (glfwGetKey(window, 'Z')) {
            vx = -1; vy = 0; vz = 0;
        }
        if (glfwGetKey(window, 'X')) {
            vx = 1; vy = 0; vz = 0;
        }
        if (glfwGetKey(window, 'C')) {
            vx = 0; vy = -1; vz = 0;
        }
        if (glfwGetKey(window, 'V')) {
            vx = 0; vy = 1; vz = 0;
        }
        if (glfwGetKey(window, 'B')) {
            vx = 0; vy = 0; vz = -1;
        }
        if (glfwGetKey(window, 'N')) {
            vx = 0; vy = 0; vz = 1;
        }
        float speed = flying ? 20 : 5;
        int step = 8;
        float ut = dt / step;
        vx = vx * ut * speed;
        vy = vy * ut * speed;
        vz = vz * ut * speed;
        for (int i = 0; i < step; i++) {
            if (flying) {
                dy = 0;
            }
            else {
                dy -= ut * 25;
                dy = MAX(dy, -250);
            }
            x += vx;
            y += vy + dy * ut;
            z += vz;
            if (collide(chunks, chunk_count, 2, &x, &y, &z)) {
                dy = 0;
            }
        }
        if (y < 0) {
            y = highest_block(chunks, chunk_count, x, z) + 2;
        }

        if (left_click) {
            left_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (hy > 0 && is_destructable(hw)) {
                set_block(chunks, chunk_count, hx, hy, hz, 0, 1);
                int above = get_block(chunks, chunk_count, hx, hy + 1, hz);
                if (is_plant(above)) {
                    set_block(chunks, chunk_count, hx, hy + 1, hz, 0, 1);
                }
            }
        }

        if (right_click) {
            right_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (is_obstacle(hw)) {
                if (!player_intersects_block(2, x, y, z, hx, hy, hz)) {
                    set_block(chunks, chunk_count, hx, hy, hz, block_type, 1);
                }
            }
        }

        if (middle_click) {
            middle_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (is_selectable(hw)) {
                block_type = hw;
            }
        }

        if (teleport) {
            teleport = 0;
            if (player_count) {
                int index = rand_int(player_count);
                Player *player = players + index;
                x = player->x; y = player->y; z = player->z;
                rx = player->rx; ry = player->ry;
                ensure_chunks(chunks, &chunk_count, x, y, z, 1);
            }
        }

        client_position(x, y, z, rx, ry);
        char buffer[RECV_BUFFER_SIZE];
        while (client_recv(buffer, RECV_BUFFER_SIZE)) {
            float ux, uy, uz, urx, ury;
            if (sscanf(buffer, "U,%*d,%f,%f,%f,%f,%f",
                &ux, &uy, &uz, &urx, &ury) == 5)
            {
                x = ux; y = uy; z = uz; rx = urx; ry = ury;
                ensure_chunks(chunks, &chunk_count, x, y, z, 1);
                y = highest_block(chunks, chunk_count, x, z) + 2;
            }
            int bx, by, bz, bw;
            if (sscanf(buffer, "B,%*d,%*d,%d,%d,%d,%d",
                &bx, &by, &bz, &bw) == 4)
            {
                set_block(chunks, chunk_count, bx, by, bz, bw, 0);
                if (player_intersects_block(2, x, y, z, bx, by, bz)) {
                    y = highest_block(chunks, chunk_count, x, z) + 2;
                }
            }
            int pid;
            float px, py, pz, prx, pry;
            if (sscanf(buffer, "P,%d,%f,%f,%f,%f,%f",
                &pid, &px, &py, &pz, &prx, &pry) == 6)
            {
                Player *player = find_player(players, player_count, pid);
                if (!player && player_count < MAX_PLAYERS) {
                    player = players + player_count;
                    player_count++;
                    player->id = pid;
                    player->position_buffer = 0;
                    player->normal_buffer = 0;
                    player->uv_buffer = 0;
                    printf("%d other players are online\n", player_count);
                }
                if (player) {
                    update_player(player, px, py, pz, prx, pry);
                }
            }
            if (sscanf(buffer, "D,%d", &pid) == 1) {
                delete_player(players, &player_count, pid);
                printf("%d other players are online\n", player_count);
            }
        }

        int p = chunked(x);
        int q = chunked(z);
        ensure_chunks(chunks, &chunk_count, x, y, z, 0);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        set_matrix_3d(matrix, width, height, x, y, z, rx, ry, fov, ortho);

        // render chunks
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, x, y, z);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        for (int i = 0; i < chunk_count; i++) {
            Chunk *chunk = chunks + i;
            if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) {
                continue;
            }
            if (y < 100 && !chunk_visible(chunk, matrix)) {
                continue;
            }
            draw_chunk(chunk, position_loc, normal_loc, uv_loc);
        }

        // render players
        for (int i = 0; i < player_count; i++) {
            Player *player = players + i;
            draw_player(player, position_loc, normal_loc, uv_loc);
        }

        // render focused block wireframe
        int hx, hy, hz;
        int hw = hit_test(
            chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz);
        if (is_obstacle(hw)) {
            glUseProgram(line_program);
            glLineWidth(1);
            glEnable(GL_COLOR_LOGIC_OP);
            glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
            GLuint wireframe_buffer = gen_wireframe_buffer(hx, hy, hz, 0.51);
            draw_lines(wireframe_buffer, line_position_loc, 3, 48);
            glDeleteBuffers(1, &wireframe_buffer);
            glDisable(GL_COLOR_LOGIC_OP);
        }

        set_matrix_2d(matrix, width, height);

        // render crosshairs
        glUseProgram(line_program);
        glLineWidth(4);
        glEnable(GL_COLOR_LOGIC_OP);
        glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
        GLuint crosshair_buffer = gen_crosshair_buffer(width, height);
        draw_lines(crosshair_buffer, line_position_loc, 2, 4);
        glDeleteBuffers(1, &crosshair_buffer);
        glDisable(GL_COLOR_LOGIC_OP);

        // render selected item
        set_matrix_item(matrix, width, height);
        if (block_type != previous_block_type) {
            previous_block_type = block_type;
            gen_item_buffers(
                &item_position_buffer, &item_normal_buffer, &item_uv_buffer,
                block_type);
        }
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, 0, 0, 5);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        glDisable(GL_DEPTH_TEST);
        draw_cube(
            item_position_buffer, item_normal_buffer, item_uv_buffer,
            position_loc, normal_loc, uv_loc);
        glEnable(GL_DEPTH_TEST);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    client_stop();
    db_save_state(x, y, z, rx, ry);
    db_close();
    glfwTerminate();
    return 0;
}
/* inits sdl and creates an opengl window */
static void initSDL(VideoMode *video) {
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
		LOGE("Failed to init SDL2: %s", SDL_GetError());
		exit(1);
	}

#ifdef _WIN32
	float ddpi;
	if (!SDL_GetDisplayDPI(0, &ddpi, nullptr, nullptr)) {
		const float WINDOWS_DEFAULT_DPI = 96.0f;
		video->pixel_scale = ddpi / WINDOWS_DEFAULT_DPI;
	}
#endif

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	//SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	//SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

#ifdef EMSCRIPTEN
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
						SDL_GL_CONTEXT_PROFILE_ES);
#else
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
						SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
#endif

	int window_flags =
		  SDL_WINDOW_SHOWN
		| SDL_WINDOW_RESIZABLE
		| SDL_WINDOW_OPENGL
		| SDL_WINDOW_ALLOW_HIGHDPI;
	if (video->fullscreen) window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;

	sdl_window = SDL_CreateWindow(WINDOW_TITLE,
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		video->pixel_scale * video->width, video->pixel_scale * video->height,
		window_flags);
	if (!sdl_window) {
		LOGE("Failed to create an OpenGL window: %s", SDL_GetError());
		exit(1);
	}

	sdl_gl_context = SDL_GL_CreateContext(sdl_window);
	if (!sdl_gl_context) {
		LOGE("Failed to create an OpenGL context: %s", SDL_GetError());
		exit(1);
	}

	int drawable_width, drawable_height;
	SDL_GL_GetDrawableSize(sdl_window, &drawable_width, &drawable_height);
	if (drawable_width != video->width) {
		LOGI("Created high DPI window. (%dx%d)", drawable_width, drawable_height);
		video->pixel_scale = (float)drawable_width / (float)video->width;
	} else {
		video->pixel_scale = 1.0f;
	}

	if (SDL_GL_SetSwapInterval(1) == -1) { // sync with monitor refresh rate
		LOGW("Could not enable VSync.");
	}

	#ifndef __APPLE__
	glewInit();
	#endif
}
Exemple #13
0
/* Initialise the double buffered display */
bool screenInitialise()
{
	GLint glMaxTUs;
	GLenum err;

	glErrors();

	err = glewInit();
	if (GLEW_OK != err)
	{
		debug(LOG_FATAL, "Error: %s", glewGetErrorString(err));
		exit(1);
	}

	/* Dump general information about OpenGL implementation to the console and the dump file */
	ssprintf(opengl.vendor, "OpenGL Vendor: %s", glGetString(GL_VENDOR));
	addDumpInfo(opengl.vendor);
	debug(LOG_3D, "%s", opengl.vendor);
	ssprintf(opengl.renderer, "OpenGL Renderer: %s", glGetString(GL_RENDERER));
	addDumpInfo(opengl.renderer);
	debug(LOG_3D, "%s", opengl.renderer);
	ssprintf(opengl.version, "OpenGL Version: %s", glGetString(GL_VERSION));
	addDumpInfo(opengl.version);
	debug(LOG_3D, "%s", opengl.version);
	ssprintf(opengl.GLEWversion, "GLEW Version: %s", glewGetString(GLEW_VERSION));
	if (strncmp(opengl.GLEWversion, "1.9.", 4) == 0) // work around known bug with KHR_debug extension support in this release
	{
		debug(LOG_WARNING, "Your version of GLEW is old and buggy, please upgrade to at least version 1.10.");
		khr_debug = false;
	}
	else
	{
		khr_debug = GLEW_KHR_debug;
	}
	addDumpInfo(opengl.GLEWversion);
	debug(LOG_3D, "%s", opengl.GLEWversion);

	GLubyte const *extensionsBegin = glGetString(GL_EXTENSIONS);
	if (extensionsBegin == nullptr)
	{
		static GLubyte const emptyString[] = "";
		extensionsBegin = emptyString;
	}
	GLubyte const *extensionsEnd = extensionsBegin + strlen((char const *)extensionsBegin);
	std::vector<std::string> glExtensions;
	for (GLubyte const *i = extensionsBegin; i < extensionsEnd;)
	{
		GLubyte const *j = std::find(i, extensionsEnd, ' ');
		glExtensions.push_back(std::string(i, j));
		i = j + 1;
	}

	/* Dump extended information about OpenGL implementation to the console */

	std::string line;
	for (unsigned n = 0; n < glExtensions.size(); ++n)
	{
		std::string word = " ";
		word += glExtensions[n];
		if (n + 1 != glExtensions.size())
		{
			word += ',';
		}
		if (line.size() + word.size() > 160)
		{
			debug(LOG_3D, "OpenGL Extensions:%s", line.c_str());
			line.clear();
		}
		line += word;
	}
	debug(LOG_3D, "OpenGL Extensions:%s", line.c_str());
	debug(LOG_3D, "Notable OpenGL features:");
	debug(LOG_3D, "  * OpenGL 1.2 %s supported!", GLEW_VERSION_1_2 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.3 %s supported!", GLEW_VERSION_1_3 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.4 %s supported!", GLEW_VERSION_1_4 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.5 %s supported!", GLEW_VERSION_1_5 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 2.0 %s supported!", GLEW_VERSION_2_0 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 2.1 %s supported!", GLEW_VERSION_2_1 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 3.0 %s supported!", GLEW_VERSION_3_0 ? "is" : "is NOT");
	debug(LOG_3D, "  * Texture compression %s supported.", GLEW_ARB_texture_compression ? "is" : "is NOT");
	debug(LOG_3D, "  * Two side stencil %s supported.", GLEW_EXT_stencil_two_side ? "is" : "is NOT");
	debug(LOG_3D, "  * ATI separate stencil is%s supported.", GLEW_ATI_separate_stencil ? "" : " NOT");
	debug(LOG_3D, "  * Stencil wrap %s supported.", GLEW_EXT_stencil_wrap ? "is" : "is NOT");
	debug(LOG_3D, "  * Anisotropic filtering %s supported.", GLEW_EXT_texture_filter_anisotropic ? "is" : "is NOT");
	debug(LOG_3D, "  * Rectangular texture %s supported.", GLEW_ARB_texture_rectangle ? "is" : "is NOT");
	debug(LOG_3D, "  * FrameBuffer Object (FBO) %s supported.", GLEW_EXT_framebuffer_object ? "is" : "is NOT");
	debug(LOG_3D, "  * ARB Vertex Buffer Object (VBO) %s supported.", GLEW_ARB_vertex_buffer_object ? "is" : "is NOT");
	debug(LOG_3D, "  * NPOT %s supported.", GLEW_ARB_texture_non_power_of_two ? "is" : "is NOT");
	debug(LOG_3D, "  * texture cube_map %s supported.", GLEW_ARB_texture_cube_map ? "is" : "is NOT");
	glGetIntegerv(GL_MAX_TEXTURE_UNITS, &glMaxTUs);
	debug(LOG_3D, "  * Total number of Texture Units (TUs) supported is %d.", (int) glMaxTUs);
	debug(LOG_3D, "  * GL_ARB_timer_query %s supported!", GLEW_ARB_timer_query ? "is" : "is NOT");
	debug(LOG_3D, "  * KHR_DEBUG support %s detected", khr_debug ? "was" : "was NOT");

	if (!GLEW_VERSION_2_0)
	{
		debug(LOG_FATAL, "OpenGL 2.0 not supported! Please upgrade your drivers.");
		return false;
	}

	screenWidth = MAX(screenWidth, 640);
	screenHeight = MAX(screenHeight, 480);

	std::pair<int, int> glslVersion(0, 0);
	sscanf((char const *)glGetString(GL_SHADING_LANGUAGE_VERSION), "%d.%d", &glslVersion.first, &glslVersion.second);

	/* Dump information about OpenGL 2.0+ implementation to the console and the dump file */
	GLint glMaxTIUs, glMaxTCs, glMaxTIUAs, glmaxSamples, glmaxSamplesbuf;

	debug(LOG_3D, "  * OpenGL GLSL Version : %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
	ssprintf(opengl.GLSLversion, "OpenGL GLSL Version : %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
	addDumpInfo(opengl.GLSLversion);

	glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &glMaxTIUs);
	debug(LOG_3D, "  * Total number of Texture Image Units (TIUs) supported is %d.", (int) glMaxTIUs);
	glGetIntegerv(GL_MAX_TEXTURE_COORDS, &glMaxTCs);
	debug(LOG_3D, "  * Total number of Texture Coords (TCs) supported is %d.", (int) glMaxTCs);
	glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, &glMaxTIUAs);
	debug(LOG_3D, "  * Total number of Texture Image Units ARB(TIUAs) supported is %d.", (int) glMaxTIUAs);
	glGetIntegerv(GL_SAMPLE_BUFFERS, &glmaxSamplesbuf);
	debug(LOG_3D, "  * (current) Max Sample buffer is %d.", (int) glmaxSamplesbuf);
	glGetIntegerv(GL_SAMPLES, &glmaxSamples);
	debug(LOG_3D, "  * (current) Max Sample level is %d.", (int) glmaxSamples);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

	pie_Skybox_Init();

	// Generate backdrop render
	backdropGfx = new GFX(GFX_TEXTURE, GL_TRIANGLE_STRIP, 2);

	if (GLEW_ARB_timer_query)
	{
		glGenQueries(PERF_COUNT, perfpos);
	}

	if (khr_debug)
	{
		glDebugMessageCallback((GLDEBUGPROC)khr_callback, NULL);
		glEnable(GL_DEBUG_OUTPUT);
		// Do not want to output notifications. Some drivers spam them too much.
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
		debug(LOG_3D, "Enabling KHR_debug message callback");
	}

	glErrors();
	return true;
}
Exemple #14
0
int main () {
	// Initialize GLFW
	if ( !glfwInit()) {
		std::cerr << "Failed to initialize GLFW! I'm out!" << std::endl;
		exit(-1);
	}

	// Use OpenGL 3.2 core profile
    /*
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    */

	// Open a window and attach an OpenGL rendering context to the window surface
	if( !glfwOpenWindow(800, 600, 8, 8, 8, 0, 0, 0, GLFW_WINDOW)) {
		std::cerr << "Failed to open a window! I'm out!" << std::endl;
		glfwTerminate();
		exit(-1);
	}

	// Register a callback function for window resize events
	glfwSetWindowSizeCallback( window_resized );

	// Register a callback function for keyboard pressed events
	glfwSetKeyCallback(keyboard);	

	// Print the OpenGL version
	int major, minor, rev;
	glfwGetGLVersion(&major, &minor, &rev);
	std::cout << "OpenGL - " << major << "." << minor << "." << rev << std::endl;

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	if(glewInit() != GLEW_OK) {
		std::cerr << "Failed to initialize GLEW! I'm out!" << std::endl;
		glfwTerminate();
		exit(-1);
	}

	// Create a vertex array object
	GLuint vao;

	// Initialize the data to be rendered
	initialize(vao);

	// Create a rendering loop
	int running = GL_TRUE;

	while(running) {
		// Display scene
		display(vao);

		// Pool for events
		glfwPollEvents();
		// Check if the window was closed
		running = glfwGetWindowParam(GLFW_OPENED);
	}

	// Terminate GLFW
	glfwTerminate();

	return 0;
}
int main(int argc, char** argv)
{
	//! The pointer to the GLFW window
	GLFWwindow* window; 

	//! Setting up the GLFW Error callback
	glfwSetErrorCallback(csX75::error_callback);

	//! Initialize GLFW
	if (!glfwInit())
	return -1;

	//We want OpenGL 4.0
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); 
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	//This is for MacOSX - can be omitted otherwise
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); 
	//We don't want the old OpenGL 
	//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); 

	//! Create a windowed mode window and its OpenGL context
	window = glfwCreateWindow(720, 720, "Assignment3:Star Wars", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	//! Make the window's context current 
	glfwMakeContextCurrent(window);

	//Initialize GLEW
	//Turn this on to get Shader based OpenGL
	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		//Problem: glewInit failed, something is seriously wrong.
		std::cerr<<"GLEW Init Failed : %s"<<std::endl;
	}

	//Keyboard Callback
	glfwSetKeyCallback(window, csX75::key_callback);
	//Framebuffer resize callback
	glfwSetFramebufferSizeCallback(window, csX75::framebuffer_size_callback);

	// Ensure we can capture the escape key being pressed below
	//glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
	glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, GL_TRUE);



	//glfwSetCursorPosCallback(window, csX75::cursor_callback);
	//Initialize GL state
	csX75::initGL();
	initBuffersGL();



	// Loop until the user closes the window
	while (glfwWindowShouldClose(window) == 0)
	{

  		// Render here
	  
		renderGL();

		// Swap front and back buffers
		glfwSwapBuffers(window);
	  
		// Poll for and process events
		glfwPollEvents();
	}

	glfwTerminate();
	return 0;
}
Exemple #16
0
int main (int argc, char** argv) {
	// GLUT initialisation and matrices
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutCreateWindow("GCP Assignment");
	glutReshapeFunc(changeViewport);
	glutKeyboardFunc(keyboardFunc);
	glutDisplayFunc(render);
	glewInit();

	initMatrices(); 

	// Make shaders
	char* vertexShaderSourceCode = readFile("vertexShader.vsh");
	char* fragmentShaderSourceCode = readFile("fragmentShader.fsh");
	GLuint vertShaderID = makeVertexShader(vertexShaderSourceCode);
	GLuint fragShaderID = makeFragmentShader(fragmentShaderSourceCode);
	shaderProgramID = makeShaderProgram(vertShaderID, fragShaderID);

	// create and bind the VBO toi the VAO"
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	// Create the buffer of the size necessary to store the model  3 flaots for RGB 3 for the vertices XYZ
	glBufferData(GL_ARRAY_BUFFER, 6*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
	
	// Load the vertex points
	glBufferSubData(GL_ARRAY_BUFFER, 0, 3*NUM_VERTICES*sizeof(GLfloat), vertices);
	// Load the colors right after that
	glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),3*NUM_VERTICES*sizeof(GLfloat), normals);
	
	
#ifdef USING_INDEX_BUFFER
	glGenBuffers(1, &indexBufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_INDICES*sizeof(GLuint), indices, GL_STATIC_DRAW);
#endif
	

	// the console output
	std::cout << "Giannandrea Grone Assignment \n";
	std::cout << "Simple demonstration of rotating a model around itself with Quaternions or Matrices\n ";
	std::cout << "The results seem similar but the maths behind it is significantly different\n ";
	std::cout << "How to use: \n ";
	std::cout << "Press P to toggle between Matrices and Quaternions \n ";
	std::cout << "Press O to toggle between Automatic and Manual \n ";
	std::cout << "WASD to move the camera (left, right, forward, backward \n ";
	std::cout << "QE  to move the camera upward downward \n ";
	std::cout << "RT FG CV to rotate the camera on XYZ \n ";
	std::cout << "(Manual only) YU HJ NM to rotate the model on XYZ \n";




	// bind the data with the shaders
	positionID = glGetAttribLocation(shaderProgramID, "s_vPosition");
	normalID = glGetAttribLocation(shaderProgramID, "s_vNormal");
	lightID = glGetUniformLocation(shaderProgramID, "vLight");	// NEW
	
	// gives the data to the shaders
	perspectiveMatrixID = glGetUniformLocation(shaderProgramID, "mP");
	viewMatrixID = glGetUniformLocation(shaderProgramID, "mV");
	modelMatrixID = glGetUniformLocation(shaderProgramID, "mM");
	allRotsMatrixID = glGetUniformLocation(shaderProgramID, "mRotations");
	

	glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	
	glUseProgram(shaderProgramID);
	glEnableVertexAttribArray(positionID);
	glEnableVertexAttribArray(normalID);
	
	// Turn on depth cullint
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);
	
	glutMainLoop();
	
	return 0;
}
Exemple #17
0
int main() {
    //    createWindow & context
    if (!glfwInit()) {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return -1;
    }
    glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Open a window and create its OpenGL context
    GLFWwindow *window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr); // Windowed
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    if (window == NULL){
        fprintf(stderr, "Failed to open GLFW window\n");
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

//// GLEW

    // Initialize GLEW
    glewExperimental = true;
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));


    // Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    // Create a Vertex Buffer Object and copy the vertex data to it
    GLuint vbo;
    glGenBuffers(1, &vbo);

    GLfloat vertices[] = {
            -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left
            0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right
            0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
            -0.5f, -0.5f, 1.0f, 1.0f, 1.0f  // Bottom-left
    };

//    GLfloat vertices[] = {
//            0.0f,  0.5f, 1.0f, 0.0f, 0.0f,
//            0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
//            -0.5f, -0.5f, 0.0f, 0.0f, 1.0f
//    };

//    GLfloat vertices[] = {
//            0.0f,  0.5f, 0.0f,
//            0.5f, -0.5f, 0.5f,
//            -0.5f, -0.5f, 1.0f
//    };

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Create an element array
    GLuint ebo;
    glGenBuffers(1, &ebo);

    GLuint elements[] = {
            0, 1, 2,
            1, 2, 3,
    };

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

    // Create and compile the vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outColor");
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);

    GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colAttrib);
    glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void *) (2 * sizeof(GLfloat)));

//    // Specify the layout of the vertex data
//    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
//    glEnableVertexAttribArray(posAttrib);
//    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
//
//    GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
//    glEnableVertexAttribArray(colAttrib);
//    glVertexAttribPointer(colAttrib, 1, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));


//// GLEW

    while (!glfwWindowShouldClose(window)) {

        if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
            glfwSetWindowShouldClose(window, GL_TRUE);

        // Clear the screen to black
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw a rectangle from the 2 triangles using 6 indices
//        glDrawArrays(GL_TRIANGLES, 0, 3);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glDeleteProgram(shaderProgram);
    glDeleteShader(fragmentShader);
    glDeleteShader(vertexShader);

    glDeleteBuffers(1, &ebo);
    glDeleteBuffers(1, &vbo);

    glDeleteVertexArrays(1, &vao);

}
Exemple #18
0
Engine::Engine(util::Dir *data_dir, const char *windowtitle)
	:
	running(false),
	window_size{800, 600},
	camgame_phys{10 * coord::settings::phys_per_tile, 10 * coord::settings::phys_per_tile, 0},
	camgame_window{400, 300},
	camhud_window{0, 600},
	tile_halfsize{48, 24},  // TODO: get from convert script
	data_dir(data_dir),
	audio_manager{48000, AUDIO_S16LSB, 2, 4096}
{

	// enqueue the engine's own input handler to the
	// execution list.
	this->register_input_action(&this->input_handler);
	this->input_handler.register_resize_action(this);

	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		throw util::Error("SDL video initialization: %s", SDL_GetError());
	} else {
		log::msg("initialized SDL video subsystems.");
	}

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
	SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	int32_t window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED;
	this->window = SDL_CreateWindow(
		windowtitle,
		SDL_WINDOWPOS_CENTERED,
		SDL_WINDOWPOS_CENTERED,
		this->window_size.x,
		this->window_size.y,
		window_flags
	);

	if (this->window == nullptr) {
		throw util::Error("Failed creating SDL window: %s", SDL_GetError());
	}

	// load support for the PNG image formats, jpg bit: IMG_INIT_JPG
	int wanted_image_formats = IMG_INIT_PNG;
	int sdlimg_inited = IMG_Init(wanted_image_formats);
	if ((sdlimg_inited & wanted_image_formats) != wanted_image_formats) {
		throw util::Error("Failed to init PNG support: %s", IMG_GetError());
	}

	this->glcontext = SDL_GL_CreateContext(this->window);

	if (this->glcontext == nullptr) {
		throw util::Error("Failed creating OpenGL context: %s", SDL_GetError());
	}

	// initialize glew, for shaders n stuff
	GLenum glew_state = glewInit();
	if (glew_state != GLEW_OK) {
		throw util::Error("GLEW initialization failed");
	}
	if (!GLEW_VERSION_2_1) {
		throw util::Error("OpenGL 2.1 not available");
	}

	// to quote the standard doc:
	// 'The value gives a rough estimate
	// of the largest texture that the GL can handle'
	// -> wat?
	// anyways, we need at least 1024x1024.
	int max_texture_size;
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
	log::dbg("Maximum supported texture size: %d", max_texture_size);
	if (max_texture_size < 1024) {
		throw util::Error("Maximum supported texture size too small: %d", max_texture_size);
	}

	int max_texture_units;
	glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units);
	log::dbg("Maximum supported texture units: %d", max_texture_units);
	if (max_texture_size < 2) {
		throw util::Error("Your GPU has too less texture units: %d", max_texture_units);
	}

	// vsync on
	SDL_GL_SetSwapInterval(1);

	// enable alpha blending
	glEnable(GL_BLEND);

	// order of drawing relevant for depth
	// what gets drawn last is displayed on top.
	glDisable(GL_DEPTH_TEST);

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// initialize debug text font
	this->dejavuserif20 = new Font{"DejaVu Serif", "Book", 20};

	// initialize job manager with cpucount-2 worker threads
	int number_of_worker_threads = SDL_GetCPUCount() - 2;
	if (number_of_worker_threads <= 0) {
		number_of_worker_threads = 1;
	}
	this->job_manager = new job::JobManager{number_of_worker_threads};

	// initialize audio
	auto devices = audio::AudioManager::get_devices();
	if (devices.empty()) {
		throw util::Error{"No audio devices found"};
	}
}
int main(int argc, char **argv)
{
    // initialize everything
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0)
    {
        return 1;
    }

    if (!g_oculusVR.InitVR())
    {
        SDL_Quit();
        return 1;
    }

    ovrSizei hmdResolution = g_oculusVR.GetResolution();
    ovrSizei windowSize = { hmdResolution.w / 2, hmdResolution.h / 2 };

    g_renderContext.Init("Oculus Rift Vive-style tracker chaperone", 100, 100, windowSize.w, windowSize.h);
    SDL_ShowCursor(SDL_DISABLE);

    if (glewInit() != GLEW_OK)
    {
        g_oculusVR.DestroyVR();
        g_renderContext.Destroy();
        SDL_Quit();
        return 1;
    }

    if (!g_oculusVR.InitVRBuffers(windowSize.w, windowSize.h))
    {
        g_oculusVR.DestroyVR();
        g_renderContext.Destroy();
        SDL_Quit();
        return 1;
    }

    ShaderManager::GetInstance()->LoadShaders();
    g_application.OnStart();

    while (g_application.Running())
    {
        // handle key presses
        processEvents();

        glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        g_oculusVR.OnRenderStart();

        for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
        {
            OVR::Matrix4f MVPMatrix = g_oculusVR.OnEyeRender(eyeIndex);

            // update MVP in both shaders
            const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
            glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
            const ShaderProgram &shader2 = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::OVRFrustumShader);
            glUniformMatrix4fv(shader2.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);

            g_application.OnRender();
            g_oculusVR.RenderTrackerChaperone();
            g_oculusVR.OnEyeRenderFinish(eyeIndex);
        }

        g_oculusVR.SubmitFrame();
        g_oculusVR.BlitMirror();
        SDL_GL_SwapWindow(g_renderContext.window);
    }

    g_oculusVR.DestroyVR();
    g_renderContext.Destroy();

    SDL_Quit(); 

    return 0;
}
int main(int argc, char **argv) 
{

//  GLUT initialization
    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);//|GLUT_MULTISAMPLE );

    glutInitContextVersion (3, 3);
    glutInitContextFlags (GLUT_COMPATIBILITY_PROFILE );

    glutInitWindowPosition(100,100);
    glutInitWindowSize(width, height);
    glutCreateWindow("OBJParser Demo");
        

//  Callback Registration
    glutDisplayFunc(Render::renderScene);
    glutReshapeFunc(IO::changeSize);
    glutIdleFunc(Render::renderScene);

//  Mouse and Keyboard Callbacks
    glutKeyboardFunc(IO::processKeys);
    glutMouseFunc(IO::processMouseButtons);
    glutMotionFunc(IO::processMouseMotion);
    glutMouseWheelFunc ( IO::mouseWheel ) ;


    if(argc == 2)
        IO::parseInputFile(argv[1]);
    else
        std::cout << "Wrong number of command line arguments\n" << std::endl;
//  Init GLEW
    //glewExperimental = GL_TRUE;
    glewInit();
    if (glewIsSupported("GL_VERSION_3_3"))
        printf("Ready for OpenGL 3.3\n");
    else {
        printf("OpenGL 3.3 not supported\n");
        return(1);
    }

    //  Init the app (load model and textures) and OpenGL
    if (!init())
    {
        printf("Could not Load the Model\n");
        return 0;
    }
   // printf ("Vendor: %s\n", glGetString (GL_VENDOR));
   // printf ("Renderer: %s\n", glGetString (GL_RENDERER));
   // printf ("Version: %s\n", glGetString (GL_VERSION));
   // printf ("GLSL: %s\n", glGetString (GL_SHADING_LANGUAGE_VERSION));


    // return from main loop
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

    //glutTimerFunc(1600, timer, 1);
    glutMainLoop();

    // cleaning up
    textureIdMap.clear();  

    Render::clearMeshes();

    // delete buffers
    glDeleteBuffers(1,&matricesUniBuffer);

    return(0);
}
ProjectorOpenGL::ProjectorOpenGL(unsigned int _screenNum){

    // Create the OpenGL context
    context = new OpenGLContext(_screenNum);

    // OpenGL setup
    context->makeContextCurrent();

    glEnable(GL_TEXTURE_2D);

    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    
    // Set up for 1:1 pixel mapping in the z=0 plane. Upper left corner is (0,0).
    glViewport(0, 0, context->getScreenResX(), context->getScreenResY());
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, 1, 1, 0, -1, 1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    
    // Set up fragment shader
    GLenum err = glewInit();
    if(err != GLEW_OK)
        std::cerr << "ProjectorOpenGL: Could not initialize GLEW!" << std::endl;

//    const GLchar *vertexShaderSource =
//    "void main(){\n"
//    "    gl_Position = ftransform();\n"
//    "}";


//    const GLchar *fragmentShaderSource =
//    "uniform sampler2D texture;\n"
//    "void main(void){\n"
//    "   gl_FragColor = texture2D(texture, gl_TexCoord[0].st);\n"
//    "}";

//    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
//    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
//    glCompileShader(vertexShader);
//    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
//    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
//    glCompileShader(fragmentShader);

//    GLint status;
//    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
//    if(status != GL_TRUE)
//        std::cerr << "ProjectorOpenGL: Could not compile vertex shader!" << std::endl;

//    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
//    if(status != GL_TRUE)
//        std::cerr << "ProjectorOpenGL: Could not compile fragment shader!" << std::endl;

//    int len = 0;
//    glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &len);
//    char* log = new char[len];
//    glGetShaderInfoLog(vertexShader, len, NULL, log);
//    std::cout << log << std::endl;

//    glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &len);
//    glGetShaderInfoLog(fragmentShader, len, NULL, log);
//    std::cout << log << std::endl;

//    shaderProgram = glCreateProgram();
//    glAttachShader(shaderProgram, vertexShader);
//    glAttachShader(shaderProgram, fragmentShader);
//    glLinkProgram(shaderProgram);
//    glUseProgram(shaderProgram);

    context->flush();
}
Exemple #22
0
void vsx_statelist::render() 
{
  if (render_first)
  {
    glewInit();
    GLint viewport[4];
    glGetIntegerv(GL_VIEWPORT, viewport);
    if (tex1.has_buffer_support())
    {
      tex1.init_buffer(viewport[2], viewport[3]);
      tex_to.init_buffer(viewport[2], viewport[3]);

      get_files_recursive(own_path+"visuals_faders", &fader_file_list,"",".svn CVS");
      for (std::list<vsx_string>::iterator it = fader_file_list.begin(); it != fader_file_list.end(); ++it)
      {
        #ifdef VSXU_DEBUG
          printf("initializing fader %s\n", (*it).c_str());
        #endif
        vsx_engine* lvxe = new vsx_engine();
        lvxe->dump_modules_to_disk = false;
        lvxe->init(sound_type);
        lvxe->start();
        lvxe->load_state(*it);
        faders.push_back(lvxe);
        fade_id = 0;
      }
    }
    transitioning = false;
    render_first = false;
    if ( state_iter == statelist.end() ) return;

    // mark all state_info instances volatile
    for (state_iter = statelist.begin(); state_iter != statelist.end(); state_iter++)
    {
      (*state_iter).is_volatile = true;
    }

    // go through statelist and load and validate every plugin
    std::vector<state_info> new_statelist;
    for (state_iter = statelist.begin(); state_iter != statelist.end(); state_iter++)
    {
      if (init_current((*state_iter).engine, &(*state_iter)) > 0)
      {
        continue;
      }
      new_statelist.push_back(*state_iter);
      if (option_preload_all == true)
      {
        while ( (*state_iter).engine->modules_left_to_load )
        {
          (*state_iter).engine->process_message_queue( &(*state_iter).cmd_in, cmd_out = &(*state_iter).cmd_out,false, true);
          (*state_iter).engine->render();
        }
      }
    }
    statelist = new_statelist;

    // mark all state_info instances non-volatile (engine will be deleted when state_iter will be deleted)
    for (state_iter = statelist.begin(); state_iter != statelist.end(); state_iter++)
    {
      (*state_iter).is_volatile = true;
    }

    // reset state_iter to a random state
    state_iter = statelist.begin();
    int steps = rand() % statelist.size();
    while (steps) {
      ++state_iter;
      if (state_iter == statelist.end()) state_iter = statelist.begin();
      --steps;
    }

    vxe = (*state_iter).engine;
    cmd_in = &(*state_iter).cmd_in;
    cmd_out = &(*state_iter).cmd_out;
  } // render first

  // prevent from rendering by mistake
  if ( !statelist.size() ) return;

  if ((*state_iter).engine != vxe) // change is on the way
  {
    if ( tex_to.has_buffer_support() )
    {
      tex_to.begin_capture();
        if ((*state_iter).engine)
        {
          (*state_iter).engine->process_message_queue(&(*state_iter).cmd_in,&(*state_iter).cmd_out);
          (*state_iter).engine->render();
        }
        glColorMask(false, false, false, true);
        glClearColor(0,0,0,1);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glColorMask(true, true, true, true);
      tex_to.end_capture();
      if (
        (*state_iter).engine->modules_left_to_load == 0 &&
        (*state_iter).engine->commands_internal.count() == 0 &&
        transition_time > 1.0f
      )
      {
        transition_time = 1.0f;
        timer.start();
        fade_id = rand() % (faders.size());
      }
    } else
    {
      transition_time = -1.0f;
    }

    if (transition_time <= 0.0)
    {
      vxe = (*state_iter).engine;
      cmd_in = &(*state_iter).cmd_in;
      cmd_out = &(*state_iter).cmd_out;
      transitioning = false;
      transition_time = 2.0f;
      if (cmd_out && cmd_in)
      {
        if (vxe)
        {
          vxe->process_message_queue(cmd_in,cmd_out);
        }
        cmd_out->clear(true);
      }
      if (vxe)
      {
        vxe->render();
      }
    } else
    {
      if (cmd_out && cmd_in)
      {
        if (vxe)
        {
          vxe->process_message_queue(cmd_in,cmd_out);
        }
        cmd_out->clear(true);
      }

      // begin capture
      if (tex1.has_buffer_support())
      {
        tex1.begin_capture();
      }

      // render
      if (vxe)
      {
        vxe->render();
      }
      glColorMask(false, false, false, true);
      glClearColor(0,0,0,1);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
      glColorMask(true, true, true, true);

      // end capture and send to fader
      if (tex1.has_buffer_support())
      {
        tex1.end_capture();
        vsx_module_param_texture* param_t_a = (vsx_module_param_texture*)faders[fade_id]->get_in_param_by_name("visual_fader", "texture_a_in");
        vsx_module_param_texture* param_t_b = (vsx_module_param_texture*)faders[fade_id]->get_in_param_by_name("visual_fader", "texture_b_in");
        vsx_module_param_float* param_pos = (vsx_module_param_float*)faders[fade_id]->get_in_param_by_name("visual_fader", "fade_pos_in");
        vsx_module_param_float* fade_pos_from_engine = (vsx_module_param_float*)faders[fade_id]->get_in_param_by_name("visual_fader", "fade_pos_from_engine");
        faders[fade_id]->process_message_queue(&l_cmd_in, &l_cmd_out);
        l_cmd_out.clear();
        if (param_t_a && param_t_b && param_pos && fade_pos_from_engine)
        {
          param_t_a->set(&tex1);
          param_t_b->set(&tex_to);
          fade_pos_from_engine->set(1.0f);
          float t = transition_time;
          if (t > 1.0f) t = 1.0f;
          if (t < 0.0f) t = 0.0f;
          param_pos->set(1.0-t);
          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
          faders[fade_id]->render();
        }
      }

      if (transition_time <= 1.0f)
      {
        transition_time -= timer.dtime();
      }
    }
  } else
  {
    if (cmd_out && cmd_in)
    {
      vxe->process_message_queue(cmd_in, cmd_out);
      cmd_out->clear();
    }
    vxe->render();
    if (randomizer)
    {
      randomizer_time -= vxe->engine_info.real_dtime;
      if (randomizer_time < 0.0f)
      {
        random_state();
        randomizer_time = (float)(rand()%1000)*0.001f*15.0f+10.0f;
      }
    }
  }
}
Exemple #23
0
int main()
{
	std::cout << "Starting GLFW context, OpenGL3.3" << std::endl;
	// Init GLFW
	glfwInit();
	// Setting all the required options for GLFW
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	glfwWindowHint(GLFW_SAMPLES, 4);

	// Create a GLFWwindows object that we can use for GLFW's funtions
	GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "OpenGL Tutorial", nullptr, nullptr);
	if (window == nullptr)
	{
		std::cout << "Failed to create GLFW window" << std::endl;
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);

	// Set the required callback functions
	glfwSetKeyCallback(window, key_callback);
	glfwSetCursorPosCallback(window, mouse_callback);
	glfwSetScrollCallback(window, scroll_callback);
	
	// GLFW Options
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
	glewExperimental = GL_TRUE;
	
	// Initialize GLEW to setup the OpenGL Function pointers
	glewInit();

	// Initialize GLEW to setup the OpenGL Function pointers
	if (glewInit() != GLEW_OK)
	{
		std::cout << "Failed to initialize GLEW" << std::endl;
		return -1;
	}

	// Define the viewport dimensions
	glViewport(0, 0, screenWidth, screenHeight);

	//Setup OpenGL options
	glEnable(GL_DEPTH_TEST);

	// Build and compile our shader program
	Shader ourShader("VertexShader.txt", "FragmentShader.txt");
	Shader lampShader("LampVertexShader.txt", "LampFragmentShader.txt");
	

	// Set up vertex data (and buffer(s)) and attribute pointers
	GLfloat vertices[] = {
		// Positions          // Normals          // Texture Coords
		-0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 0.0f,
		 0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 0.0f,
		 0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 1.0f,
		 0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 1.0f,
		-0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 1.0f,
		-0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 0.0f,

		-0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   0.0f, 0.0f,
		 0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   1.0f, 0.0f,
		 0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   1.0f, 1.0f,
		 0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   1.0f, 1.0f,
		-0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   0.0f, 1.0f,
		-0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   0.0f, 0.0f,

		-0.5f,  0.5f,  0.5f, -1.0f,  0.0f, 0.0f,   1.0f, 0.0f,
		-0.5f,  0.5f, -0.5f, -1.0f,  0.0f, 0.0f,   1.0f, 1.0f,
		-0.5f, -0.5f, -0.5f, -1.0f,  0.0f, 0.0f,   0.0f, 1.0f,
		-0.5f, -0.5f, -0.5f, -1.0f,  0.0f, 0.0f,   0.0f, 1.0f,
		-0.5f, -0.5f,  0.5f, -1.0f,  0.0f, 0.0f,   0.0f, 0.0f,
		-0.5f,  0.5f,  0.5f, -1.0f,  0.0f, 0.0f,   1.0f, 0.0f,

		 0.5f,  0.5f,  0.5f,  1.0f,  0.0f, 0.0f,   1.0f, 0.0f,
		 0.5f,  0.5f, -0.5f,  1.0f,  0.0f, 0.0f,   1.0f, 1.0f,
		 0.5f, -0.5f, -0.5f,  1.0f,  0.0f, 0.0f,   0.0f, 1.0f,
		 0.5f, -0.5f, -0.5f,  1.0f,  0.0f, 0.0f,   0.0f, 1.0f,
		 0.5f, -0.5f,  0.5f,  1.0f,  0.0f, 0.0f,   0.0f, 0.0f,
		 0.5f,  0.5f,  0.5f,  1.0f,  0.0f, 0.0f,   1.0f, 0.0f,

		-0.5f, -0.5f, -0.5f,  0.0f, -1.0f, 0.0f,   0.0f, 1.0f,
		 0.5f, -0.5f, -0.5f,  0.0f, -1.0f, 0.0f,   1.0f, 1.0f,
		 0.5f, -0.5f,  0.5f,  0.0f, -1.0f, 0.0f,   1.0f, 0.0f,
		 0.5f, -0.5f,  0.5f,  0.0f, -1.0f, 0.0f,   1.0f, 0.0f,
		-0.5f, -0.5f,  0.5f,  0.0f, -1.0f, 0.0f,   0.0f, 0.0f,
		-0.5f, -0.5f, -0.5f,  0.0f, -1.0f, 0.0f,   0.0f, 1.0f,

		-0.5f, 0.5f, -0.5f,   0.0f,  1.0f, 0.0f,   0.0f, 1.0f,
		 0.5f, 0.5f, -0.5f,   0.0f,  1.0f, 0.0f,   1.0f, 1.0f,
		 0.5f, 0.5f,  0.5f,   0.0f,  1.0f, 0.0f,   1.0f, 0.0f,
		 0.5f, 0.5f,  0.5f,   0.0f,  1.0f, 0.0f,   1.0f, 0.0f,
		-0.5f, 0.5f,  0.5f,   0.0f,  1.0f, 0.0f,   0.0f, 0.0f,
		-0.5f, 0.5f, -0.5f,   0.0f,  1.0f, 0.0f,   0.0f, 1.0f
	};
	GLuint indices[] = {
		0, 1, 3,	// First Triangle
		1, 2, 3		// Second Triangle
	};
	
	glm::vec3 cubePositions[] = {
		glm::vec3(0.0f, 0.0f, 0.0f),
		glm::vec3(2.0f, 5.0f, -15.0f),
		glm::vec3(-1.5f, -2.2f, -2.5f),
		glm::vec3(-3.8f, -2.0f, -12.3f),
		glm::vec3(2.4f, -0.4f, -3.5f),
		glm::vec3(-1.7f, 3.0f, -7.5f),
		glm::vec3(1.3f, -2.0f, -2.5f),
		glm::vec3(1.5f, 2.0f, -2.5f),
		glm::vec3(1.5f, 0.2f, -1.5f),
		glm::vec3(-1.3f, 1.0f, -1.5f)
	};

	glm::vec3 cubePositions2[] = {
		glm::vec3(0.0f, 0.0f, -2.0f),
		glm::vec3(0.0f, 1.0f, -4.0f),
		glm::vec3(0.0f, 2.0f, -6.0f),
		glm::vec3(0.0f, 3.0f, -8.0f),
		glm::vec3(0.0f, 4.0f, -10.0f),
		glm::vec3(0.0f, 5.0f, -12.0f),
		glm::vec3(0.0f, 6.0f, -14.0f),
		glm::vec3(0.0f, 7.0f, -16.0f),
		glm::vec3(0.0f, 8.0f, -18.0f),
		glm::vec3(0.0f, 9.0f, -20.0f)
	};

	GLfloat lightVertices[] = {
		-0.5f, -0.5f, -0.5f,
		0.5f, -0.5f, -0.5f,
		0.5f, 0.5f, -0.5f,
		0.5f, 0.5f, -0.5f,
		-0.5f, 0.5f, -0.5f,
		-0.5f, -0.5f, -0.5f,

		-0.5f, -0.5f, 0.5f,
		0.5f, -0.5f, 0.5f,
		0.5f, 0.5f, 0.5f,
		0.5f, 0.5f, 0.5f,
		-0.5f, 0.5f, 0.5f,
		-0.5f, -0.5f, 0.5f,

		-0.5f, 0.5f, 0.5f,
		-0.5f, 0.5f, -0.5f,
		-0.5f, -0.5f, -0.5f,
		-0.5f, -0.5f, -0.5f,
		-0.5f, -0.5f, 0.5f,
		-0.5f, 0.5f, 0.5f,

		0.5f, 0.5f, 0.5f,
		0.5f, 0.5f, -0.5f,
		0.5f, -0.5f, -0.5f,
		0.5f, -0.5f, -0.5f,
		0.5f, -0.5f, 0.5f,
		0.5f, 0.5f, 0.5f,

		-0.5f, -0.5f, -0.5f,
		0.5f, -0.5f, -0.5f,
		0.5f, -0.5f, 0.5f,
		0.5f, -0.5f, 0.5f,
		-0.5f, -0.5f, 0.5f,
		-0.5f, -0.5f, -0.5f,

		-0.5f, 0.5f, -0.5f,
		0.5f, 0.5f, -0.5f,
		0.5f, 0.5f, 0.5f,
		0.5f, 0.5f, 0.5f,
		-0.5f, 0.5f, 0.5f,
		-0.5f, 0.5f, -0.5f
	};
	glm::vec3 pointLightPositions[] =
	{
		glm::vec3( 0.7f, 0.2f, 2.0f),
		glm::vec3( 2.3f,-3.3f,-4.0f),
		glm::vec3(-4.0f, 2.0f,-12.0f),
		glm::vec3( 0.0f, 0.0f,-3.0f)
	};

	glm::vec3 pointLightPositions2[] =
	{
		glm::vec3(0.5f, 0.5f, 2.0f),
		glm::vec3(2.5f, 2.0f, -6.0f),
		glm::vec3(-2.5f, 6.0f, -12.0f),
		glm::vec3(0.0f, 0.0f, -3.0f)
	};

	GLuint VBO, VAO, EBO;
	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);
	// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
	glBindVertexArray(VAO);

	// Vertex Buffer Objects
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

	// Element Buffer Objects
	//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
	//glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

	// Position attribute
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
	glEnableVertexAttribArray(0);

	// Normal attribpointer
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
	glEnableVertexAttribArray(1);

	// TexCoord attribute
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
	glEnableVertexAttribArray(2);
	glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind
	glBindVertexArray(0);

	//-------------------------------------------------------------------
	// LIGHTNING
	GLuint lightVAO, lightVBO;
	glGenVertexArrays(1, &lightVAO);
	glGenBuffers(1, &lightVBO);
	glBindVertexArray(lightVAO);
	glBindBuffer(GL_ARRAY_BUFFER, lightVBO);
	
	glBufferData(GL_ARRAY_BUFFER, sizeof(lightVertices), lightVertices, GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
	glEnableVertexAttribArray(0);

	glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)

	// Adding textures
	std::vector<unsigned char> png, pixels;
	
	GLuint width, height;
	GLuint texture;
	GLuint texture2;

	GLuint diffuseMap;

	glGenTextures(1, &diffuseMap);
	glBindTexture(GL_TEXTURE_2D, diffuseMap);

	// Set the texture wrapping parameters
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	// Set texture filtering parameters
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// Loading the image, creating a texture and generate mipmaps
	lodepng::load_file(png, "woodbox.png");
	lodepng::decode(pixels, width, height, png.data(), png.size());

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
	glGenerateMipmap(GL_TEXTURE_2D);

	glBindTexture(GL_TEXTURE_2D, 0);

	// Second texture
	png.clear();
	pixels.clear();

	GLuint specularMap;

	glGenTextures(1, &specularMap);
	glBindTexture(GL_TEXTURE_2D, specularMap);

	//// Set our texture parameters
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	//// Set texture filtering
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	lodepng::load_file(png, "smiley.png");
	lodepng::decode(pixels, width, height, png.data(), png.size());

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
	glGenerateMipmap(GL_TEXTURE_2D);

	glBindTexture(GL_TEXTURE_2D, 0);

	// Game loop
	while (!glfwWindowShouldClose(window))
	{
		// Calculating the deltatime of current frame
		GLfloat currentFrame = glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;

		// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
		glfwPollEvents();
		do_movement();

		// Render
		glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Load shaders
		ourShader.Use();
		
		// Binding texture
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, diffuseMap);
		glUniform1i(glGetUniformLocation(ourShader.Program, "material.diffuse"), 0);

		//.... texture2
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, specularMap);
		glUniform1i(glGetUniformLocation(ourShader.Program, "material.specular"), 1);
		
		//View position
		glUniform3f(glGetUniformLocation(ourShader.Program, "viewPos"), camera.Position.x, camera.Position.y, camera.Position.z);
		// Material properties
		glUniform1f(glGetUniformLocation(ourShader.Program, "material.shininess"), 32.0f);

		// Directional light
		glUniform3f(glGetUniformLocation(ourShader.Program, "dirLight.direction"), -0.2f, -1.0f, -0.3f);
		glUniform3f(glGetUniformLocation(ourShader.Program, "dirLight.ambient"), 0.05f, 0.05f, 0.05f);
		glUniform3f(glGetUniformLocation(ourShader.Program, "dirLight.diffuse"), 0.4f, 0.4f, 0.4f);
		glUniform3f(glGetUniformLocation(ourShader.Program, "dirLight.specular"), 0.5f, 0.5f, 0.5f);
		
		// Light materials
		glUniform3f(glGetUniformLocation(ourShader.Program, "light.ambient"), 0.1f, 0.1f, 0.1f);
		glUniform3f(glGetUniformLocation(ourShader.Program, "light.diffuse"), 0.8f, 0.8f, 0.8f);
		glUniform3f(glGetUniformLocation(ourShader.Program, "light.specular"), 1.0f, 1.0f, 1.0f);
		glUniform1f(glGetUniformLocation(ourShader.Program, "light.constant"), 1.0f);
		glUniform1f(glGetUniformLocation(ourShader.Program, "light.linear"), 0.09);
		glUniform1f(glGetUniformLocation(ourShader.Program, "light.quadratic"), 0.032);
		glUniform1f(glGetUniformLocation(ourShader.Program, "material.shininess"), 32.0f);

		// 4 point lights
		for (GLuint i = 0; i < 4; i++)
		{
			std::string number = std::to_string(i);

			glUniform3f(glGetUniformLocation(ourShader.Program, ("pointLights[" + number + "].position").c_str()), pointLightPositions[i].x, pointLightPositions[i].y, pointLightPositions[i].z);
			glUniform3f(glGetUniformLocation(ourShader.Program, ("pointLights[" + number + "].ambient").c_str()), 0.05f, 0.05f, 0.05f);
			glUniform3f(glGetUniformLocation(ourShader.Program, ("pointLights[" + number + "].diffuse").c_str()), 0.8f, 0.8f, 0.8f);
			glUniform3f(glGetUniformLocation(ourShader.Program, ("pointLights[" + number + "].specular").c_str()), 1.0f, 1.0f, 1.0f);
			glUniform1f(glGetUniformLocation(ourShader.Program, ("pointLights[" + number + "].constant").c_str()), 1.0f);
			glUniform1f(glGetUniformLocation(ourShader.Program, ("pointLights[" + number + "].linear").c_str()), 0.09f);
			glUniform1f(glGetUniformLocation(ourShader.Program, ("pointLights[" + number + "].quadratic").c_str()), 0.032f);
		}
		// SpotLight
		glUniform3f(glGetUniformLocation(ourShader.Program, "spotLight.position"), camera.Position.x, camera.Position.y, camera.Position.z);
		glUniform3f(glGetUniformLocation(ourShader.Program, "spotLight.direction"), camera.Front.x, camera.Front.y, camera.Front.z);
		glUniform3f(glGetUniformLocation(ourShader.Program, "spotLight.ambient"), 0.0f, 0.0f, 0.0f);
		glUniform3f(glGetUniformLocation(ourShader.Program, "spotLight.diffuse"), 1.0f, 1.0f, 1.0f);
		glUniform3f(glGetUniformLocation(ourShader.Program, "spotLight.specular"), 1.0f, 1.0f, 1.0f);
		glUniform1f(glGetUniformLocation(ourShader.Program, "spotLight.constant"), 1.0f);
		glUniform1f(glGetUniformLocation(ourShader.Program, "spotLight.linear"), 0.09);
		glUniform1f(glGetUniformLocation(ourShader.Program, "spotLight.quadratic"), 0.032);
		glUniform1f(glGetUniformLocation(ourShader.Program, "spotLight.cutOff"), glm::cos(glm::radians(12.5f)));
		glUniform1f(glGetUniformLocation(ourShader.Program, "spotLight.outerCutOff"), glm::cos(glm::radians(15.0f)));

		// Camera/View Transformations
		glm::mat4 view;
		view = camera.GetViewMatrix();

		// Projection
		glm::mat4 projection;
		projection = glm::perspective(glm::radians(camera.Zoom), (GLfloat)screenWidth / (GLfloat)screenHeight, 0.1f, 100.0f);

		// Get their uniform locations
		GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
		GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
		GLint projectionLoc = glGetUniformLocation(ourShader.Program, "projection");
		
		// Passing them to shaders
		glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
		glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));
		
		// Draw box
		glBindVertexArray(VAO);
		glm::mat4 model;
		//glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
		//glDrawArrays(GL_TRIANGLES, 0, 36);
		//glBindVertexArray(0);

		for (GLuint i = 0; i < 10; i++)
		{
			model = glm::mat4();
			model = glm::translate(model, cubePositions2[i]);
			GLfloat angle = glm::radians(20.0f) * i;
			model = glm::rotate(model, (GLfloat)glfwGetTime() * angle, glm::vec3(1.0f, 0.3f, 0.5f));
			glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
			glDrawArrays(GL_TRIANGLES, 0, 36);
		}

		// Lamps
		lampShader.Use();
		modelLoc = glGetUniformLocation(lampShader.Program, "model");
		viewLoc = glGetUniformLocation(lampShader.Program, "view");
		projectionLoc = glGetUniformLocation(lampShader.Program, "projection");
		// Matrices
		glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
		glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection));

		//Drawing light object using light's vertex attributes
		glBindVertexArray(lightVAO);
		for (GLuint i = 0; i < 4; i++)
		{
			model = glm::mat4();
			model = glm::translate(model, pointLightPositions2[i]);
			model = glm::scale(model, glm::vec3(0.2f));
			glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
			glDrawArrays(GL_TRIANGLES, 0, 36);
		}
		glBindVertexArray(0);
		
		// Swap the screen buffers
		glfwSwapBuffers(window);
	}
	// Deleting all resources, what have been rendered
	glDeleteVertexArrays(1, &VAO);
	glDeleteBuffers(1, &VBO);
	glDeleteBuffers(1, &EBO);
	// Clearing any resources allocated by GLFW
	glfwTerminate();
	return 0;
}
Exemple #24
0
int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(800, 450, "Mah Base Project", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    glewInit();
    // Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    // Create a Vertex Buffer Object and copy the vertex data to it
    GLuint vbo;
    glGenBuffers(1, &vbo);
    GLfloat vertices[] = {
        0.0f, 0.5f,
        0.5f, -0.5f,
        -0.5f, -0.5f
    };
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    const char* vertexSource = loadSource("VertexSource.glsl");

    const char* fragmentSource = loadSource("FragmentSource.glsl");

    GLint status = GL_TRUE;

    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
    // cout<< "Vertex" << status << endl;

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
    // cout<< "Fragment" << status << endl;

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outColor");
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);


    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        // Clear the screen to black
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        // Draw a triangle from the 3 vertices
        glDrawArrays(GL_TRIANGLES, 0, 3);
        // Swap buffers

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}
Exemple #25
0
	window = glfwCreateWindow( 1024, 768, "Window sample", NULL, NULL);
	if( window == NULL ){
		fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, \
			they are not 3.3 compatible. \
			Try the 2.1 version of the tutorials.\n" );
		glfwTerminate();
		return -1;
	}

	//Initialize Glew ~ which would load glFunctions :)

	glfwMakeContextCurrent(window); // Initialize GLEW
	glewExperimental=true; // Needed in core profile

	///NOTE: Always initialize glewinit after this, else glShaderCreate() will be null....
	GLenum err = glewInit();

	if (err == GLEW_OK)
	{
		std::cout << "gliew initialized ok\n";
		//return 0;
	}
	//GLuint shader = glCreateShader(GL_VERTEX_SHADER);
	// Ensure we can capture the escape key being pressed below
	glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);



	std::cout << "glew version using: " << glewGetString(GLEW_VERSION) << std::endl;

int main(int argc, char** argv)
{

	if (!glfwInit())	// 初始化glfw库
	{
		std::cout << "Error::GLFW could not initialize GLFW!" << std::endl;
		return -1;
	}

	// 开启OpenGL 3.3 core profile
	std::cout << "Start OpenGL core profile version 3.3" << std::endl;
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	// 创建窗口
	GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
		"Demo of parallax mapping(Press p to change mapping)", NULL, NULL);
	if (!window)
	{
		std::cout << "Error::GLFW could not create winddow!" << std::endl;
		glfwTerminate();
		return -1;
	}
	// 创建的窗口的context指定为当前context
	glfwMakeContextCurrent(window);

	// 注册窗口键盘事件回调函数
	glfwSetKeyCallback(window, key_callback);
	// 注册鼠标事件回调函数
	glfwSetCursorPosCallback(window, mouse_move_callback);
	// 注册鼠标滚轮事件回调函数
	glfwSetScrollCallback(window, mouse_scroll_callback);
	// 鼠标捕获 停留在程序内
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	// 初始化GLEW 获取OpenGL函数
	glewExperimental = GL_TRUE; // 让glew获取所有拓展函数
	GLenum status = glewInit();
	if (status != GLEW_OK)
	{
		std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION)
			<< " error string:" << glewGetErrorString(status) << std::endl;
		glfwTerminate();
		return -1;
	}

	// 设置视口参数
	glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

	// Section1 准备顶点数据
	setupQuadVAO();

	// Section2 加载纹理
	GLuint diffuseMap = TextureHelper::load2DTexture("../../resources/textures/bricks2.jpg");
	GLuint normalMap = TextureHelper::load2DTexture("../../resources/textures/bricks2_normal.jpg");
	GLuint heightMap = TextureHelper::load2DTexture("../../resources/textures/bricks2_disp.jpg");

	// Section3 准备着色器程序
	Shader shader("scene.vertex", "scene.frag");

	glEnable(GL_DEPTH_TEST);
	// 开始游戏主循环
	while (!glfwWindowShouldClose(window))
	{
		GLfloat currentFrame = (GLfloat)glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;
		glfwPollEvents(); // 处理例如鼠标 键盘等事件
		do_movement(); // 根据用户操作情况 更新相机属性

		// 清除颜色缓冲区 重置为指定颜色
		glClearColor(0.18f, 0.04f, 0.14f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glm::mat4 projection = glm::perspective(camera.mouse_zoom,
			(GLfloat)(WINDOW_WIDTH) / WINDOW_HEIGHT, 1.0f, 100.0f); // 投影矩阵
		glm::mat4 view = camera.getViewMatrix(); // 视变换矩阵

		// 这里填写场景绘制代码

		shader.use();
		// 设置光源属性
		GLint lightAmbientLoc = glGetUniformLocation(shader.programId, "light.ambient");
		GLint lightDiffuseLoc = glGetUniformLocation(shader.programId, "light.diffuse");
		GLint lightSpecularLoc = glGetUniformLocation(shader.programId, "light.specular");
		GLint lightPosLoc = glGetUniformLocation(shader.programId, "light.position");
		glUniform3f(lightAmbientLoc, 0.2f, 0.2f, 0.2f);
		glUniform3f(lightDiffuseLoc, 0.5f, 0.5f, 0.5f);
		glUniform3f(lightSpecularLoc, 1.0f, 1.0f, 1.0f);
		glUniform3f(lightPosLoc, lampPos.x, lampPos.y, lampPos.z);
		// 设置观察者位置
		GLint viewPosLoc = glGetUniformLocation(shader.programId, "viewPos");
		glUniform3f(viewPosLoc, camera.position.x, camera.position.y, camera.position.z);
		// 设置光源位置 用于顶点着色器计算
		lightPosLoc = glGetUniformLocation(shader.programId, "lightPos");
		glUniform3f(lightPosLoc, lampPos.x, lampPos.y, lampPos.z);
		// 设置变换矩阵
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"),
			1, GL_FALSE, glm::value_ptr(projection));
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"),
			1, GL_FALSE, glm::value_ptr(view));
		glm::mat4 model;
		// 旋转以便于观察
		//model = glm::rotate(model, (GLfloat)glfwGetTime() * -2, glm::normalize(glm::vec3(1.0, 0.0, 1.0)));
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"),
			1, GL_FALSE, glm::value_ptr(model));
		glUniform1f(glGetUniformLocation(shader.programId, "heightScale"), heightScale);
		glUniform1i(glGetUniformLocation(shader.programId, "bParallaxMapping"), bParallaxMapping);
		// 绘制墙面
		glBindVertexArray(quadVAOId);
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, diffuseMap);
		glUniform1i(glGetUniformLocation(shader.programId, "diffuseMap"), 0);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, normalMap);
		glUniform1i(glGetUniformLocation(shader.programId, "normalMap"), 1);
		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, heightMap);
		glUniform1i(glGetUniformLocation(shader.programId, "heightMap"), 2);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		// 绘制模拟光源用于调试
		model = glm::mat4();
		model = glm::translate(model, lampPos);
		model = glm::scale(model, glm::vec3(0.1f));
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"),
			1, GL_FALSE, glm::value_ptr(model));
		glDrawArrays(GL_TRIANGLES, 0, 6);

		std::cout << "using parallax mapping: " << (bParallaxMapping ? "true" : "false") << std::endl;

		glBindVertexArray(0);
		glUseProgram(0);
		glfwSwapBuffers(window); // 交换缓存
	}
	// 释放资源
	glDeleteVertexArrays(1, &quadVAOId);
	glDeleteBuffers(1, &quadVBOId);
	glfwTerminate();
	return 0;
}
Exemple #27
0
Renderer* Init(Settings vs)
{
	assert(!initted);
	if (initted) return 0;

	// no mode set, find an ok one
	if ((vs.width <= 0) || (vs.height <= 0)) {
		const std::vector<VideoMode> modes = GetAvailableVideoModes();
		assert(!modes.empty());

		vs.width = modes.front().width;
		vs.height = modes.front().height;
	}

	WindowSDL *window = new WindowSDL(vs, "Pioneer");
	width = window->GetWidth();
	height = window->GetHeight();

	GLenum glew_err;
	if ((glew_err = glewInit()) != GLEW_OK)
		Error("GLEW initialisation failed: %s", glewGetErrorString(glew_err));

	{
		std::ostringstream buf;
		write_opengl_info(buf);

		FILE *f = FileSystem::userFiles.OpenWriteStream("opengl.txt", FileSystem::FileSourceFS::WRITE_TEXT);
		if (!f)
			Output("Could not open 'opengl.txt'\n");
		const std::string &s = buf.str();
		fwrite(s.c_str(), 1, s.size(), f);
		fclose(f);
	}

	if (!glewIsSupported("GL_VERSION_2_0") )
		Error("OpenGL Version 2.0 is not supported. Pioneer cannot run on your graphics card.");

	if (!glewIsSupported("GL_ARB_vertex_buffer_object"))
		Error("OpenGL extension ARB_vertex_buffer_object not supported. Pioneer can not run on your graphics card.");

	if (!glewIsSupported("GL_EXT_texture_compression_s3tc"))
		Error("OpenGL extension GL_EXT_texture_compression_s3tc not supported.\nPioneer can not run on your graphics card as it does not support compressed (DXTn/S3TC) format textures.");

	// We deliberately ignore the value from GL_NUM_COMPRESSED_TEXTURE_FORMATS, because some drivers
	// choose not to list any formats (despite supporting texture compression). See issue #3132.
	// This is (probably) allowed by the spec, which states that only formats which are "suitable
	// for general-purpose usage" should be enumerated.

	Renderer *renderer = new RendererGL2(window, vs);

	Output("Initialized %s\n", renderer->GetName());

	initted = true;

	MaterialDescriptor desc;
	desc.vertexColors = true;
	vtxColorMaterial = renderer->CreateMaterial(desc);
	vtxColorMaterial->IncRefCount();

	return renderer;
}
// The MAIN function, from here we start our application and run our Game loop
int main()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, screenWidth, screenHeight);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);

    // Setup and compile our shaders
    Shader shader("shaders/blending_discard.vs", "shaders/blending_discard.frag");

#pragma region "object_initialization"
    // Set the object data (buffers, vertex attributes)
    GLfloat cubeVertices[] = {
        // Positions          // Texture Coords
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f,
         0.5f, -0.5f, -0.5f,  1.0f,  0.0f,
         0.5f,  0.5f, -0.5f,  1.0f,  1.0f,
         0.5f,  0.5f, -0.5f,  1.0f,  1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f,

        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  1.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  1.0f,  1.0f,
         0.5f,  0.5f,  0.5f,  1.0f,  1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,

        -0.5f,  0.5f,  0.5f,  1.0f,  0.0f,
        -0.5f,  0.5f, -0.5f,  1.0f,  1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f,  1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f,  1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,
        -0.5f,  0.5f,  0.5f,  1.0f,  0.0f,

         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,
         0.5f,  0.5f, -0.5f,  1.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  0.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  0.0f,  1.0f,
         0.5f, -0.5f,  0.5f,  0.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,

        -0.5f, -0.5f, -0.5f,  0.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  1.0f,  1.0f,
         0.5f, -0.5f,  0.5f,  1.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  1.0f,  0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f,  1.0f,

        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,
         0.5f,  0.5f, -0.5f,  1.0f,  1.0f,
         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f
    };
    GLfloat planeVertices[] = {
        // Positions          // Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat)
         5.0f, -0.5f,  5.0f,  2.0f,  0.0f,
        -5.0f, -0.5f,  5.0f,  0.0f,  0.0f,
        -5.0f, -0.5f, -5.0f,  0.0f,  2.0f,

         5.0f, -0.5f,  5.0f,  2.0f,  0.0f,
        -5.0f, -0.5f, -5.0f,  0.0f,  2.0f,
         5.0f, -0.5f, -5.0f,  2.0f,  2.0f
    };
    GLfloat transparentVertices[] = {
        // Positions         // Texture Coords (swapped y coordinates because texture is flipped upside down)
        0.0f,  0.5f,  0.0f,  0.0f,  0.0f,
        0.0f, -0.5f,  0.0f,  0.0f,  1.0f,
        1.0f, -0.5f,  0.0f,  1.0f,  1.0f,

        0.0f,  0.5f,  0.0f,  0.0f,  0.0f,
        1.0f, -0.5f,  0.0f,  1.0f,  1.0f,
        1.0f,  0.5f,  0.0f,  1.0f,  0.0f
    };
    // Setup cube VAO
    GLuint cubeVAO, cubeVBO;
    glGenVertexArrays(1, &cubeVAO);
    glGenBuffers(1, &cubeVBO);
    glBindVertexArray(cubeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glBindVertexArray(0);
    // Setup plane VAO
    GLuint planeVAO, planeVBO;
    glGenVertexArrays(1, &planeVAO);
    glGenBuffers(1, &planeVBO);
    glBindVertexArray(planeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glBindVertexArray(0);
    // Setup transparent plane VAO
    GLuint transparentVAO, transparentVBO;
    glGenVertexArrays(1, &transparentVAO);
    glGenBuffers(1, &transparentVBO);
    glBindVertexArray(transparentVAO);
    glBindBuffer(GL_ARRAY_BUFFER, transparentVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(transparentVertices), transparentVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glBindVertexArray(0);

    // Load textures
    GLuint cubeTexture = loadTexture("resources/textures/wood.png");
    GLuint floorTexture = loadTexture("resources/textures/metal.png");
    GLuint transparentTexture = loadTexture("resources/textures/grass.png", true);
#pragma endregion

    std::vector<glm::vec3> vegetation;
    vegetation.push_back(glm::vec3(-1.5f,  0.0f, -0.48f));
    vegetation.push_back(glm::vec3( 1.5f,  0.0f,  0.51f));
    vegetation.push_back(glm::vec3( 0.0f,  0.0f,  0.7f));
    vegetation.push_back(glm::vec3(-0.3f,  0.0f, -2.3f));
    vegetation.push_back(glm::vec3( 0.5f,  0.0f, -0.6f));

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // Check and call events
        glfwPollEvents();
        Do_Movement();

        // Clear the colorbuffer
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Draw objects
        shader.Use();
        glm::mat4 model;
        glm::mat4 view = camera.GetViewMatrix();
        glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth / (float)screenHeight, 0.1f, 100.0f);
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        // Cubes
        glBindVertexArray(cubeVAO);
        glBindTexture(GL_TEXTURE_2D, cubeTexture);  // We omit the glActiveTexture part since TEXTURE0 is already the default active texture unit. (a single sampler used in fragment is set to 0 as well by default)
        model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 36);
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 36);
        // Floor
        glBindVertexArray(planeVAO);
        glBindTexture(GL_TEXTURE_2D, floorTexture);
        model = glm::mat4();
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 6);
        // Vegetation
        glBindVertexArray(transparentVAO);
        glBindTexture(GL_TEXTURE_2D, transparentTexture);
        for (GLuint i = 0; i < vegetation.size(); i++)
        {
            model = glm::mat4();
            model = glm::translate(model, vegetation[i]);
            glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
            glDrawArrays(GL_TRIANGLES, 0, 6);
        }
        glBindVertexArray(0);


        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Exemple #29
0
int main()
{
    GLFWwindow* window;
    NVGcontext *vg;

    if(!glfwInit()) {
        fprintf(stderr, "Failed to start glfw\n");
        return -1;
    }


    //Set OpenGL Revision
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    //Create Window
    window = glfwCreateWindow(1000, 600, "NanoVG", NULL, NULL);
    if (!window) {
        fprintf(stderr, "Failed to make window\n");
        glfwTerminate();
        return -1;
    }


    //Setup Context
    glfwSetKeyCallback(window, key);
    glfwSetMouseButtonCallback(window, mouse_event);
    glfwSetCursorPosCallback(window, mouse_hover);
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to start GLEW\n");
        return -1;
    }

    vg = nvgCreateGL2(NVG_ANTIALIAS | NVG_STENCIL_STROKES | NVG_DEBUG);
    nvgCreateFont(vg, "sans", "Roboto-Regular.ttf");
    nvgCreateFont(vg, "icons", "entypo.ttf");

    glfwSwapInterval(0);

	glfwSetTime(0);
	long prevt = glfwGetTime();


	while (!glfwWindowShouldClose(window))
	{
		double mx, my;
		int winWidth, winHeight;
		int fbWidth, fbHeight;
		float pxRatio;

		glfwGetCursorPos(window, &mx, &my);
		glfwGetWindowSize(window, &winWidth, &winHeight);
		glfwGetFramebufferSize(window, &fbWidth, &fbHeight);

		// Calculate pixel ration for hi-dpi devices.
		pxRatio = (float)fbWidth / (float)winWidth;

		// Update and render
		glViewport(0, 0, fbWidth, fbHeight);
        //glClearColor(0x06/255.0, 0x27/255.0, 0x37/255.0, 1.0f);
        glClearColor(0, 0, 0, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);

//#define M_PI 3.14159
        nvgBeginFrame(vg, winWidth, winHeight, pxRatio);
        //float in[100] = {0.0, 0.0, 0.5, 0.2, 0.3, 0.7,0.9,0.8,0.0,1.0};
        //drawHarmonicPlot(vg, in, 100, 0,0,winWidth, winHeight);
        //drawPowButton(vg, 0,0,winWidth, winHeight);
        drawPanDial(vg, "100", 0.4, 0, 0, winWidth, winHeight);

	//nvgBeginPath(vg);
    //float cx = 30.0, cy = 30.0, h = 80;
    //nvgArc(vg, cx, cy, 0.4*h, 0, 1.0/2.0*M_PI, 1);
    //nvgArc(vg, cx, cy, 0.2*h, 1.0/2.0*M_PI, 0, 2);
    //nvgClosePath(vg);
	//nvgFillColor(vg, nvgRGBA(0x11,0x45,0x75,255));
	//nvgFill(vg);
    nvgEndFrame(vg);
//		nvgBeginFrame(vg, winWidth, winHeight, pxRatio);
//
//        //viewReverb(vg, 0,0, winWidth, winHeight);
//        viewModule(vg, "afilter", 0,0,winWidth, winHeight);
//        //viewLFO(vg, 0,0, winWidth, winHeight);
//        //viewFilterEnv(vg, 0,0, winWidth, winHeight);
//                       //y   x    y   x     y    x    y   x   y   x
//        //float in[10] = {0.0, 0.0, 0.5, 0.2, 0.3, 0.7,-0.9,0.8,0.0,1.0};
//        //drawEnvEdit(vg, in, 5, 3, 0, 0, winWidth, winHeight);
//
//#if 0
//        dial_t dial = {60, 0, 0, 100, "label"};
//        renderDial(vg, dial);
//        drawButton(vg, "banana", 100, 25, 100, 50);
//        drawOptButton(vg, "opt", 200, 25, 100, 50);
//        drawButtonGrid(vg, 4,4, 300, 0, 100, 100);
//        drawAltDial(vg, 400, 0, 100, 100);
//        drawGrid(vg, 8, 8, 500, 0, 200, 200);
//        drawSin(vg,  500, 0, 200, 200);
//#endif
//
//		nvgEndFrame(vg);

		glfwSwapBuffers(window);
		glfwPollEvents();
	}


	nvgDeleteGL2(vg);
	glfwTerminate();
	return 0;
}
Exemple #30
0
int main (int argc, char **argv) {
  
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL);
  
  windowWidth = 512;
  windowHeight = 512;
  
  zNear = 0.1f;
  zFar = 1000.0f;
  fov = 45.0f;

  glutInitWindowSize (windowWidth, windowHeight);
  glutInitWindowPosition (100, 100);
  glutCreateWindow("Exercise 10");
  
  glutReshapeFunc(resizeGL);
  glutDisplayFunc(updateGL);
  glutIdleFunc(idle);
  glutKeyboardFunc(keyboardEvent);
  glutMouseFunc(mouseEvent);
  glutMotionFunc(mouseMoveEvent);
  
  GLenum err = glewInit();
  if (GLEW_OK != err) {
    fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  }
  fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  
  initGL();
  initFBO();
  initScene();
  
  // this path defines a looped circular curve //
  std::vector<ControlPoint> p;
  p.push_back(ControlPoint( 1.0, 0.0, 0.0, 0.0));
  p.push_back(ControlPoint( 0.7, 0.0, 0.7, 0.5));
  p.push_back(ControlPoint( 0.0, 0.0, 1.0, 1.0));
  p.push_back(ControlPoint(-0.7, 0.0, 0.7, 1.5));
  p.push_back(ControlPoint(-1.0, 0.0, 0.0, 2.0));
  p.push_back(ControlPoint(-0.7, 0.0,-0.7, 2.5));
  p.push_back(ControlPoint( 0.0, 0.0,-1.0, 3.0));
  p.push_back(ControlPoint( 0.7, 0.0,-0.7, 3.5));
  p.push_back(ControlPoint( 1.0, 0.0, 0.0, 4.0));
  
  mPath.setFirstControlPoint(p[p.size() - 2]);
  mPath.setLastControlPoint(p[1]);
  for (unsigned int i = 0; i < p.size(); ++i) {
    mPath.addIntermediateControlPoint(p[i]);
  }
  mPath.setLooped(true);
  // ----------------------------------------- // 

  std::cout << mPath.getPositionForTime(3.999) << std::endl;
  std::cout << mPath.getPositionForTime(4.001) << std::endl;
//  return 0;
  
  glutMainLoop();
  
  delete mNormalMapShader;
  
  return 0;
}