コード例 #1
0
ファイル: main.cpp プロジェクト: TiarnyMN/RealTimePhysics
int main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
	glutInitWindowSize(1280, 720);
	glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH)-1280)/2, (glutGet(GLUT_SCREEN_HEIGHT)-720)/2);
	glutCreateWindow("Real Time Physics - Lab 3 - Broad Phase Collisions - AABB Sweep and Prune");
	//glutGameModeString("1280x720@32");
    //glutEnterGameMode();

	glEnable(GL_DEPTH_TEST);
	//glEnable(GL_LINE_SMOOTH);
	//glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
	//glEnable(GL_POINT_SMOOTH);
	//glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
	
	//glEnable(GL_BLEND);
	//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	//glEnable(GL_MULTISAMPLE);
	//glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);

	InitialiseCallbacks();
	
	GLenum res = glewInit();
    if (res != GLEW_OK)
	{
		fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
		return 1;
    }

	glClearColor(0.3f, 0.3f, 0.3f, 1.0f);

	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);

	InitialiseScene();
	glutMainLoop();
	return 0;
}
コード例 #2
0
ファイル: Renderer.cpp プロジェクト: dmerejkowsky/nao-gm
Renderer::Renderer()
{
	IniReader reader( "common/ini/main.ini" );
	m_bCheckerror = reader.GetInt( "Window", "GLCheckError" ) != 0;

	GLenum err = glewInit();
	CHECK( err == GLEW_OK, "GLEW unable to initialize!" );

	// print info
	/*char buffer[256];
	GetInfo(buffer, sizeof(buffer));
	printf("%s\n", buffer);*/

	ilInit();
	iluInit();
	ilEnable(IL_ORIGIN_SET);
	ilSetInteger(IL_ORIGIN_MODE, IL_ORIGIN_LOWER_LEFT);

	m_shaderProgram = NULL;
}
コード例 #3
0
ファイル: iltest-algo-quant.c プロジェクト: kolrabi/kail
int main(int argc, char **argv) {
  ILuint  image     = 0;
  ILuint  reference = 0;

  // syntax: ILtestAlgoQuant <reference> 
  if (argc < 2) {
    return -1;
  }

  ilInit();
  iluInit();

  ilEnable(IL_ORIGIN_SET);    // flip image on load if necessary
  ilEnable(IL_FILE_MODE);     // overwrite files

  // load reference image
  ilGenImages(1, &reference);
  CHECK(reference != 0);
  CHECK(testLoadImage(argv[1], reference));

  // duplicate
  image = ilCloneCurImage();
  CHECK(image != 0);
  

  // quantize
  ilBindImage(image);
  ilSetInteger(IL_QUANTIZATION_MODE, IL_WU_QUANT);
  ilConvertImage(IL_COLOUR_INDEX, IL_UNSIGNED_BYTE);
  CHECK(testSaveImage("test_quant.png", image));

  // compare two images
  CHECK_GREATER(iluSimilarity(reference), 0.98f);

  // cleanup
  ilDeleteImages(1, &image);  
  ilDeleteImages(1, &reference);  
  ilShutDown();

  return 0;
}
コード例 #4
0
ファイル: DevIL Interface.c プロジェクト: AMDmi3/DevIL
int main(int argc, char *argv[])
{
	int retval;
	int image;

	ilInit();
	iluInit();
	ilutInit();

	ilGenImages(1, &image);
	ilBindImage(image);
	ilOriginFunc(IL_ORIGIN_LOWER_LEFT);

	retval = MLMain(argc, argv);

	ilDeleteImages(1, &image);

	ilShutDown();  // Only need to shut down DevIL, not ILU or ILUT

	return retval;
}
コード例 #5
0
ファイル: main.cpp プロジェクト: TiarnyMN/RealTimePhysics
int main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
	glutInitWindowSize(1280, 720);
	glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH)-1280)/2, (glutGet(GLUT_SCREEN_HEIGHT)-720)/2);
	glutCreateWindow("Real Time Physics - Lab 2 - Rigid Bodies & Springs");

	glEnable(GL_DEPTH_TEST);

	glEnable(GL_LINE_SMOOTH);
	glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
	glEnable(GL_POINT_SMOOTH);
	glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);

	glEnable(GL_MULTISAMPLE);
	glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);

	InitialiseCallbacks();
	
	GLenum res = glewInit();
    if (res != GLEW_OK)
	{
		fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
		return 1;
    }

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

	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);

	InitialiseScene();
	glutMainLoop();
	return 0;
}
コード例 #6
0
ファイル: iltest-io.c プロジェクト: kolrabi/kail
int main(int argc, char **argv) {
  if (argc != 3) {
    return 1;
  }

  ilInit();
  iluInit();

  ilGenImages(1, &image);
  charToILchar(argv[2], fileName, 1024);
  data = argv[2];

  argv++;

  RUN_TEST(open_read)
  RUN_TEST(open_read_lump)
    fprintf(stderr, "unknown test %s\n", *argv);

  ilDeleteImages(1, &image);
  ilShutDown();

  return 0;
}
コード例 #7
0
ファイル: main.cpp プロジェクト: Madsy/NPixel
int main(int argc, char* argv[])
{
	(void)argc;
	(void)argv;
	const int width = 640;
	const int height = 480;
	const int depth = 32;
	Mesh mesh[NUM_MESHES];

	ilInit();
	iluInit();

	//srand(time(NULL));
	perspective(clipMatrix, 60.0f, (float)width/(float)height, 1.0f, 40.0f);

	for(int i = 0; i < NUM_MESHES; ++i) {
		mesh[i].rotationSpeed = rnd_min_max(0.0f, 0.25f);
		mesh[i].position.x = rnd_min_max(-1.0f, 1.0f);
		mesh[i].position.y = rnd_min_max(-1.0f, 1.0f);
		mesh[i].position.z = rnd_min_max(-2.5f, -30.0f);
		mesh[i].position.w = 1.0f;
	}
	SR_Init(width, height);
	SR_SetCaption("Tile-Rasterizer Test");

	const Texture* tex = ReadPNG("texture0.png");
	if(!tex){
		printf("Couldn't find texture0.png, aborting..\n");
		return -1;
	}
	SR_BindTexture0(tex);

	for(int i=0; i<NUM_MESHES; ++i)
		makeMeshCube(mesh[i].vertexData, mesh[i].tcoordData, 1.0f);

	SR_MainLoop(loop, quit, (void*)&mesh[0]);
}
コード例 #8
0
ファイル: main.cpp プロジェクト: Farades/OpenGL_Flag_Effect-
//-----------------------------------------------------------------------------
//Функция инициализации
void init()
{
    //Инициализация DevIL
    ilInit();
    iluInit();
    ilutInit();

    Load_Tex_Image();

    glEnable(GL_TEXTURE_2D);
    glViewport( 0, 0, WinWidth, WinHeight );
    glClearColor(0.9f, 0.9f, 0.9f, 0.0f);
    glClearDepth(1.0);
    glDepthFunc(GL_LESS);
    glEnable(GL_DEPTH_TEST);
    glShadeModel(GL_SMOOTH);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective( 45.0f, (GLfloat)WinWidth/(GLfloat)WinHeight, 0.1f, 100.0f );
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

//    glPolygonMode( GL_BACK, GL_FILL );       // нижняя (задняя) сторона заполнена
//    glPolygonMode( GL_FRONT, GL_LINE );      // верхняя (передняя) сторона прорисована линиями

    for(int x=0; x<45; x++)
    {
        for(int y=0; y<45; y++)
        {
            // применим волну к нашей сетке
            points[x][y][0]=float((x/5.0f)-4.5f);
            points[x][y][1]=float((y/5.0f)-4.5f);
            points[x][y][2]=float(sin((((x/5.0f)*40.0f)/360.0f)*3.141592654*2.0f));
        }
    }
}
コード例 #9
0
ファイル: application.cpp プロジェクト: foxostro/arbarlith2
void Application::startDevIL()
{
	TRACE("Initializing DevIL...");

	TRACE("Linked against IL with IL_VERSION of " + itoa(IL_VERSION));
	TRACE("Linked against ILU with ILU_VERSION of " + itoa(ILU_VERSION));
	TRACE("Linked against ILUT with ILUT_VERSION of " + itoa(ILUT_VERSION));

	// First, check the DevIL image library's version
	if(ilGetInteger(IL_VERSION_NUM) < IL_VERSION)
	{
		FAIL("IL_VERSION_NUM is different than expected!");
	}

	if(ilGetInteger(ILU_VERSION_NUM) < ILU_VERSION)
	{
		FAIL("ILU_VERSION_NUM is different than expected!");
	}

	if(ilGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
	{
		FAIL("ILUT_VERSION_NUM is different than expected!");
	}

	/*
	Then, Initialize the DevIL image library
	The docs say this step isn't necessary as long as we use a shared
	library when linking to DevIL.  However, it suggests we do it anyway
	to ease a few sorts of particular problems.
	*/
	ilInit();
	iluInit();
	ilutInit();

	TRACE("...DevIL initialized successfully");
}
コード例 #10
0
ファイル: main.cpp プロジェクト: Jing-Qiu/JelloDemo
int main(int argc, char **argv)
{
	if (argc != 2)
	{
		cout << "No configuration file" << endl;
		system("pause");
		return 1;
	}

    ilInit();
    iluInit();
    ilEnable(IL_FILE_OVERWRITE);
    ilutRenderer(ILUT_OPENGL);

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowSize(640, 480);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("JelloSim by AlineN");
    glutDisplayFunc(onDrawCb);
    glutKeyboardFunc(onKeyboardCb);
    glutSpecialFunc(onKeyboardSpecialCb);
    glutMouseFunc(onMouseCb);
    glutMotionFunc(onMouseMotionCb); 
    glutTimerFunc(100, onTimerCb, 0);
    glutReshapeFunc(onResizeCb);

    int intMenu = glutCreateMenu(onMenuCb);
    glutAddMenuEntry("Euler\t'8'", '8');
    glutAddMenuEntry("Midpoint\t'9'", '9');
    glutAddMenuEntry("RK4\t'0'", '0');

    int displayMenu = glutCreateMenu(onMenuCb);
    glutAddMenuEntry("Mesh\t'1'", '1');
    glutAddMenuEntry("Forces\t'2'", '2');
    glutAddMenuEntry("Collision Normals\t'3'", '3');
    glutAddMenuEntry("Structural Springs\t'4'", '4');
    glutAddMenuEntry("Shear Springs\t'5'", '5');
    glutAddMenuEntry("Bend Springs\t'6'", '6');

    theMenu = glutCreateMenu(onMenuCb);
    glutAddMenuEntry("Start\t'>'", '>');
    glutAddMenuEntry("Pause\t'='", '=');
    glutAddMenuEntry("Reset\t'<'", '<');
    glutAddMenuEntry("Record\t'r'", 'r');
    glutAddSubMenu("Integration Type", intMenu);
    glutAddSubMenu("Draw Settings", displayMenu);
    glutAddMenuEntry("_________________", -1);
    glutAddMenuEntry("Exit", 27);
    glutAttachMenu(GLUT_RIGHT_BUTTON);

	init();
	if (loadJelloParameters(argv[1]) != 0)
	{
		cout << "Failed to open configuration file" << endl;
		system("pause");
		return 1;
	}

    glutMainLoop();
    return 0;             
}
コード例 #11
0
int main()
{
	if (!glfwInit())
		exit(EXIT_FAILURE);
	if (!glfwOpenWindow(screenWidth, screenHeight, 0, 0, 0, 0, 0, 0, GLFW_WINDOW))
	{
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	glfwSetWindowTitle("Example Program: Craig McMillan 10004794 ");
	GLenum error = glewInit();
	if (error != GLEW_OK)
	{
		std::cout << "Error: " << glewGetErrorString(error) <<std::endl;
		exit(EXIT_FAILURE);
	}

	const GLubyte* renderer = glGetString(GL_RENDERER);
	const GLubyte* vendor = glGetString(GL_VENDOR);
	const GLubyte* version = glGetString(GL_VERSION);
	const GLubyte* glslVersion = glGetString(GL_SHADING_LANGUAGE_VERSION);
	GLint major , minor;
	glGetIntegerv(GL_MAJOR_VERSION, &major);
	glGetIntegerv(GL_MINOR_VERSION, &minor);
	printf("GL VENDOR : %s\n", vendor);
	printf("GL Renderer : %s\n", renderer);
	printf("GL Version (string) : %s\n", version);
	printf("GL Version (integer) : %d.%d\n", major, minor);
	printf("GLSL version : %s\n", glslVersion);

	ilInit();
	iluInit();
	ilutRenderer(ILUT_OPENGL);

	initialise();

	double prevTimeStamp = glfwGetTime();
	double lastFPS = glfwGetTime();
	double currentTimeStamp;
	int nbFrames = 0;
	while (running)
	{
		currentTimeStamp = glfwGetTime();
		//calculate frame rate
		nbFrames++;
		update(currentTimeStamp - prevTimeStamp);
		if (currentTimeStamp - lastFPS >= 1.0)
		{			
			printf("%f ms/frame\n", double(nbFrames));
			nbFrames = 0;
			lastFPS += 1.0;
		}
		render();
		prevTimeStamp = currentTimeStamp;
	} 

	cleanup();

	glfwTerminate();

	exit(EXIT_SUCCESS);

}
コード例 #12
0
ファイル: TextureControl.cpp プロジェクト: MonoS/GlossTech
int TextureControl::InitImageLibrary() {
	ilInit();
	iluInit();
	ilutRenderer(ILUT_WIN32);
	return 0;
}
コード例 #13
0
ファイル: WindowsTest.cpp プロジェクト: AMDmi3/DevIL
int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	MSG			msg;
	WNDCLASSEX	wcex;
	HACCEL		hAccelTable;

	hInstance = hInst;
	memset(OpenFileName, 0, 2048 * sizeof(TCHAR));

	BackBrush = CreateSolidBrush(RGB(128,128,128));

	wcex.cbSize			= sizeof(WNDCLASSEX);
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= BackBrush;
	wcex.lpszMenuName	= (LPCWSTR)IDR_MENU1; //@TODO: (LPCSTR)IDR_MENU1;
	wcex.lpszClassName	= TITLE;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, (LPCTSTR)IDI_ICON1);

	RegisterClassEx(&wcex);

	HWnd = CreateWindow(TITLE, TITLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE,
						50, 50, 400, 300, NULL, NULL, hInstance, NULL);
	if (HWnd == NULL)
		return FALSE;

	//if (SDL_Init(SDL_INIT_TIMER) < 0)
	//	return FALSE;
	//atexit(SDL_Quit);

	// Display the window
	ShowWindow(HWnd, nCmdShow);
	UpdateWindow(HWnd);

	// Initialize DevIL
	ilInit();
	iluInit();
	ilutRenderer(ILUT_WIN32);

	// Is there a file to load from the command-line?
	if (__argc > 1) {
		ilGenImages(1, Undos);
		ilBindImage(Undos[0]);
		/*if (ilLoadImage(__argv[1])) {
			CurImage = 0;
			//ilConvertImage(IL_BGRA);
			ilutRenderer(ILUT_WIN32);
			ResizeWin();
			CreateGDI();
			sprintf(NewTitle, "%s - %s", TITLE, __argv[1]);
			SetWindowText(HWnd, NewTitle);
		}*/
	}

	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDR_MENU1);

	while (GetMessage(&msg, NULL, 0, 0)) {
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

#ifdef _DEBUG
	_CrtDumpMemoryLeaks();
#endif

	return (int)msg.wParam;
}
コード例 #14
0
ファイル: view.cpp プロジェクト: nobbk/copo
/// render
void view::render() {

	// Clear Screen And Depth Buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);

	if (!m_world) {
		return;
	}

	if(ortho_sh)
	{
		glClearColor(0,0,0,1);
		modifiedmesh_drawable->set_render_faces(true);
		modifiedmesh_drawable->set_render_edges(false);
		modifiedmesh_drawable->set_render_normals(false);
		modifiedmesh_drawable->set_render_vertices(false);
		modifiedmesh_drawable->render();
		glFlush();
		int size = w()*h()*3;

		unsigned char *data = new unsigned char[size];
		glReadPixels(0,0, w(), h(),GL_RGB,GL_UNSIGNED_BYTE,data);

		ilInit();
		iluInit();
		ilutInit();

		ILuint ImageName;
		ilGenImages(1, &ImageName);
		ilBindImage(ImageName);
		ilTexImage(w(),h(),1,3,IL_RGB,IL_UNSIGNED_BYTE,data);

		//iluFlipImage();
		ilEnable(IL_FILE_OVERWRITE);

#ifdef _WIN32
		// Did not compile in linux:
		ilSaveImage(reinterpret_cast<const wchar_t *>(filename_screenshot.c_str()));
#else
		ilSaveImage(filename_screenshot.c_str());
#endif

		delete[] data;
		glClearColor(0.80f, 0.80f, 0.90f, 1.0f);
	}
	else
	{
		// Reset Modelview:
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glEnable(GL_BLEND);
		glEnable(GL_DEPTH_TEST);

		// Set modelviewmatrix
		m =	translate_44(0.0f, 0.0f, -cam_distance)
				* rotate_x_44(cam_polar)
				* rotate_y_44(cam_azimut)
				* translate_44(-cam_target.x(), -cam_target.y(), -cam_target.z() );

		// Transpose (here: invert) matrix:
		Mat44f mat_trans = transpose(m);

		point3f camera_pos(0.0, 0.0, 0.0);
		camera_pos = invert(m) * camera_pos;

		glLoadMatrixf( &mat_trans(0,0) );

		// Create light components
		GLfloat ambientLight[]	= { 0.0f, 0.0f, 0.0f, 1.0f };
		GLfloat diffuseLight[]	= { 1.0f, 1.0f, 1.0f, 1.0f };
		GLfloat specularLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };
		GLfloat position[]		= { 1.0f, 1.0f, 1.0f, 0.0f };

		GLfloat globalAmbient[] = { 0.2f, 0.2f, 0.2f, 1.0f};
		glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbient);

		// Assign created components to GL_LIGHT1
		glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
		glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
		glLightfv(GL_LIGHT0, GL_POSITION, position);

		Rendering::RenderingInfo info( camera_pos, m_noise_tex );

		/* render the world */
		m_world->render( info );

		renderCoordinateSystem();

		//render_noise_texture();
	}
}
コード例 #15
0
ファイル: ILUTest.cpp プロジェクト: AMDmi3/DevIL
void ILUTest::setUp()
{
  ilInit();
  iluInit();
}
コード例 #16
0
ファイル: Main.cpp プロジェクト: EricLemieux/Robopocalypse
int main()
{
	//Init the game
	Game *Robopocalypse = new Game;

	//Open a window for the game
	Robopocalypse->OpenWindow(1280, 720);

	//Init GLEW
	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (err != GLEW_OK)
		std::cout << "glewInit() Error\n";

	//Init DevIL
	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);
	
	//Init OpenGL
	initOpenGL();

	//Load a blank image into spot #1 using this for objects that dont have a normal map, there is probably a way better way of doing this...
	loadTexture("Resources/NormalMaps/blank.png");

	//Robopocalypse->initGameplay();
	Robopocalypse->initMainMenu();

	//Set the time to zero before running the game loop so we know it starts from scratch.
	glfwSetTime(0.0f);

	float deltaTime		= 0.0f;
	double timeOfLastUpdate	= 0.0f;

	//While the window is open run the game
	while (Robopocalypse->GetIfRunning())
	{
		//Update the deltaTime
		deltaTime = glfwGetTime() - timeOfLastUpdate;

		//Makes sure there has been enough time between updates before rendering to the screen.
		if (deltaTime >= FPS_REFRESH_CAP)
		{
			if (Robopocalypse->GetState() == STATE_GAMEPLAY)
			{
				Robopocalypse->Update();
				Robopocalypse->Render();
			}
			else if (Robopocalypse->GetState() == STATE_MAINMENU)
			{
				Robopocalypse->GetMenu()->Update(Robopocalypse);
				Robopocalypse->GetMenu()->Render();
			}

			//Reset the time between updates
			deltaTime			= 0.0f;
			timeOfLastUpdate	= glfwGetTime();
		}		
	}
	
	//Shutdown gldw
	glfwTerminate();

	//End the program
	return 0;
}
コード例 #17
0
ファイル: WebMEnc.cpp プロジェクト: langazov/WebMEnc
int main(int argc, char* argv[])
{
	if (argc != 7)
	{
		fprintf(stderr, "  Usage: WebMEnc <input filename> <flip> <threads> <bit-rates> <frame-per-second> <output filename>\nExample: WebMEnc frame.%%.5d.tiff 1 8 512 30 frame.webm\n");
		return EXIT_FAILURE;
	}

	ilInit();
	iluInit();

	// Initialize VPX codec.
	//
	vpx_codec_ctx_t vpxContext;
	vpx_codec_enc_cfg_t vpxConfig;

    if (vpx_codec_enc_config_default(vpx_codec_vp8_cx(), &vpxConfig, 0) != VPX_CODEC_OK)
	{
        return EXIT_FAILURE;
    }

	// Try to load the first frame to initialize width and height.
	//
	int flip = (bool)atoi(argv[2]);

	vpx_image_t *rgbImage = NULL, *yv12Image = NULL;
	if (readImage(argv[1], 0, &rgbImage, &yv12Image, flip) == false)
	{
		return EXIT_FAILURE;
	}
	vpxConfig.g_h = yv12Image->h;
	vpxConfig.g_w = yv12Image->w;

	vpxConfig.g_threads = atoi(argv[3]);

	vpxConfig.rc_target_bitrate = atoi(argv[4]);

	vpxConfig.g_timebase.den = atoi(argv[5]);
	vpxConfig.g_timebase.num = 1;

	// Prepare the output .webm file.
	//
	EbmlGlobal ebml;
	memset(&ebml, 0, sizeof(EbmlGlobal));
	ebml.last_pts_ms = -1;
	ebml.stream = fopen(argv[6], "wb");
	if (ebml.stream == NULL)
	{
		return EXIT_FAILURE;
	}
	vpx_rational ebmlFPS = vpxConfig.g_timebase;
	struct vpx_rational arg_framerate = {atoi(argv[5]), 1};
	Ebml_WriteWebMFileHeader(&ebml, &vpxConfig, &arg_framerate);

	unsigned long duration = (float)arg_framerate.den / (float)arg_framerate.num * 1000;

	if (vpx_codec_enc_init(&vpxContext, vpx_codec_vp8_cx(), &vpxConfig, 0) != VPX_CODEC_OK)
	{
        return EXIT_FAILURE;
    }

	//
	fprintf(stdout, "input=%s\nflip=%s\nthreads=%s\nbps=%s\nfps=%s\noutput=%s\n", argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);

	
	// Reading image file sequence, encoding to .WebM file.
	//
	int frameNumber = 0;
	while(readImage(argv[1], frameNumber, &rgbImage, &yv12Image, flip))
	{
		vpx_codec_err_t vpxError = vpx_codec_encode(&vpxContext, yv12Image, frameNumber, duration, 0, 0);
		if (vpxError != VPX_CODEC_OK)
		{
			return EXIT_FAILURE;
		}
		
		vpx_codec_iter_t iter = NULL;
		const vpx_codec_cx_pkt_t *packet;
		while( (packet = vpx_codec_get_cx_data(&vpxContext, &iter)) )
		{
			Ebml_WriteWebMBlock(&ebml, &vpxConfig, packet);
		}

		frameNumber ++;
		printf("Processed %d frames.\r", frameNumber);

		vpx_img_free(yv12Image);
		yv12Image = NULL;
	}

	Ebml_WriteWebMFileFooter(&ebml, 0);
	fclose(ebml.stream);

	vpx_codec_destroy(&vpxContext);

	return EXIT_SUCCESS;
}
コード例 #18
0
bool initGL()
{
    //Initialize GLEW
    GLenum glewError = glewInit();
    if( glewError != GLEW_OK )
    {
        printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
        return false;
    }

    //Make sure OpenGL 2.1 is supported
    if( !GLEW_VERSION_2_1 )
    {
        printf( "OpenGL 2.1 not supported!\n" );
        return false;
    }

    //Set the viewport
    glViewport( 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT );

    //Initialize Projection Matrix
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho( 0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 1.0, -1.0 );

    //Initialize Modelview Matrix
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    //Initialize clear color
    glClearColor( 0.f, 0.f, 0.f, 1.f );

    //Enable texturing
    glEnable( GL_TEXTURE_2D );

    //Set blending
    glEnable( GL_BLEND );
    glDisable( GL_DEPTH_TEST );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

    //Check for error
    GLenum error = glGetError();
    if( error != GL_NO_ERROR )
    {
        printf( "Error initializing OpenGL! %s\n", gluErrorString( error ) );
        return false;
    }

    //Initialize DevIL and DevILU
    ilInit();
    iluInit();
    ilClearColour( 255, 255, 255, 000 );

    //Check for error
    ILenum ilError = ilGetError();
    if( ilError != IL_NO_ERROR )
    {
        printf( "Error initializing DevIL! %s\n", iluErrorString( ilError ) );
        return false;
    }

    return true;
}
コード例 #19
0
ファイル: simple.c プロジェクト: AMDmi3/DevIL
int main(int argc, char **argv)
{
	ILuint	ImgId;
	ILenum	Error;

	// We use the filename specified in the first argument of the command-line.
	if (argc < 2) {
		fprintf(stderr, "DevIL_test : DevIL simple command line application.\n");
		fprintf(stderr, "Usage : DevIL_test <file> [output]\n");
		fprintf(stderr, "Default output is test.tga\n");
		return 1;
	}

	// Check if the shared lib's version matches the executable's version.
	if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION) {
		printf("DevIL version is different...exiting!\n");
		return 2;
	}

	// Initialize DevIL.
	ilInit();
#ifdef ILU_ENABLED
	iluInit();
#endif 

	// Generate the main image name to use.
	ilGenImages(1, &ImgId);

	// Bind this image name.
	ilBindImage(ImgId);

	// Loads the image specified by File into the image named by ImgId.
	if (!ilLoadImage(argv[1])) {
		printf("Could not open file...exiting.\n");
		return 3;
	}

	// Display the image's dimensions to the end user.
	printf("Width: %d  Height: %d  Depth: %d  Bpp: %d\n",
	       ilGetInteger(IL_IMAGE_WIDTH),
	       ilGetInteger(IL_IMAGE_HEIGHT),
	       ilGetInteger(IL_IMAGE_DEPTH),
	       ilGetInteger(IL_IMAGE_BITS_PER_PIXEL));

	// Enable this to let us overwrite the destination file if it already exists.
	ilEnable(IL_FILE_OVERWRITE);

	// If argv[2] is present, we save to this filename, else we save to test.tga.
	if (argc > 2)
		ilSaveImage(argv[2]);
	else
		ilSaveImage("test.tga");

	// We're done with the image, so let's delete it.
	ilDeleteImages(1, &ImgId);

	// Simple Error detection loop that displays the Error to the user in a human-readable form.
	while ((Error = ilGetError())) {
		PRINT_ERROR_MACRO;}

	return 0;

}
コード例 #20
0
ファイル: engine.cpp プロジェクト: gladky/Four-stroke-engine
/* inicjuje 
 * -oswietlenie
 * -cieniowanie
 * -biblioteke glut
 * -wspolprace z systemem okienkowym
 */
void init()
{   
   GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		std::cout << "GLEW initialisation error: " << glewGetErrorString(err) << std::endl;
		exit(-1);
	}
	std::cout << "GLEW intialised successfully. Using GLEW version: " << glewGetString(GLEW_VERSION) << std::endl;
 


    GLfloat mat_ambient[]    = { 1.0, 1.0,  1.0, 1.0 };
	GLfloat mat_diffuse[]    = { 0.5, 0.5,  0.5, 1.0 };
    GLfloat mat_specular[]   = { 1.0, 1.0,  1.0, 1.0 };
    GLfloat light1_position[] = { 10.0,		5.0,	10.0,	1.0 };
	GLfloat light2_position[] = { -10.0,	10.0,	-10.0,	1.0 };
	GLfloat light3_position[] = { 10.0,		10.0,	-10.0,	1.0 };
	GLfloat light4_position[] = { -10.0,	10.0,	10.0,	1.0 };
    GLfloat lm_ambient[]     = { 0.2, 0.2,  0.2, 1.0 };

    glMaterialfv( GL_FRONT, GL_AMBIENT, mat_ambient );
    glMaterialfv( GL_FRONT, GL_SPECULAR, mat_specular );
    glMaterialf( GL_FRONT, GL_SHININESS, 50.0 );
    glLightfv( GL_LIGHT0, GL_POSITION, light1_position );
		glLightfv( GL_LIGHT1, GL_POSITION, light2_position );
		glLightfv(GL_LIGHT1, GL_DIFFUSE, mat_diffuse);
		glLightfv( GL_LIGHT2, GL_POSITION, light3_position );
		glLightfv(GL_LIGHT2, GL_DIFFUSE, mat_diffuse);
		glLightfv( GL_LIGHT3, GL_POSITION, light4_position );
		glLightfv(GL_LIGHT3, GL_DIFFUSE, mat_diffuse);
    glLightModelfv( GL_LIGHT_MODEL_AMBIENT, lm_ambient );
    
	glEnable(GL_NORMALIZE);

    glShadeModel( GL_SMOOTH );													// obliczanie swiatla 
	
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );
	glEnable( GL_LIGHT1 );
	glEnable( GL_LIGHT2 );
	glEnable( GL_LIGHT3 );

    glDepthFunc( GL_LESS );
    glEnable( GL_DEPTH_TEST );
	//glBlendFunc (GL_SRC_ALPHA, GL_ONE);


	// DevIL sanity check
	if ( (iluGetInteger(IL_VERSION_NUM) < IL_VERSION) || (iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION) || (ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION) )
	{
		std::cout << "DevIL versions are different... Exiting." << std::endl;
		exit(-1);
	}
	

	// Initialise all DevIL functionality
	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);	// Tell DevIL that we're using OpenGL for our rendering

}
コード例 #21
0
ファイル: textureatlas.cpp プロジェクト: Domix24/Cube
bool TextureAtlas::Generate(int textureSize, bool mipmap)
{
	// TODO mipmap pas encore 100% parfait...
	assert(!mipmap);

	if (!IsPowerOfTwo(textureSize))
		return false;

	// Initialize Devil only once:
	static bool alreadyInitialized = false;
	if (!alreadyInitialized)
	{
		ilInit();
		iluInit();
		alreadyInitialized = true;
	}

	for (TextureList::iterator it = m_textureList.begin(); it != m_textureList.end(); ++it)
	{
		ILuint texid = it->second.texId;
		if (texid == (ILuint)-1)
		{
			std::cout << "Loading " << it->first << " (id=" << it->second.texIdx << ")..." << std::endl;
			ilGenImages(1, &texid);
			ilBindImage(texid);

			ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
			ilEnable(IL_ORIGIN_SET);

			if (!ilLoadImage((const ILstring)it->first.c_str()))
				return false;

			if (!ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE))
				return false;

			iluScale(textureSize, textureSize, 1);

			it->second.texId = texid;
		}
	}


	//std::cout << ilGetInteger(IL_IMAGE_BPP) << std::endl;
	//std::cout << ilGetInteger(IL_IMAGE_FORMAT) << std::endl;
	//std::cout << ilGetInteger(IL_IMAGE_DEPTH) << std::endl;
	//std::cout << ilGetInteger(IL_IMAGE_TYPE) << std::endl;
	//std::cout << ilGetInteger(IL_IMAGE_WIDTH) << std::endl;
	//std::cout << ilGetInteger(IL_IMAGE_HEIGHT) << std::endl;



	glGenTextures(1, &m_textureId);
	glBindTexture(GL_TEXTURE_2D, m_textureId);
	if (mipmap)
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	}
	else
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	}
	
	int level = textureSize;
	int oglLevel = 0;
	int mipmapSize = textureSize * m_nbTexturePerSide;
	while (mipmapSize != 0)
	{
		ILuint atlasTex;
		ilGenImages(1, &atlasTex);
		ilBindImage(atlasTex);
		ilTexImage(mipmapSize, mipmapSize, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, 0);
		ilClearColour(1, 0, 0, 1);
		ilClearImage();

		for (TextureList::iterator it = m_textureList.begin(); it != m_textureList.end(); ++it)
		{
			ILuint tmpImg;
			ilGenImages(1, &tmpImg);
			ilBindImage(tmpImg);
			ilCopyImage(it->second.texId);

			iluImageParameter(ILU_FILTER, ILU_NEAREST);
			//iluImageParameter(ILU_FILTER, ILU_BILINEAR);
			if (level != textureSize)
				iluScale(level, level, 1);

			char* data = new char[level * level * 4];
			ilCopyPixels(0, 0, 0, level, level, 1, IL_RGBA, IL_UNSIGNED_BYTE, data);


			int imgIdx = it->second.texIdx;
			int x = imgIdx % m_nbTexturePerSide;
			int y = m_nbTexturePerSide - 1 - imgIdx / m_nbTexturePerSide;
			ilBindImage(atlasTex);
			ilSetPixels(x * level, y * level, 0, level, level, 1, IL_RGBA, IL_UNSIGNED_BYTE, data);
			//ilOverlayImage(tmpImg, x * level, y * level, 0);

			delete[] data;
			ilDeleteImages(1, &tmpImg);
		}

		// TODO
		//if(level == textureSize)
		//{
		//ilEnable(IL_FILE_OVERWRITE);
		//ilSaveImage("textureatlas.png");
		//}

		//std::cout << oglLevel << ":" << level << ":" << mipmapSize << std::endl;
		glTexImage2D(GL_TEXTURE_2D, oglLevel++, GL_RGBA, ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, GL_RGBA, GL_UNSIGNED_BYTE, ilGetData());

		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP);
		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
		CHECK_GL_ERROR();


		ilDeleteImages(1, &atlasTex);

		if (!mipmap)
			break;

		level /= 2;
		mipmapSize /= 2;
	}

	m_isValid = true;
	return true;
}
コード例 #22
0
ファイル: main.cpp プロジェクト: c-day/Warp
int main(int argc, char * argv[])
{
	glutInit(&argc , argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
	glutInitWindowPosition(0 , 0);
	glutInitWindowSize(window_width, window_height);
	glutCreateWindow("Warp");
	glutDisplayFunc(DisplayFunc);
	glutTimerFunc(1000 / 60, TimerFunc, 1000 / 60);
	glutReshapeFunc(ReshapeFunc);
	glutSpecialFunc(SpecialFunc);
	glutKeyboardFunc(KeyboardFunc);
	glutMouseFunc(MouseFunc);
	glutMotionFunc(MotionFunc);
	glutCloseFunc(CloseFunc);
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
	glEnable(GL_DEPTH_TEST);

	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);

	if (glewInit() != GLEW_OK)
	{
		cerr << "GLEW failed to initialize." << endl;
		return 0;
	}
			
	if (!shader.Initialize("stub.vert", "stub.frag"))
	{
		return 0;
	}

	if (!background.Initialize("back.vert", "back.frag"))
	{
		return 0;
	}


	image_1_handle = ilutGLLoadImage("lotr-scene.jpg");
	image_1_w = ilGetInteger(IL_IMAGE_WIDTH);
	image_1_h = ilGetInteger(IL_IMAGE_HEIGHT);
	
	tex_handle = ilutGLLoadImage("Home-Theater.jpg");
	tex_w = ilGetInteger(IL_IMAGE_WIDTH);
	tex_h = ilGetInteger(IL_IMAGE_HEIGHT);

	left_overlay_handle = ilutGLLoadImage("left-over.jpg");
	right_overlay_handle = ilutGLLoadImage("right-over.jpg");
	left_curtain_handle = ilutGLLoadImage("left-curtain.jpg");

	cout << "Image 1: " << image_1_w << " x " << image_1_h << endl;
	cout << "Background: " << tex_w << " x " << tex_h << endl;
	
	if (!frame.Initialize(glm::ivec2(image_1_w, image_1_h), 1, true))
	{
		cerr << "Frame buffer 1 failed to initialize." << endl;
		return 0;
	}

	cout << "Window Size: " << window_width << " x " << window_height << endl;
	cout << "Frame buffer 1 size: " << frame.size.x << " x " << frame.size.y << endl;

	glutMainLoop();
	return 0;
}
コード例 #23
0
//Load----------------------------------------------------------------------
bool TextureItem::Load( GLuint minFilter, GLuint maxFilter, bool forceMipmap, bool resizeIfNeeded )
{
    /** NOTE: This is a test of using an archive file.  This will need to
        be modified to allow direct file access, or archived file access.
    */
    ArchiveFile* file = ArchiveManager::GetSingleton().CreateArchiveFile( mImageFileName );
    if ( file )
    {
        UInt32 fileSize = file->Length();
        unsigned char* buf = new unsigned char [ fileSize ];
        if ( !buf )
        {
            delete file;
            return false;
        }
        file->Read( buf, fileSize );

        // Load the texture:

        //****
        ilInit();
        iluInit();

        // Make sure the DevIL version is valid:
        if ( ilGetInteger( IL_VERSION_NUM ) < IL_VERSION || iluGetInteger( ILU_VERSION_NUM ) < ILU_VERSION )
        {
            // Invalid version...
            delete file;
            delete buf;
            return false;
        }


        // Get the decompressed data
        ILuint imageID;
        ilGenImages( 1, &imageID );
        ilBindImage( imageID );
        //if ( ilLoadImage( const_cast< char* >( mImageFileName.c_str() ) ) )
        if ( ilLoadL( IL_TYPE_UNKNOWN, buf, fileSize ) )
        {
            // Convert the image to unsigned bytes:
            ilConvertImage( IL_RGBA, IL_UNSIGNED_BYTE );

            // Generate the GL texture
            glGenTextures( 1, &mTextureID );
            glBindTexture( GL_TEXTURE_2D, mTextureID );
            mWidth  = ilGetInteger( IL_IMAGE_WIDTH );
            mHeight = ilGetInteger( IL_IMAGE_HEIGHT );
            mOriginalWidth  = mWidth;
            mOriginalHeight = mHeight;

            // OpenGL will work better with textures that have dimensions
            // that are a power of 2.  If doing a scrolling tile map, then
            // this is pretty much a necessity.  However, there are times
            // when using a mipmap instead is perfectly fine (ie, when NOT
            // doing tiles, or in cases where we might be running out of
            // video memory...
            if ( resizeIfNeeded && !forceMipmap )
            {
                UInt32 newWidth = mWidth, newHeight = mHeight;
                if ( !Math::IsPowerOf2( mWidth ) )
                {
                    // Find the next power of 2:
                    newWidth = Math::FindNextPowerOf2( mWidth );
                }

                if ( !Math::IsPowerOf2( mHeight ) )
                {
                    // Find the next power of 2:
                    newHeight = Math::FindNextPowerOf2( mHeight );
                }

                if ( newWidth != mWidth || newHeight != mHeight )
                {
                    // Resize the canvas:
                    ilClearColor( 0, 0, 0, 0 );
                    iluImageParameter( ILU_PLACEMENT, ILU_UPPER_LEFT );
                    iluEnlargeCanvas( newWidth, newHeight, ilGetInteger( IL_IMAGE_DEPTH ) );
                    mWidth  = ilGetInteger( IL_IMAGE_WIDTH );
                    mHeight = ilGetInteger( IL_IMAGE_HEIGHT );
                }
            }

            // If forcing mipmap generation, or if the size is not a power of 2,
            // generate as mipmaps
            if ( forceMipmap || !Math::IsPowerOf2( mWidth ) || !Math::IsPowerOf2( mHeight ) )
            {
                gluBuild2DMipmaps( GL_TEXTURE_2D,
                                   ilGetInteger( IL_IMAGE_BPP ),
                                   mWidth,
                                   mHeight,
                                   ilGetInteger( IL_IMAGE_FORMAT ),
                                   GL_UNSIGNED_BYTE,
                                   ilGetData() );
            }
            else
            {
                glTexImage2D(   GL_TEXTURE_2D,
                                0,
                                ilGetInteger( IL_IMAGE_BPP ),
                                mWidth,
                                mHeight,
                                0,
                                ilGetInteger( IL_IMAGE_FORMAT ),
                                GL_UNSIGNED_BYTE,
                                ilGetData() );
            }

            // Set the minification and magnification filters
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, maxFilter );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );

            mIsLoaded = true;
        }
        else
        {
            ILenum error;
            error = ilGetError();
            //std::string errString = iluErrorString( error );
        }

        ilDeleteImages( 1, &imageID );

        //***

        // Free memory:
        delete buf;
        delete file;
    }
    else
        return false;

    return true;
}
コード例 #24
0
/* Program entry point */
int 
main(int argc, char *argv[])
{

    glutInit(&argc, argv);
    glutInitWindowSize(winWidth,winHeight);
    glutInitWindowPosition(300,50);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
    glutCreateWindow("Turmites v01    ----     Martin Johansson");

	// Parse settings file
	std::ifstream file_settings("settings.txt");
	if(file_settings.is_open()) {
		std::cout << "Successfully opened settings.txt" << std::endl;
	}
	if( !file_settings.is_open() ) {
		file_settings.open("../settings.txt");
	}
	if(file_settings.is_open()) {
		std::cout << "Successfully opened settings.txt in down folder" << std::endl;
	}

	std::string str;
	std::vector<int> v;

	// Debug
	
	// Get map size and boarder settings
	while(std::getline(file_settings, str)) {
		std::istringstream iss(str);
		int n;	
		while (iss >> n)
			v.push_back(n);
	}

	// Validate input
	if(v.size() != 3 || v[0] < 2 || v[1] < 2 || v[2]<0 || v[2]>1) {
		printf("Error reading settings file");
		return EXIT_FAILURE;	
	}
	
	// Create the turmite on the specified map size
	turmite.reset(new Turmite(v[0], v[1]));
	
	// Set boundary condition
	turmite->toroidalWalk = v[2];
	
	bool success = turmite->readInput();
	if(!success) {
		printf("Error loading input file.");
		return EXIT_FAILURE;
	}

	//callbacks
	glutDisplayFunc(draw);
	glutReshapeFunc(changeSize);
	glutCreateMenu(timer);
		glutAddMenuEntry("Fastest",   1);
		glutAddMenuEntry("2 ms delay",   2);
		glutAddMenuEntry("10 ms delay",   10);
		glutAddMenuEntry("100 ms delay",   100);
		glutAddMenuEntry("Slowest",  1000);
	glutAttachMenu(GLUT_RIGHT_BUTTON);

	 // Setup keyboard
	glutKeyboardFunc(keyboard);

    ilInit();  
    iluInit();      
    ilutRenderer(ILUT_OPENGL);                  		

	Viewer::init(winWidth,winHeight);

    glutMainLoop();


    return EXIT_SUCCESS;
}
コード例 #25
0
int main(int argc, char *argv[])
{
    e_epiphany_t Epiphany, *pEpiphany;
    e_mem_t      DRAM,     *pDRAM;
    unsigned int msize;
    int          row, col, cnum;



    ILuint  ImgId;
//	ILenum  Error;
    ILubyte *imdata;
    ILuint  imsize, imBpp;



    unsigned int addr;
    size_t sz;
    struct timespec timer[4];
    uint32_t time_p[TIMERS];
    uint32_t time_d[TIMERS];
    FILE *fo;
//	FILE *fi;
    int  result;


    pEpiphany = &Epiphany;
    pDRAM     = &DRAM;
    msize     = 0x00400000;

    //get_args(argc, argv);
    strcpy(ar.ifname,argv[1]);
    strcpy(ar.elfFile,argv[2]);
    strcpy(ar.ofname, ar.ifname);
    printf("------------------------------------------------------------\n");
    fo = fopen("matprt.m", "w");
    if ((fo == NULL)) // || (fi == NULL))
    {
        fprintf(stderr, "Could not open Octave file \"%s\" ...exiting.\n", "matprt.m");
        exit(4);
    }
//	fo = stderr;


    // Connect to device for communicating with the Epiphany system
    // Prepare device
    e_set_host_verbosity(ar.verbose);
    e_init(NULL);
    e_reset_system();
    e_get_platform_info(&platform);
    if (e_open(pEpiphany, 0, 0, platform.rows, platform.cols))
    {
        fprintf(fo, "\nERROR: Can't establish connection to Epiphany device!\n\n");
        exit(1);
    }
    if (e_alloc(pDRAM, 0x00000000, msize))
    {
        fprintf(fo, "\nERROR: Can't allocate Epiphany DRAM!\n\n");
        exit(1);
    }

    // Initialize Epiphany "Ready" state
    addr = offsetof(shared_buf_t, core.ready);
    Mailbox.core.ready = 0;
    e_write(pDRAM, 0, 0, addr, (void *) &(Mailbox.core.ready), sizeof(Mailbox.core.ready));

    result = e_load_group(ar.elfFile, pEpiphany, 0, 0, platform.rows, platform.cols, (e_bool_t) (ar.run_target));
    if (result == E_ERR) {
        printf("Error loading Epiphany program.\n");
        exit(1);
    }


    // Check if the DevIL shared lib's version matches the executable's version.
    if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION)
    {
        fprintf(stderr, "DevIL version is different ...exiting!\n");
        exit(2);
    }

    // Initialize DevIL.
    ilInit();
#ifdef ILU_ENABLED
    iluInit();
#endif



    // create the coreID list
    init_coreID(pEpiphany, coreID, _Nside, _Nside, 0x808);


    // Generate the main image name to use, bind it and load the image file.
    ilGenImages(1, &ImgId);
    ilBindImage(ImgId);
    if (!ilLoadImage(ar.ifname))//ar.ifname
    {
        fprintf(stderr, "Could not open input image file \"%s\" ...exiting.\n", ar.ifname);
        exit(3);
    }


    // Display the image's dimensions to the end user.
    /*
    printf("Width: %d  Height: %d  Depth: %d  Bpp: %d\n\n",
           ilGetInteger(IL_IMAGE_WIDTH),
           ilGetInteger(IL_IMAGE_HEIGHT),
           ilGetInteger(IL_IMAGE_DEPTH),
           ilGetInteger(IL_IMAGE_BITS_PER_PIXEL));
    */
    imdata = ilGetData();
    imsize = ilGetInteger(IL_IMAGE_WIDTH) * ilGetInteger(IL_IMAGE_HEIGHT);
    imBpp  = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);

    if (imsize != (_Sfft * _Sfft))
    {
        printf("Image file size is different from %dx%d ...exiting.\n", _Sfft, _Sfft);
        exit(5);
    }


    // Extract image data into the A matrix.
    for (unsigned int i=0; i<imsize; i++)
    {
        Mailbox.A[i] = (float) imdata[i*imBpp] + 0.0 * I;
    }

    fprintf(fo, "\n");


    // Generate operand matrices based on a provided seed
    matrix_init(0);

#ifdef _USE_DRAM_
    // Copy operand matrices to Epiphany system
    addr = DRAM_BASE + offsetof(shared_buf_t, A[0]);
    sz = sizeof(Mailbox.A);
    fprintf(fo, "%% Writing A[%ldB] to address %08x...\n", sz, addr);
    e_write(addr, (void *) Mailbox.A, sz);

    addr = DRAM_BASE + offsetof(shared_buf_t, B[0]);
    sz = sizeof(Mailbox.B);
    fprintf(fo, "%% Writing B[%ldB] to address %08x...\n", sz, addr);
    e_write(addr, (void *) Mailbox.B, sz);
#else
    // Copy operand matrices to Epiphany cores' memory
    fprintf(fo, "%% Writing image to Epiphany\n");

    sz = sizeof(Mailbox.A) / _Ncores;
    for (row=0; row<(int) platform.rows; row++)
        for (col=0; col<(int) platform.cols; col++)
        {
            addr = BankA_addr;
            fflush(stdout);
            cnum = e_get_num_from_coords(pEpiphany, row, col);
//			 printf(       "Writing A[%uB] to address %08x...\n", sz, addr);
            fprintf(fo, "%% Writing A[%uB] to address %08x...\n", sz, (coreID[cnum] << 20) | addr);
            fflush(fo);
            e_write(pEpiphany, row, col, addr, (void *) &Mailbox.A[cnum * _Score * _Sfft], sz);
        }
#endif



    // Call the Epiphany fft2d() function
    fprintf(fo, "%% GO!\n");
    fflush(stdout);
    fflush(fo);
    clock_gettime(CLOCK_MONOTONIC, &timer[0]);
    fft2d_go(pDRAM);
    clock_gettime(CLOCK_MONOTONIC, &timer[1]);
    fprintf(fo, "%% Done!\n\n");
    fflush(stdout);
    fflush(fo);

    // Read time counters
//	 printf(       "Reading time count...\n");
    fprintf(fo, "%% Reading time count...\n");
    addr = 0x7128+0x4*2 + offsetof(core_t, time_p[0]);
    sz = TIMERS * sizeof(uint32_t);
    e_read(pEpiphany, 0, 0, addr, (void *) (&time_p[0]), sz);

//	for (int i=0; i<TIMERS; i++)
//		printf("time_p[%d] = %u\n", i, time_p[i]);

    time_d[2] = time_p[7] - time_p[2]; // FFT setup
    time_d[3] = time_p[2] - time_p[3]; // bitrev (x8)
    time_d[4] = time_p[3] - time_p[4]; // FFT-1D (x8)
    time_d[5] = time_p[4] - time_p[5]; // corner-turn
    time_d[6] = time_p[7] - time_p[8]; // FFT-2D
    time_d[7] = time_p[6] - time_p[7]; // LPF
    time_d[9] = time_p[0] - time_p[9]; // Total cycles
    fprintf(fo, "%% Finished calculation in %u cycles (%5.3f msec @ %3.0f MHz)\n\n", time_d[9], (time_d[9] * 1000.0 / eMHz), (eMHz / 1e6));

    printf(       "FFT2D         - %7u cycles (%5.3f msec)\n", time_d[6], (time_d[6] * 1000.0 / eMHz));
    printf(       "  FFT Setup   - %7u cycles (%5.3f msec)\n", time_d[2], (time_d[2] * 1000.0 / eMHz));
    printf(       "  BITREV      - %7u cycles (%5.3f msec)\n", time_d[3], (time_d[3] * 1000.0 / eMHz));
    printf(       "  FFT1D       - %7u cycles (%5.3f msec x2)\n", time_d[4], (time_d[4] * 1000.0 / eMHz));
    printf(       "  Corner Turn - %7u cycles (%5.3f msec)\n", time_d[5], (time_d[5] * 1000.0 / eMHz));
    printf(       "LPF           - %7u cycles (%5.3f msec)\n", time_d[7], (time_d[7] * 1000.0 / eMHz));
    fprintf(fo, "%% Reading processed image back to host\n");



    // Read result matrix
#ifdef _USE_DRAM_
    addr = DRAM_BASE + offsetof(shared_buf_t, B[0]);
    sz = sizeof(Mailbox.B);
    printf(       "Reading B[%ldB] from address %08x...\n", sz, addr);
    fprintf(fo, "%% Reading B[%ldB] from address %08x...\n", sz, addr);
    blknum = sz / RdBlkSz;
    remndr = sz % RdBlkSz;
    for (i=0; i<blknum; i++)
    {
        fflush(stdout);
        e_read(addr+i*RdBlkSz, (void *) ((long unsigned)(Mailbox.B)+i*RdBlkSz), RdBlkSz);
    }
    fflush(stdout);
    e_read(addr+i*RdBlkSz, (void *) ((long unsigned)(Mailbox.B)+i*RdBlkSz), remndr);
#else
    // Read result matrix from Epiphany cores' memory
    sz = sizeof(Mailbox.A) / _Ncores;
    for (row=0; row<(int) platform.rows; row++)
        for (col=0; col<(int) platform.cols; col++)
        {
            addr = BankA_addr;
            fflush(stdout);
            cnum = e_get_num_from_coords(pEpiphany, row, col);
//			printf(        "Reading A[%uB] from address %08x...\n", sz, addr);
            fprintf(fo, "%% Reading A[%uB] from address %08x...\n", sz, (coreID[cnum] << 20) | addr);
            fflush(fo);
            e_read(pEpiphany, row, col, addr, (void *) &Mailbox.B[cnum * _Score * _Sfft], sz);
        }
#endif

    // Convert processed image matrix B into the image file date.
    for (unsigned int i=0; i<imsize; i++)
    {
        for (unsigned int j=0; j<imBpp; j++)
            imdata[i*imBpp+j] = cabs(Mailbox.B[i]);
    }

    // Save processed image to the output file.
    ilEnable(IL_FILE_OVERWRITE);
    if (!ilSaveImage(ar.ofname))
    {
        fprintf(stderr, "Could not open output image file \"%s\" ...exiting.\n", ar.ofname);
        exit(7);
    }

    // We're done with the image, so let's delete it.
    ilDeleteImages(1, &ImgId);

    // Simple Error detection loop that displays the Error to the user in a human-readable form.
//	while ((Error = ilGetError()))
//		PRINT_ERROR_MACRO;

    // Close connection to device
    if (e_close(pEpiphany))
    {
        fprintf(fo, "\nERROR: Can't close connection to Epiphany device!\n\n");
        exit(1);
    }
    if (e_free(pDRAM))
    {
        fprintf(fo, "\nERROR: Can't release Epiphany DRAM!\n\n");
        exit(1);
    }

    fflush(fo);
    fclose(fo);

    //Returnin success if test runs expected number of clock cycles
    //Need to add comparison with golden reference image!
    printf("------------------------------------------------------------\n");
    if(time_d[9]>50000) {
        printf( "TEST \"fft2d\" PASSED\n");
        return EXIT_SUCCESS;
    }
    else {
        printf( "TEST \"fft2d\" FAILED\n");
        return EXIT_FAILURE;
    }
}
コード例 #26
0
ファイル: FCProcessImages.cpp プロジェクト: BSVino/fcolladaCE
int main(int argc, const char* argv[], char* envp[])
{
#ifdef WIN32
	_environ = envp;
#else //LINUX
	environ = envp;
#endif //WIN32 and LINUX
	if (argc != 3)
	{
		std::cout << "Expecting two arguments:" << std::endl;
		std::cout << "FCProcessImages.exe <input_filename> <output_filename>" <<std::endl;
		exit(-1);
	}

	fstring inputFilename = TO_FSTRING(argv[1]);
	fstring outputFilename = TO_FSTRING(argv[2]);

	// Create an empty COLLADA document and import the given file.
	FCollada::Initialize();
	FUErrorSimpleHandler errorHandler;
	FCDocument* document = FCollada::NewTopDocument();
	FCollada::LoadDocumentFromFile(document, inputFilename.c_str());
	std::cout << argv[1] << std::endl;
	if (errorHandler.IsSuccessful())
	{
		std::cout << "Import: Done." << std::endl;

		// Initialize DevIL.
		ilInit();
		iluInit();

		// Process the image library
		ProcessImageLibrary(document->GetImageLibrary());

		// Shutdown DevIL
		ilShutDown();

		// It is common practice for tools to add a new contributor to identify that they were run
		// on a COLLADA document.
		FCDAssetContributor* contributor = document->GetAsset()->AddContributor();
		const char* userName = getenv("USER");
		if (userName == NULL) userName = getenv("USERNAME");
		if (userName != NULL) contributor->SetAuthor(TO_FSTRING(userName));
		contributor->SetSourceData(inputFilename);
		char authoringTool[1024];
		snprintf(authoringTool, 1024, "FCProcessImages sample for FCollada v%d.%02d", FCOLLADA_VERSION >> 16, FCOLLADA_VERSION & 0xFFFF);
		authoringTool[1023] = 0;
		contributor->SetAuthoringTool(TO_FSTRING((const char*)authoringTool));

		// Write out the processed COLLADA document.
		FCollada::SaveDocument(document, outputFilename.c_str());
		if (errorHandler.IsSuccessful())
		{
			std::cout << "Export: Done." << std::endl;
		}
		else
		{
			std::cout << errorHandler.GetErrorString();
			std::cout << std::endl << std::endl;
		}
	}
コード例 #27
0
ファイル: gltest.c プロジェクト: xksteven/myOpenGL
int main(int argc, char** argv)
{
	// No filename is specified on the command-line.
	if (argc < 2) {
		printf ("Please run as:\n\nDevIL_testGL image_filename\n");
		return 1;
	}
	FileName = argv[1];  // Set filename equal to the first argument.

	//
	// Check if the shared lib's version matches the executable's version.
	//



//
// fixed to get the right numbers from the right library call...
//
	if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
		iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
		ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION) {
		printf ("DevIL library is out of date! Please upgrade\n");
		return 2;
	}

	// Needed to initialize DevIL.
	ilInit ();
	iluInit();

	// GL cannot use palettes anyway, so convert early.
	ilEnable (IL_CONV_PAL);

	// Gets rid of dithering on some nVidia-based cards.
	ilutEnable (ILUT_OPENGL_CONV);

	// Generate the main image name to use.
	ilGenImages (1, &ImgId);
	
	// Bind this image name.
	ilBindImage (ImgId);

	// Loads the image specified by File into the ImgId image.
	if (!ilLoadImage(FileName)) {
		HandleDevILErrors ();
	}

	// Make sure the window is in the same proportions as the image.
	//  Generate the appropriate width x height less than or equal to MAX_X x MAX_Y.
	//	Instead of just clipping Width x Height to MAX_X x MAX_Y, we scale to
	//	an appropriate size, so the image isn't stretched/squished.
	Width  = ilGetInteger (IL_IMAGE_WIDTH);
	Height = ilGetInteger (IL_IMAGE_HEIGHT);
	
	if (Width > 0) {  // Don't want a divide by 0...
		if (Width > MAX_X) {
			Width = MAX_X;
			Height = (ILuint)(MAX_X / (ILfloat)ilGetInteger(IL_IMAGE_WIDTH) * Height);
		}
	}
	if (Height > 0) {  // Don't want a divide by 0...
		if (Height > MAX_Y) {
			Height = MAX_Y;
			Width = (ILuint)(MAX_Y / (ILfloat)ilGetInteger(IL_IMAGE_HEIGHT) * Width);
		}
	}

	HandleDevILErrors ();

	// Standard glut initializations.
	glutInit               (&argc, argv);  // Standard glut initialization.
	glutInitDisplayMode    (GLUT_RGB | GLUT_DOUBLE);
	glutInitWindowPosition (100, 100);
	glutInitWindowSize     (Width, Height);
	
	window = glutCreateWindow("Developer's Image Library (DevIL) Test");

	ilutInit();

	glutDisplayFunc  (DisplayFunc);
	glutKeyboardFunc (KeyboardFunc);

	// Goes into our setup function.
	if (Setup() == IL_FALSE)
		return 1;

	// Enter the main (Free)GLUT processing loop
	glutMainLoop();

	// Clean up any loose ends.
	CleanUp();

	return 0;
}
コード例 #28
0
	InitializeOpenIL() {
		ilInit();
		iluInit();
	}
コード例 #29
0
ファイル: main.cpp プロジェクト: GoodRon/OpenSR
int main(int argc, char **argv)
{
    if (argc < 2)
    {
        showHelp();
        return 0;
    }
    ilInit();
    iluInit();
    if (std::string(argv[1]) == "pkgx")
    {
        if (argc < 4)
        {
            showHelp();
            return 0;
        }
        Rangers::extractPKG(argv[2], argv[3]);
    }
    else if (std::string(argv[1]) == "pkg2rpkg")
    {
        if (argc < 5)
        {
            showHelp();
            return 0;
        }
        Rangers::RPKGCompression compression;
        std::string compStr = argv[2];
        std::transform(compStr.begin(), compStr.end(), compStr.begin(), toupper);

        if (compStr == "NONE")
            compression = Rangers::RPKG_NONE;
        else if (compStr == "LZMA")
            compression = Rangers::RPKG_SEEKABLE_LZMA;
        else if (compStr == "ZLIB")
            compression = Rangers::RPKG_SEEKABLE_ZLIB;

        Rangers::pkg2rpkg(argv[3], argv[4], compression);
    }
    else if (std::string(argv[1]) == "gai2png")
    {
        if (argc < 4)
        {
            showHelp();
            return 0;
        }
        Rangers::extractGAI2PNG(argv[2], argv[3]);
    }
    else if (std::string(argv[1]) == "gi2png")
    {
        if (argc < 4)
        {
            showHelp();
            return 0;
        }
        Rangers::gi2png(argv[2], argv[3]);
    }
    else if (std::string(argv[1]) == "create_planet")
    {
        if (argc < 5)
        {
            showHelp();
            return 0;
        }
        Rangers::createPlanet(argv[2], argv[3], argv[4]);
    }
    else
    {
        std::cout << "Invalid command" << std::endl;
        showHelp();

    }
}
コード例 #30
0
ファイル: texturereader.cpp プロジェクト: waschkbaer/BrainVis
Texture* loadTexture(const std::string& filename, bool useCompression) {
    std::string _loggerCat = "loadTexture";

#if defined( GHOUL_USE_DEVIL )
    ilInit();
    iluInit();
    
    //ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
    //ilEnable(IL_ORIGIN_SET);

    ILboolean loadSuccess = ilLoadImage(filename.c_str());
    if (!loadSuccess) {
        ILenum error = ilGetError();
        LERROR("Error while loading image '" << filename << "': " <<
                    iluErrorString(error));
        return nullptr;
    }
    ILint imageFormat = ilGetInteger(IL_IMAGE_FORMAT);
    ILint imageType = ilGetInteger(IL_IMAGE_TYPE);
    ILint imageByte = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
    ILint width = ilGetInteger(IL_IMAGE_WIDTH);
    ILint height = ilGetInteger(IL_IMAGE_HEIGHT);
    ILint depth = ilGetInteger(IL_IMAGE_DEPTH);

    // Copy data from common data store to own address space
    ILubyte* data = new ILubyte[width * height * imageByte];
    ilCopyPixels(0, 0, 0, width, height, 1, imageFormat, IL_UNSIGNED_BYTE, data);

    glm::size3_t size(width, height, depth);

    Texture::Format format;
    switch (imageFormat) {
        case IL_RGB:
            format = Texture::Format::RGB;
            break;
        case IL_RGBA:
            format = Texture::Format::RGBA;
            break;
        case IL_BGR:
            format = Texture::Format::BGR;
            break;
        case IL_BGRA:
            format = Texture::Format::BGRA;
            break;
        default:
            LERROR("Could not read image file '" << filename << "' of format: '" <<
                        imageFormat << "'");
            return nullptr;
    }

    
    GLenum type;
    switch (imageType) {
        case IL_UNSIGNED_BYTE:
            type = GL_UNSIGNED_BYTE;
            break;
        case IL_BYTE:
            type = GL_BYTE;
            break;
        case IL_UNSIGNED_SHORT:
            type = GL_UNSIGNED_SHORT;
            break;
        case IL_SHORT:
            type = GL_SHORT;
            break;
        case IL_UNSIGNED_INT:
            type = GL_UNSIGNED_INT;
            break;
        case IL_INT:
            type = GL_INT;
            break;
        case IL_FLOAT:
            type = GL_FLOAT;
            break;
        default:
            LERROR("Could not read image file '" << filename <<
                        "' of data type: '" << imageType << "'");
            return nullptr;
    }

#elif defined( GHOUL_USE_FREEIMAGE)

	//image format
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	//pointer to the image, once loaded
	FIBITMAP *dib(0);
	//pointer to the image data
	BYTE* bits(0);
	//image width and height
	unsigned int width(0), height(0);
	//OpenGL's image ID to map to
	GLuint gl_texID;

	//check the file signature and deduce its format
	fif = FreeImage_GetFileType(filename.c_str(), 0);
	//if still unknown, try to guess the file format from the file extension
	if (fif == FIF_UNKNOWN)
		fif = FreeImage_GetFIFFromFilename(filename.c_str());
	//if still unkown, return failure
	if (fif == FIF_UNKNOWN)
		return nullptr;

	//check that the plugin has reading capabilities and load the file
	if (FreeImage_FIFSupportsReading(fif))
		dib = FreeImage_Load(fif, filename.c_str());
	//if the image failed to load, return failure
	if (!dib)
		return nullptr;

	//retrieve the image data
	bits = FreeImage_GetBits(dib);
	//get the image width and height
	width = FreeImage_GetWidth(dib);
	height = FreeImage_GetHeight(dib);

	glm::size3_t size(width, height, 1);
	//if this somehow one of these failed (they shouldn't), return failure
	if ((bits == 0) || (width == 0) || (height == 0))
		return nullptr;


	FREE_IMAGE_TYPE			imageType = FreeImage_GetImageType(dib);
	FREE_IMAGE_COLOR_TYPE	colorType = FreeImage_GetColorType(dib);
	BITMAPINFOHEADER*		infoheader = FreeImage_GetInfoHeader(dib);
	/*
	FIT_UNKNOWN = 0,	// unknown type
		FIT_BITMAP = 1,	// standard image			: 1-, 4-, 8-, 16-, 24-, 32-bit
		FIT_UINT16 = 2,	// array of unsigned short	: unsigned 16-bit
		FIT_INT16 = 3,	// array of short			: signed 16-bit
		FIT_UINT32 = 4,	// array of unsigned long	: unsigned 32-bit
		FIT_INT32 = 5,	// array of long			: signed 32-bit
		FIT_FLOAT = 6,	// array of float			: 32-bit IEEE floating point
		FIT_DOUBLE = 7,	// array of double			: 64-bit IEEE floating point
		FIT_COMPLEX = 8,	// array of FICOMPLEX		: 2 x 64-bit IEEE floating point
		FIT_RGB16 = 9,	// 48-bit RGB image			: 3 x 16-bit
		FIT_RGBA16 = 10,	// 64-bit RGBA image		: 4 x 16-bit
		FIT_RGBF = 11,	// 96-bit RGB float image	: 3 x 32-bit IEEE floating point
		FIT_RGBAF = 12	// 128-bit RGBA float image	: 4 x 32-bit IEEE floating point

		FI_ENUM(FREE_IMAGE_COLOR_TYPE) {
		FIC_MINISWHITE = 0,		// min value is white
		FIC_MINISBLACK = 1,		// min value is black
		FIC_RGB        = 2,		// RGB color model
		FIC_PALETTE    = 3,		// color map indexed
		FIC_RGBALPHA   = 4,		// RGB color model with alpha channel
		FIC_CMYK       = 5		// CMYK color model
		};

		*/

	if (imageType != FIT_BITMAP) {
		LERROR("Could not read image file '" << filename <<
			"' of data type: '" << imageType << "'");
		return nullptr;
	}
	GLenum type = GL_UNSIGNED_BYTE;
	Texture::Format format;
	switch (colorType) {
	case FIC_RGB:
		format = Texture::Format::RGB;
		break;
	case FIC_RGBALPHA:
		format = Texture::Format::RGBA;
		break;
	default:
		LERROR("Could not read image file '" << filename <<
			"' of color type: '" << colorType << "'");
		return nullptr;

	}
	int imageByte = FreeImage_GetBPP(dib);
	unsigned int pitch = FreeImage_GetPitch(dib);
	BYTE* data = new BYTE[width * height * imageByte/8];

	FreeImage_ConvertToRawBits(data, dib, pitch, imageByte, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, TRUE);
	FreeImage_Unload(dib);


	// Swap red and blue channels, cannot use GL_BGR in OpenGL core profile
	for (size_t i = 0; i < width * height; ++i) {
		size_t index = i * imageByte / 8;
		std::swap(data[index], data[index + 2]);
	}

#endif

    Texture* result;
    if (useCompression) {
        switch (format) {
            case Texture::Format::RGB:
                result = new Texture(data, size, format,
                                     GL_COMPRESSED_RGB_S3TC_DXT1_EXT, type);
                break;
            case Texture::Format::RGBA:
                result = new Texture(data, size, format,
                                     GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, type);
                break;
            default:
                LERROR("Could not assign compressed format for: '" <<
                    GLint(format) << "'. Using no compression instead");
                result = new Texture(data, size, format, static_cast<int>(format), type);
                break;
        }
    }
    else
        result = new Texture(data, size, format, static_cast<int>(format), type);

	return result;

}