Exemplo n.º 1
0
static void test(void)
{
    GLsizei vertex_offset;
    GLsizei vertex_stride;
    GLsizei vertex_count;
    GLuint vertex_buffer;

    GLsizei index_offset;
    GLsizei index_count;
    GLuint max_index;
    GLuint min_index;
    GLuint index_buffer;

    vertex_offset = (rand() % 0xff) * sizeof(GLfloat);
    vertex_stride = (rand() % 0xf) * sizeof(GLfloat);
    vertex_count = 1 + rand() % 0xffff;

    index_offset = (rand() % 0xff) * sizeof(GLushort);
    index_count = 1 + rand() % 0xffff;
    min_index = rand() % vertex_count;
    max_index = min_index + rand() % (vertex_count - min_index);

    if (!piglit_automatic) {
        fprintf(stdout, "vertex_offset = %i\n", vertex_offset);
        fprintf(stdout, "vertex_stride = %i\n", vertex_stride);
        fprintf(stdout, "vertex_count = %i\n", vertex_count);
        fprintf(stdout, "index_offset = %i\n", index_offset);
        fprintf(stdout, "index_count = %i\n", index_count);
        fprintf(stdout, "min_index = %u\n", min_index);
        fprintf(stdout, "max_index = %u\n", max_index);
        fprintf(stdout, "\n");
	fflush(stdout);
    }

    glGenBuffers(1, &vertex_buffer);
    glGenBuffers(1, &index_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);

    random_vertices(vertex_offset, vertex_stride, vertex_count);

    if (0) {
        /* Generate valid indices only */
        random_ushort_indices(index_offset, index_count, min_index, max_index);
    } else {
        /* Generate out-of-range indices */
        random_ushort_indices(index_offset, index_count, 0, 2*vertex_count - 1);
    }

    glVertexPointer(2, GL_FLOAT, vertex_stride, (const void*)(intptr_t)vertex_offset);
    glDrawRangeElements(GL_TRIANGLES,
                        min_index,
                        max_index,
                        index_count,
                        GL_UNSIGNED_SHORT,
                        (const void*)(intptr_t)index_offset);
    assert(glGetError() == GL_NO_ERROR);

    /* Call glFinish to prevent the draw from being batched, delaying the cpu crash / gpu crash
     * to much later. */
    glFinish();

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glDeleteBuffers(1, &index_buffer);
    glDeleteBuffers(1, &vertex_buffer);
}
Exemplo n.º 2
0
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE ignoreMe0, LPSTR ignoreMe1, INT ignoreMe2)
{
	HRESULT hr = S_OK;
	HWND hWnd = NULL;
	HDC hDC = NULL;
	HGLRC hRC = NULL;
	MSG msg = {};
	PIXELFORMATDESCRIPTOR pfd;
	
    LARGE_INTEGER previousTime;
    LARGE_INTEGER freqTime;
	double aveDeltaTime = 0.0;

    LPCSTR wndName = "Flow Snake";

	IFC( InitWindow(hWnd, g_width, g_height, wndName) );
    hDC = GetDC(hWnd);

    // Create the GL context.
    ZeroMemory(&pfd, sizeof(pfd));
    pfd.nSize = sizeof(pfd);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 24;
    pfd.cDepthBits = 16;
    pfd.iLayerType = PFD_MAIN_PLANE;
    int pixelFormat = ChoosePixelFormat(hDC, &pfd);
	SetPixelFormat(hDC, pixelFormat, &pfd);
    
	hRC = wglCreateContext(hDC);
    wglMakeCurrent(hDC, hRC);

	IFC( Init() );

    QueryPerformanceFrequency(&freqTime);
    QueryPerformanceCounter(&previousTime);
	
	// -------------------
    // Start the Game Loop
    // -------------------
    while (msg.message != WM_QUIT)
    {
        if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg); 
            DispatchMessage(&msg);
        }
        else
        {
            LARGE_INTEGER currentTime;
            __int64 elapsed;
            double deltaTime;

            QueryPerformanceCounter(&currentTime);
            elapsed = currentTime.QuadPart - previousTime.QuadPart;
            deltaTime = double(elapsed) / freqTime.QuadPart;
			aveDeltaTime = aveDeltaTime * 0.9 + 0.1 * deltaTime;
            previousTime = currentTime;

			IFC( Update(deltaTime) );

			Render();
            SwapBuffers(hDC);
            if (glGetError() != GL_NO_ERROR)
            {
                Error("OpenGL error.\n");
            }
        }
    }

Cleanup:
	if(hRC)  wglDeleteContext(hRC);
	if(hDC)  ReleaseDC(hWnd, hDC);
	if(hWnd) DestroyWindow(hWnd);

	char strBuf[256];
	sprintf_s(strBuf, "Average frame duration = %.3f ms\n", aveDeltaTime*1000.0f); 
	OutputDebugString(strBuf);

    return FAILED(hr);
}
Exemplo n.º 3
0
extern "C" int main(int argcount, char* argvec[])
#endif
{
#if defined(__native_client__)
	std::cerr << "Running game_main" << std::endl;

	chdir("/frogatto");
	{
		char buf[256];
		const char* const res = getcwd(buf,sizeof(buf));
		std::cerr << "Current working directory: " << res << std::endl;
	}
#endif 

#if defined(_MSC_VER)
	std::shared_ptr<FILE> f_stderr = std::shared_ptr<FILE>(freopen ("stderr.txt", "wt", stderr), [](FILE* f){fclose(f); delete f;});
#endif

#if defined(__APPLE__) && TARGET_OS_MAC
    chdir([[[NSBundle mainBundle] resourcePath] fileSystemRepresentation]);
#endif

	#ifdef NO_STDERR
	std::freopen("/dev/null", "w", stderr);
	std::cerr.sync_with_stdio(true);
	#endif

	std::cerr << "Frogatto engine version " << preferences::version() << "\n";
	LOG( "After print engine version" );

	#if defined(TARGET_BLACKBERRY)
		chdir("app/native");
		std::cout<< "Changed working directory to: " << getcwd(0, 0) << std::endl;
	#endif

	game_logic::init_callable_definitions();

	std::string level_cfg = "titlescreen.cfg";
	bool unit_tests_only = false, skip_tests = false;
	bool run_benchmarks = false;
	std::vector<std::string> benchmarks_list;
	std::string utility_program;
	std::vector<std::string> util_args;
	std::string server = "wesnoth.org";
#if defined(UTILITY_IN_PROC)
	bool create_utility_in_new_process = false;
	std::string utility_name;
#endif
	bool is_child_utility = false;

	const char* profile_output = NULL;
	std::string profile_output_buf;

#if defined(__ANDROID__)
	//monstartup("libapplication.so");
#endif

	std::string orig_level_cfg = level_cfg;
	std::string override_level_cfg = "";

	int modules_loaded = 0;

	std::vector<std::string> argv;
	for(int n = 1; n < argcount; ++n) {
#if defined(UTILITY_IN_PROC)
		std::string sarg(argvec[n]);
		if(sarg.compare(0, 15, "--utility-proc=") == 0) {
			create_utility_in_new_process = true;
			utility_name = "--utility-child=" + sarg.substr(15);
		} else {
			argv.push_back(argvec[n]);
		}
#else
		argv.push_back(argvec[n]);
#endif
        
        if(argv.size() >= 2 && argv[argv.size()-2] == "-NSDocumentRevisionsDebugMode" && argv.back() == "YES") {
            //XCode passes these arguments by default when debugging -- make sure they are ignored.
            argv.resize(argv.size()-2);
        }
	}

	std::cerr << "Build Options:";
	for(auto bo : preferences::get_build_options()) {
		std::cerr << " " << bo;
	}
	std::cerr << std::endl;

#if defined(UTILITY_IN_PROC)
	if(create_utility_in_new_process) {
		argv.push_back(utility_name);
#if defined(_MSC_VER)
		// app name is ignored for windows, we get windows to tell us.
		is_child_utility = create_utility_process("", argv);
#else 
		is_child_utility = create_utility_process(argvec[0], argv);
#endif
		if(!is_child_utility) {
			argv.pop_back();
		}
#if defined(_MSC_VER)
		atexit(terminate_utility_process);
#endif
	}
#endif

	if(sys::file_exists("./master-config.cfg")) {
		std::cerr << "LOADING CONFIGURATION FROM master-config.cfg" << std::endl;
		variant cfg = json::parse_from_file("./master-config.cfg");
		if(cfg.is_map()) {
			if( cfg["id"].is_null() == false) {
				std::cerr << "SETTING MODULE PATH FROM master-config.cfg: " << cfg["id"].as_string() << std::endl;
				preferences::set_preferences_path_from_module(cfg["id"].as_string());
				//XXX module::set_module_name(cfg["id"].as_string(), cfg["id"].as_string());
			}
			if(cfg["arguments"].is_null() == false) {
				std::vector<std::string> additional_args = cfg["arguments"].as_list_string();
				argv.insert(argv.begin(), additional_args.begin(), additional_args.end());
				std::cerr << "ADDING ARGUMENTS FROM master-config.cfg:";
				for(size_t n = 0; n < cfg["arguments"].num_elements(); ++n) {
					std::cerr << " " << cfg["arguments"][n].as_string();
				}
				std::cerr << std::endl;
			}
		}
	}

	stats::record_program_args(argv);

	for(size_t n = 0; n < argv.size(); ++n) {
		const int argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		if(arg_name == "--module") {
			if(load_module(arg_value, &argv) != 0) {
				std::cerr << "FAILED TO LOAD MODULE: " << arg_value << "\n";
				return -1;
			}
			++modules_loaded;
		} else if(arg == "--tests") {
			unit_tests_only = true;
		}
	}

	if(modules_loaded == 0 && !unit_tests_only) {
		if(load_module(DEFAULT_MODULE, &argv) != 0) {
			std::cerr << "FAILED TO LOAD MODULE: " << DEFAULT_MODULE << "\n";
			return -1;
		}
	}

	preferences::load_preferences();
	LOG( "After load_preferences()" );

	// load difficulty settings after module, before rest of args.
	difficulty::manager();

	for(size_t n = 0; n < argv.size(); ++n) {
		const size_t argc = argv.size();
		const std::string arg(argv[n]);
		std::string arg_name, arg_value;
		std::string::const_iterator equal = std::find(arg.begin(), arg.end(), '=');
		if(equal != arg.end()) {
			arg_name = std::string(arg.begin(), equal);
			arg_value = std::string(equal+1, arg.end());
		}
		std::cerr << "ARGS: " << arg << std::endl;
		if(arg.substr(0,4) == "-psn") {
			// ignore.
		} else if(arg_name == "--module") {
			// ignore already processed.
		} else if(arg_name == "--profile" || arg == "--profile") {
			profile_output_buf = arg_value;
			profile_output = profile_output_buf.c_str();
		} else if(arg_name == "--utility" || arg_name == "--utility-child") {
			if(arg_name == "--utility-child") {
				is_child_utility = true;
			}
			utility_program = arg_value;
			for(++n; n < argc; ++n) {
				const std::string arg(argv[n]);
				util_args.push_back(arg);
			}

			break;
		} else if(arg == "--benchmarks") {
			run_benchmarks = true;
		} else if(arg_name == "--benchmarks") {
			run_benchmarks = true;
			benchmarks_list = util::split(arg_value);
		} else if(arg == "--tests") {
			// ignore as already processed.
		} else if(arg == "--no-tests") {
			skip_tests = true;
		} else if(arg_name == "--width") {
			std::string w(arg_value);
			preferences::set_actual_screen_width(boost::lexical_cast<int>(w));
		} else if(arg == "--width" && n+1 < argc) {
			std::string w(argv[++n]);
			preferences::set_actual_screen_width(boost::lexical_cast<int>(w));
		} else if(arg_name == "--height") {
			std::string h(arg_value);
			preferences::set_actual_screen_height(boost::lexical_cast<int>(h));
		} else if(arg == "--height" && n+1 < argc) {
			std::string h(argv[++n]);
			preferences::set_actual_screen_height(boost::lexical_cast<int>(h));
		} else if(arg_name == "--level") {
			override_level_cfg = arg_value;
		} else if(arg == "--level" && n+1 < argc) {
			override_level_cfg = argv[++n];
		} else if(arg_name == "--host") {
			server = arg_value;
		} else if(arg == "--host" && n+1 < argc) {
			server = argv[++n];
		} else if(arg == "--compiled") {
			preferences::set_load_compiled(true);
#ifndef NO_EDITOR
		} else if(arg == "--edit") {
			preferences::set_edit_on_start(true);
#endif
		} else if(arg == "--no-compiled") {
			preferences::set_load_compiled(false);
#if defined(TARGET_PANDORA)
		} else if(arg == "--no-fbo") {
			preferences::set_fbo(false);
		} else if(arg == "--no-bequ") {
			preferences::set_bequ(false);
#endif
		} else if(arg == "--help" || arg == "-h") {
			print_help(std::string(argvec[0]));
			return 0;
		} else {
			const bool res = preferences::parse_arg(argv[n].c_str());
			if(!res) {
				std::cerr << "unrecognized arg: '" << arg << "'\n";
				return -1;
			}
		}
	}

	checksum::manager checksum_manager;
#ifndef NO_EDITOR
	sys::filesystem_manager fs_manager;
#endif // NO_EDITOR

	preferences::expand_data_paths();

	background_task_pool::manager bg_task_pool_manager;
	LOG( "After expand_data_paths()" );

	std::cerr << "Preferences dir: " << preferences::user_data_path() << '\n';

	//make sure that the user data path exists.
	if(!preferences::setup_preferences_dir()) {
		std::cerr << "cannot create preferences dir!\n";
	}

	std::cerr << "\n";

	const tbs::internal_server_manager internal_server_manager_scope(preferences::internal_tbs_server());

	if(utility_program.empty() == false 
		&& test::utility_needs_video(utility_program) == false) {
#if defined(UTILITY_IN_PROC)
		if(is_child_utility) {
			ASSERT_LOG(ipc::semaphore::create(shared_sem_name, 1) != false, 
				"Unable to create shared semaphore: " << errno);
			std::cerr.sync_with_stdio(true);
		}
#endif
		test::run_utility(utility_program, util_args);
		return 0;
	}

#if defined(TARGET_PANDORA)
    EGL_Open();
#endif

#if defined(__ANDROID__)
	std::freopen("stdout.txt","w",stdout);
	std::freopen("stderr.txt","w",stderr);
	std::cerr.sync_with_stdio(true);
#endif

	LOG( "Start of main" );

	if(!skip_tests && !test::run_tests()) {
		return -1;
	}

	if(unit_tests_only) {
		return 0;
	}

#if !defined(__native_client__)
	Uint32 sdl_init_flags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
#if defined(_WINDOWS) || TARGET_OS_IPHONE
	sdl_init_flags |= SDL_INIT_TIMER;
#endif
	if(SDL_Init(sdl_init_flags) < 0) {
		std::cerr << "could not init SDL\n";
		return -1;
	}
	LOG( "After SDL_Init" );
#endif

#ifdef TARGET_OS_HARMATTAN
	g_type_init();
#endif
	i18n::init ();
	LOG( "After i18n::init()" );

	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);

#if TARGET_OS_IPHONE || defined(TARGET_BLACKBERRY) || defined(__ANDROID__)
	//on the iPhone and PlayBook, try to restore the auto-save if it exists
	if(sys::file_exists(preferences::auto_save_file_path()) && sys::read_file(std::string(preferences::auto_save_file_path()) + ".stat") == "1") {
		level_cfg = "autosave.cfg";
		sys::write_file(std::string(preferences::auto_save_file_path()) + ".stat", "0");

	}
#endif

	if(override_level_cfg.empty() != true) {
		level_cfg = override_level_cfg;
		orig_level_cfg = level_cfg;
	}

#if !SDL_VERSION_ATLEAST(2, 0, 0) && defined(USE_SHADERS)
	wm.create_window(preferences::actual_screen_width(),
		preferences::actual_screen_height(),
		0,
		(preferences::resizable() ? SDL_RESIZABLE : 0) | (preferences::fullscreen() ? SDL_FULLSCREEN : 0));
#else

#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
	int width, height;
	iphone_screen_res(&width, &height);
	preferences::set_actual_screen_width(width);
	preferences::set_actual_screen_height(height);
	int multiplier = 2;
	if (width > 320)
	{
		//preferences::set_use_pretty_scaling(true);
		multiplier = 1;
	}
	preferences::set_virtual_screen_width(height*multiplier);
	preferences::set_virtual_screen_height(width*multiplier);
	preferences::set_control_scheme(height % 1024 ? "iphone_2d" : "ipad_2d");
	
	SDL_WindowID windowID = SDL_CreateWindow (NULL, 0, 0, preferences::actual_screen_width(), preferences::actual_screen_height(),
		SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
		SDL_WINDOW_BORDERLESS);
	if (windowID == 0) { 
		std::cerr << "Could not create window: " << SDL_GetError() << "\n"; 
		return -1;
	}
	
	//	if (SDL_GL_CreateContext(windowID) == 0) {
	//		std::cerr << "Could not create GL context: " << SDL_GetError() << "\n";
	//		return -1;
	//	}
	if (SDL_CreateRenderer(windowID, -1, 0) != 0) {
		std::cerr << "Could not create renderer\n";
		return -1;
	}
	
#else
#ifdef TARGET_OS_HARMATTAN
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGLES | SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}

	preferences::init_oes();
	SDL_ShowCursor(0);
#else

#if defined(TARGET_PANDORA)
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),16,SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
    EGL_Init();
    preferences::init_oes();
#elif defined(TARGET_TEGRA)
	//if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,preferences::resizable() ? SDL_RESIZABLE : 0|preferences::fullscreen() ? SDL_FULLSCREEN : 0) == NULL) {
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
    EGL_Init();
    preferences::init_oes();
#elif defined(TARGET_BLACKBERRY)
	if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|SDL_FULLSCREEN) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
	}
	preferences::init_oes();
#elif defined(__ANDROID__)
#if SDL_VERSION_ATLEAST(2, 0, 0)
	int num_video_displays = SDL_GetNumVideoDisplays();
	SDL_Rect r;
	if(num_video_displays < 0) {
		std::cerr << "no video displays available" << std::endl;
		return -1;
	}
	if(SDL_GetDisplayBounds(0, &r) < 0) {
        preferences::set_actual_screen_width(r.w);
        preferences::set_actual_screen_height(r.h);
		if(r.w < 640) {
        	preferences::set_virtual_screen_width(r.w*2);
        	preferences::set_virtual_screen_height(r.h*2);
		} else {
			preferences::set_virtual_screen_width(r.w);
			preferences::set_virtual_screen_height(r.h);
		}
		preferences::set_control_scheme(r.h >= 1024 ? "ipad_2d" : "android_med");
    }
#else
    SDL_Rect** r = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
    if( r != (SDL_Rect**)0 && r != (SDL_Rect**)-1 ) {
        preferences::set_actual_screen_width(r[0]->w);
        preferences::set_actual_screen_height(r[0]->h);
		if(r[0]->w < 640) {
        	preferences::set_virtual_screen_width(r[0]->w*2);
        	preferences::set_virtual_screen_height(r[0]->h*2);
		} else {
			preferences::set_virtual_screen_width(r[0]->w);
			preferences::set_virtual_screen_height(r[0]->h);
		}
		preferences::set_control_scheme(r[0]->h >= 1024 ? "ipad_2d" : "android_med");
    }
#endif

#if SDL_VERSION_ATLEAST(2, 0, 0)
	if(!graphics::set_video_mode(preferences::actual_screen_width(), preferences::actual_screen_height())) {
#else
    if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_FULLSCREEN|SDL_OPENGL) == NULL) {
#endif
		std::cerr << "could not set video mode\n";
		return -1;
    }
#elif defined(__native_client__)
    SDL_Rect** r = SDL_ListModes(NULL, SDL_OPENGL);
	std::cerr << "Video modes";
	if(r == (SDL_Rect**)0) {
		std::cerr << "No modes available";
		return -1;
	}
	if(r == (SDL_Rect**)-1) {
		std::cerr << "All modes available";
	} else {
		for(int i = 0; r[i]; ++i) {
			std::cerr << r[i]->w << r[i]->h << std::endl;
		}
	}

    if (SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,0) == NULL) {
		std::cerr << "could not set video mode\n";
		return -1;
    }
#else
#if SDL_VERSION_ATLEAST(2, 0, 0)
	if(preferences::auto_size_window()) {
		const SDL_DisplayMode mode = graphics::set_video_mode_auto_select();
		preferences::set_actual_screen_width(mode.w);
		preferences::set_actual_screen_height(mode.h);
		preferences::set_virtual_screen_width(mode.w);
		preferences::set_virtual_screen_height(mode.h);
	} else if(!graphics::set_video_mode(preferences::actual_screen_width(), preferences::actual_screen_height(), SDL_WINDOW_RESIZABLE|SDL_WINDOW_OPENGL)) {
#else
	if(SDL_SetVideoMode(preferences::actual_screen_width(),preferences::actual_screen_height(),0,SDL_OPENGL|(preferences::resizable() ? SDL_RESIZABLE : 0)|(preferences::fullscreen() ? SDL_FULLSCREEN : 0)) == NULL) {
#endif
		std::cerr << "could not set video mode\n";
		return -1;
	}
#ifndef __APPLE__
	graphics::surface wm_icon = graphics::surface_cache::get("window-icon.png");
	if(!wm_icon.null()) {
#if SDL_VERSION_ATLEAST(2, 0, 0)
		SDL_SetWindowIcon(graphics::get_window(), wm_icon.get());
#else
		SDL_WM_SetIcon(wm_icon, NULL);
#endif
	}
#endif // __APPLE__
#endif
#endif
#endif

#endif

#if !SDL_VERSION_ATLEAST(2, 0, 0) && defined(__GLEW_H__)
	GLenum glew_status = glewInit();
	ASSERT_EQ(glew_status, GLEW_OK);
#endif

#if defined(USE_SHADERS)
	if(glCreateShader == NULL) {
		const GLubyte* glstrings;
		if(glGetString != NULL && (glstrings = glGetString(GL_VERSION)) != NULL) {
			std::cerr << "OpenGL version: " << reinterpret_cast<const char *>(glstrings) << std::endl;
		}
		std::cerr << "glCreateShader is NULL. Check that your current video card drivers support "
			<< "an OpenGL version >= 2. Exiting." << std::endl;
		return 0;
	}
	// Has to happen after the call to glewInit().
	gles2::init_default_shader();
#endif

//	srand(time(NULL));

	const stats::manager stats_manager;
#ifndef NO_EDITOR
	const external_text_editor::manager editor_manager;
#endif // NO_EDITOR

#if defined(USE_BOX2D)
	box2d::manager b2d_manager;
#endif

	std::cerr << std::endl;
	const GLubyte* glstrings;
	if((glstrings = glGetString(GL_VENDOR)) != NULL) {
		std::cerr << "OpenGL vendor: " << reinterpret_cast<const char *>(glstrings) << std::endl;
	} else {
		GLenum err = glGetError();
		std::cerr << "Error in vendor string: " << std::hex << err << std::endl;
	}
	if((glstrings = glGetString(GL_VERSION)) != NULL) {
		std::cerr << "OpenGL version: " << reinterpret_cast<const char *>(glstrings) << std::endl;
	} else {
		GLenum err = glGetError();
		std::cerr << "Error in version string: " << std::hex << err << std::endl;
	}
	if((glstrings = glGetString(GL_EXTENSIONS)) != NULL) {
		std::cerr << "OpenGL extensions: " << reinterpret_cast<const char *>(glstrings) << std::endl;
	} else {
		GLenum err = glGetError();
		std::cerr << "Error in extensions string: " << std::hex << err << std::endl;
	}
#ifdef GL_SHADING_LANGUAGE_VERSION
	if((glstrings = glGetString(GL_SHADING_LANGUAGE_VERSION)) != NULL) {
		std::cerr << "GLSL Version: " << reinterpret_cast<const char *>(glstrings) << std::endl;
	} else {
		GLenum err = glGetError();
		std::cerr << "Error in GLSL string: " << std::hex << err << std::endl;
	}
#endif
	std::cerr << std::endl;

	GLint stencil_bits = 0;
	glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
	std::cerr << "Stencil bits: " << stencil_bits << std::endl;

#if defined(USE_SHADERS)
#if !defined(GL_ES_VERSION_2_0)
	GLfloat min_pt_sz;
	glGetFloatv(GL_POINT_SIZE_MIN, &min_pt_sz);
	GLfloat max_pt_sz;
	glGetFloatv(GL_POINT_SIZE_MAX, &max_pt_sz);
	std::cerr << "Point size range: " << min_pt_sz << " < size < " << max_pt_sz << std::endl;
	glEnable(GL_POINT_SPRITE);
	glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
#endif
#endif

	glShadeModel(GL_SMOOTH);
	glEnable(GL_BLEND);
#if !defined(USE_SHADERS)
	glEnable(GL_TEXTURE_2D);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
#endif

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	std::cerr << "JOYSTICKS: " << SDL_NumJoysticks() << "\n";

	const load_level_manager load_manager;

	{ //manager scope
	const font::manager font_manager;
	const sound::manager sound_manager;
#if !defined(__native_client__)
	const joystick::manager joystick_manager;
#endif 
	
	graphics::texture::manager texture_manager;

#ifndef NO_EDITOR
	editor::manager editor_manager;
#endif

	variant preloads;
	loading_screen loader;
	try {
		variant gui_node = json::parse_from_file(preferences::load_compiled() ? "data/compiled/gui.cfg" : "data/gui.cfg");
		gui_section::init(gui_node);
		loader.draw_and_increment(_("Initializing GUI"));
		framed_gui_element::init(gui_node);

		sound::init_music(json::parse_from_file("data/music.cfg"));
		graphical_font::init_for_locale(i18n::get_locale());
		preloads = json::parse_from_file("data/preload.cfg");
		int preload_items = preloads["preload"].num_elements();
		loader.set_number_of_items(preload_items+7); // 7 is the number of items that will be loaded below
		custom_object::init();
		loader.draw_and_increment(_("Initializing custom object functions"));
		init_custom_object_functions(json::parse_from_file("data/functions.cfg"));
		loader.draw_and_increment(_("Initializing textures"));
		loader.load(preloads);
		loader.draw_and_increment(_("Initializing tiles"));
		tile_map::init(json::parse_from_file("data/tiles.cfg"));


		game_logic::formula_object::load_all_classes();

	} catch(const json::parse_error& e) {
		std::cerr << "ERROR PARSING: " << e.error_message() << "\n";
		return 0;
	}
	loader.draw(_("Loading level"));

#if defined(__native_client__)
	while(1) {
	}
#endif

#if defined(__APPLE__) && !(TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE) && !defined(USE_SHADERS)
	GLint swapInterval = 1;
	CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &swapInterval);
#endif

	loader.finish_loading();
	//look to see if we got any quit events while loading.
	{
	SDL_Event event;
	while(SDL_PollEvent(&event)) {
		if(event.type == SDL_QUIT) {
			return 0;
		}
	}
	}

	formula_profiler::manager profiler(profile_output);

#ifdef USE_SHADERS
	texture_frame_buffer::init(preferences::actual_screen_width(), preferences::actual_screen_height());
#else
	texture_frame_buffer::init();
#endif

	if(run_benchmarks) {
		if(benchmarks_list.empty() == false) {
			test::run_benchmarks(&benchmarks_list);
		} else {
			test::run_benchmarks();
		}
		return 0;
	} else if(utility_program.empty() == false && test::utility_needs_video(utility_program) == true) {
		test::run_utility(utility_program, util_args);
		return 0;
	}

	bool quit = false;

	while(!quit && !show_title_screen(level_cfg)) {
		boost::intrusive_ptr<level> lvl(load_level(level_cfg));
		

#if !defined(__native_client__)
		//see if we're loading a multiplayer level, in which case we
		//connect to the server.
		multiplayer::manager mp_manager(lvl->is_multiplayer());
		if(lvl->is_multiplayer()) {
			multiplayer::setup_networked_game(server);
		}

		if(lvl->is_multiplayer()) {
			last_draw_position() = screen_position();
			std::string level_cfg = "waiting-room.cfg";
			boost::intrusive_ptr<level> wait_lvl(load_level(level_cfg));
			wait_lvl->finish_loading();
			wait_lvl->set_multiplayer_slot(0);
			if(wait_lvl->player()) {
				wait_lvl->player()->set_current_level(level_cfg);
			}
			wait_lvl->set_as_current_level();

			level_runner runner(wait_lvl, level_cfg, orig_level_cfg);

			multiplayer::sync_start_time(*lvl, boost::bind(&level_runner::play_cycle, &runner));

			lvl->set_multiplayer_slot(multiplayer::slot());
		}
#endif

		last_draw_position() = screen_position();

		assert(lvl.get());
		if(!lvl->music().empty()) {
			sound::play_music(lvl->music());
		}

		if(lvl->player() && level_cfg != "autosave.cfg") {
			lvl->player()->set_current_level(level_cfg);
			lvl->player()->get_entity().save_game();
		}

		set_scene_title(lvl->title());

		try {
			quit = level_runner(lvl, level_cfg, orig_level_cfg).play_level();
			level_cfg = orig_level_cfg;
		} catch(multiplayer_exception&) {
		}
	}

	level::clear_current_level();

	} //end manager scope, make managers destruct before calling SDL_Quit
//	controls::debug_dump_controls();
#if defined(TARGET_PANDORA) || defined(TARGET_TEGRA)
    EGL_Destroy();
#endif

#if SDL_VERSION_ATLEAST(2, 0, 0)
	// Be nice and destroy the GL context and the window.
	graphics::set_video_mode(0, 0, CLEANUP_WINDOW_CONTEXT);
#elif defined(USE_SHADERS)
	wm.destroy_window();
#endif
	SDL_Quit();
	
	preferences::save_preferences();
	std::cerr << SDL_GetError() << "\n";

#if !defined(_MSC_VER) && defined(UTILITY_IN_PROC)
	if(create_utility_in_new_process) {
		terminate_utility_process();
	}
#endif

#ifdef _MSC_VER
	ExitProcess(0);
#endif

	std::set<variant*> loading;
	swap_variants_loading(loading);
	if(loading.empty() == false) {
		fprintf(stderr, "Illegal object: %p\n", (void*)(*loading.begin())->as_callable_loading());
		ASSERT_LOG(false, "Unresolved unserialized objects: " << loading.size());
	}

	return 0;
}
Exemplo n.º 4
0
enum piglit_result
piglit_display(void)
{
	GLboolean pass = GL_TRUE;
	GLuint tex, fb;
	GLenum status;
	float fbo_white[] = {0.0, 0.0, 0.0, 1.0};
	float fbo_black[] = {0.0, 0.0, 0.0, 0.0};
	float fbo_gray[] =  {0.0, 0.0, 0.0, 0.5};
	float white[] = {1.0, 1.0, 1.0, 1.0};
	float black[] = {0.0, 0.0, 0.0, 0.0};
	float gray[] =  {0.5, 0.5, 0.5, 0.5};
	int fbo_width = 64;
	int fbo_height = 64;

	glGenFramebuffersEXT(1, &fb);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
	glViewport(0, 0, fbo_width, fbo_height);

	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA,
		     fbo_width, fbo_height, 0,
		     GL_ALPHA, GL_UNSIGNED_BYTE, NULL);

	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
				  GL_COLOR_ATTACHMENT0_EXT,
				  GL_TEXTURE_2D,
				  tex,
				  0);
	assert(glGetError() == 0);

	status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
		fprintf(stderr, "fbo incomplete (status = 0x%04x)\n", status);
		piglit_report_result(PIGLIT_SKIP);
	}

	/* Clear to no alpha. */
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glClear(GL_COLOR_BUFFER_BIT);

	glColor4f(0.0, 0.0, 0.0, 0.0);
	piglit_draw_rect(-1.0, -1.0, 0.5, 2.0);

	glColor4f(0.0, 0.0, 0.0, 1.0);
	piglit_draw_rect(-0.5, -1.0, 0.5, 2.0);

	glColor4f(0.0, 0.0, 0.0, 0.5);
	piglit_draw_rect(0.0, -1.0, 0.5, 2.0);
	glEnable(GL_BLEND);
	glBlendFunc(GL_DST_ALPHA, GL_ZERO);
	glColor4f(0.0, 0.0, 0.0, 1.0);
	piglit_draw_rect(0.0, -1.0, 0.5, 2.0);
	glDisable(GL_BLEND);

	glColor4f(0.0, 0.0, 0.0, 0.5);
	piglit_draw_rect(0.5, -1.0, 0.5, 2.0);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
	glColor4f(0.0, 0.0, 0.0, 1.0);
	piglit_draw_rect(0.5, -1.0, 0.5, 2.0);
	glDisable(GL_BLEND);

	printf("Testing FBO result.\n");
	pass = piglit_probe_pixel_rgba(fbo_width * 1 / 8, 0, fbo_black) && pass;
	pass = piglit_probe_pixel_rgba(fbo_width * 3 / 8, 0, fbo_white) && pass;
	pass = piglit_probe_pixel_rgba(fbo_width * 5 / 8, 0, fbo_gray) && pass;
	pass = piglit_probe_pixel_rgba(fbo_width * 7 / 8, 0, fbo_gray) && pass;

	/* Draw the two textures to halves of the window. */
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glViewport(0, 0, piglit_width, piglit_height);

	glEnable(GL_TEXTURE_2D);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
	glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE);
	glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
	glTexEnvi (GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_ALPHA);
	glTexEnvi (GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE);
	glTexEnvi (GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
	glTexEnvi (GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE);

	glBindTexture(GL_TEXTURE_2D, tex);
	piglit_draw_rect_tex(-1, -1, 2, 2,
			     0, 0, 1, 1);

	glDisable(GL_TEXTURE_2D);
	glDeleteTextures(1, &tex);
	glDeleteFramebuffersEXT(1, &fb);

	printf("Testing window result.\n");
	pass = piglit_probe_pixel_rgba(piglit_width * 1 / 8, 0, black) && pass;
	pass = piglit_probe_pixel_rgba(piglit_width * 3 / 8, 0, white) && pass;
	pass = piglit_probe_pixel_rgba(piglit_width * 5 / 8, 0, gray) && pass;
	pass = piglit_probe_pixel_rgba(piglit_width * 7 / 8, 0, gray) && pass;

	glutSwapBuffers();

	return pass ? PIGLIT_PASS : PIGLIT_FAIL;
}
Exemplo n.º 5
0
void GL32_draw2DRectangle(video::SColor color, const core::rect<s32>& position,
	const core::rect<s32>* clip)
{

	if (!irr_driver->isGLSL())
	{
		irr_driver->getVideoDriver()->draw2DRectangle(color, position, clip);
		return;
	}

	core::dimension2d<u32> frame_size =
		irr_driver->getVideoDriver()->getCurrentRenderTargetSize();
	const int screen_w = frame_size.Width;
	const int screen_h = frame_size.Height;
	float center_pos_x = position.UpperLeftCorner.X + position.LowerRightCorner.X;
	center_pos_x /= screen_w;
	center_pos_x -= 1;
	float center_pos_y = position.UpperLeftCorner.Y + position.LowerRightCorner.Y;
	center_pos_y /= screen_h;
	center_pos_y = 1 - center_pos_y;
	float width = position.LowerRightCorner.X - position.UpperLeftCorner.X;
	width /= screen_w;
	float height = position.LowerRightCorner.Y - position.UpperLeftCorner.Y;
	height /= screen_h;

	if (color.getAlpha() < 255)
	{
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}
	else
	{
		glDisable(GL_BLEND);
	}

    if (clip)
    {
        if (!clip->isValid())
            return;

        glEnable(GL_SCISSOR_TEST);
        const core::dimension2d<u32>& renderTargetSize = irr_driver->getVideoDriver()->getCurrentRenderTargetSize();
        glScissor(clip->UpperLeftCorner.X, renderTargetSize.Height - clip->LowerRightCorner.Y,
            clip->getWidth(), clip->getHeight());
    }

	glUseProgram(UIShader::ColoredRectShader::Program);
	glBindVertexArray(UIShader::ColoredRectShader::vao);
	UIShader::ColoredRectShader::setUniforms(center_pos_x, center_pos_y, width, height, color);

	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);
    if (clip)
        glDisable(GL_SCISSOR_TEST);
	glUseProgram(0);

    GLenum glErr = glGetError();
    if (glErr != GL_NO_ERROR)
    {
        Log::warn("IrrDriver", "GLWrap : OpenGL error %i\n", glErr);
    }
}
Exemplo n.º 6
0
void TextureManager_CreateTextureClassic(TextureManager *This, glTexture *texture, int width, int height, glUtil *util)
{
	int texformat = -1;
	int i;
	DWORD x, y;
	GLenum error;
	if (!texture->miplevel) texture->miplevel = 1;
	texture->pixelformat.dwSize = sizeof(DDPIXELFORMAT);
	for(i = 0; i < numtexformats; i++)
	{
		if(!memcmp(&texformats[i],&texture->pixelformat,sizeof(DDPIXELFORMAT)))
		{
			texformat = i;
			break;
		}
	}
	ZeroMemory(texture->internalformats, 8 * sizeof(GLint));
	switch(texformat)
	{
	case -1:
	case 0: // 8-bit palette
		if(This->ext->glver_major >= 3)
		{
			texture->internalformats[0] = GL_R8;
			texture->format = GL_RED;
		}
		else
		{
			texture->internalformats[0] = GL_RGBA8;
			texture->format = GL_LUMINANCE;
		}
		texture->type = GL_UNSIGNED_BYTE;
		texture->colororder = 4;
		texture->colorsizes[0] = 255;
		texture->colorsizes[1] = 255;
		texture->colorsizes[2] = 255;
		texture->colorsizes[3] = 255;
		texture->colorbits[0] = 8;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 0;
		break;
	case 1: // 8-bit RGB332
		texture->internalformats[0] = GL_R3_G3_B2;
		texture->internalformats[1] = GL_RGB8;
		texture->internalformats[2] = GL_RGBA8;
		texture->format = GL_RGB;
		texture->type = GL_UNSIGNED_BYTE_3_3_2;
		texture->colororder = 1;
		texture->colorsizes[0] = 7;
		texture->colorsizes[1] = 7;
		texture->colorsizes[2] = 3;
		texture->colorsizes[3] = 1;
		texture->colorbits[0] = 3;
		texture->colorbits[1] = 3;
		texture->colorbits[2] = 2;
		texture->colorbits[3] = 0;
		break;
	case 2: // 16-bit RGB555
		texture->internalformats[0] = GL_RGB5_A1;
		texture->internalformats[1] = GL_RGBA8;
		texture->format = GL_BGRA;
		texture->type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
		texture->colororder = 1;
		texture->colorsizes[0] = 31;
		texture->colorsizes[1] = 31;
		texture->colorsizes[2] = 31;
		texture->colorsizes[3] = 1;
		texture->colorbits[0] = 5;
		texture->colorbits[1] = 5;
		texture->colorbits[2] = 5;
		texture->colorbits[3] = 1;
		break;
	case 3: // 16-bit RGB565
		texture->internalformats[0] = GL_RGB565;
		texture->internalformats[1] = GL_RGB8;
		texture->internalformats[2] = GL_RGBA8;
		texture->format = GL_RGB;
		texture->type = GL_UNSIGNED_SHORT_5_6_5;
		texture->colororder = 1;
		texture->colorsizes[0] = 31;
		texture->colorsizes[1] = 63;
		texture->colorsizes[2] = 31;
		texture->colorsizes[3] = 1;
		texture->colorbits[0] = 5;
		texture->colorbits[1] = 6;
		texture->colorbits[2] = 5;
		texture->colorbits[3] = 0;
		break;
	case 4: // 24-bit RGB888
		texture->internalformats[0] = GL_RGB8;
		texture->internalformats[1] = GL_RGBA8;
		texture->format = GL_BGR;
		texture->type = GL_UNSIGNED_BYTE;
		texture->colororder = 1;
		texture->colorsizes[0] = 255;
		texture->colorsizes[1] = 255;
		texture->colorsizes[2] = 255;
		texture->colorsizes[3] = 1;
		texture->colorbits[0] = 8;
		texture->colorbits[1] = 8;
		texture->colorbits[2] = 8;
		texture->colorbits[3] = 0;
		break;
	case 5: // 32-bit RGB888
		texture->internalformats[0] = GL_RGBA8;
		texture->format = GL_BGRA;
		texture->type = GL_UNSIGNED_INT_8_8_8_8_REV;
		texture->colororder = 1;
		texture->colorsizes[0] = 255;
		texture->colorsizes[1] = 255;
		texture->colorsizes[2] = 255;
		texture->colorsizes[3] = 1;
		texture->colorbits[0] = 8;
		texture->colorbits[1] = 8;
		texture->colorbits[2] = 8;
		texture->colorbits[3] = 0;
		break;
	case 6: // 32-bit BGR888
		texture->internalformats[0] = GL_RGBA8;
		texture->format = GL_RGBA;
		texture->type = GL_UNSIGNED_INT_8_8_8_8_REV;
		texture->colororder = 0;
		texture->colorsizes[0] = 255;
		texture->colorsizes[1] = 255;
		texture->colorsizes[2] = 255;
		texture->colorsizes[3] = 1;
		texture->colorbits[0] = 8;
		texture->colorbits[1] = 8;
		texture->colorbits[2] = 8;
		texture->colorbits[3] = 0;
		break;
	case 7: // 16-bit RGBA8332
		FIXME("Unusual texture format RGBA8332 not supported");
		texture->colororder = 1;
		texture->colorsizes[0] = 7;
		texture->colorsizes[1] = 7;
		texture->colorsizes[2] = 3;
		texture->colorsizes[3] = 255;
		texture->colorbits[0] = 3;
		texture->colorbits[1] = 3;
		texture->colorbits[2] = 2;
		texture->colorbits[3] = 8;
		break;
	case 8: // 16-bit RGBA4444
		texture->internalformats[0] = GL_RGBA4;
		texture->internalformats[1] = GL_RGBA8;
		texture->format = GL_BGRA;
		texture->type = GL_UNSIGNED_SHORT_4_4_4_4_REV;
		texture->colororder = 1;
		texture->colorsizes[0] = 15;
		texture->colorsizes[1] = 15;
		texture->colorsizes[2] = 15;
		texture->colorsizes[3] = 15;
		texture->colorbits[0] = 4;
		texture->colorbits[1] = 4;
		texture->colorbits[2] = 4;
		texture->colorbits[3] = 4;
		break;
	case 9: // 16-bit RGBA1555
		texture->internalformats[0] = GL_RGB5_A1;
		texture->internalformats[1] = GL_RGBA8;
		texture->format = GL_BGRA;
		texture->type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
		texture->colorbits[0] = 5;
		texture->colorbits[1] = 5;
		texture->colorbits[2] = 5;
		texture->colorbits[3] = 1;
		break;
	case 10: // 32-bit RGBA8888
		texture->internalformats[0] = GL_RGBA8;
		texture->format = GL_BGRA;
		texture->type = GL_UNSIGNED_INT_8_8_8_8_REV;
		texture->colororder = 1;
		texture->colorsizes[0] = 255;
		texture->colorsizes[1] = 255;
		texture->colorsizes[2] = 255;
		texture->colorsizes[3] = 255;
		texture->colorbits[0] = 8;
		texture->colorbits[1] = 8;
		texture->colorbits[2] = 8;
		texture->colorbits[3] = 8;
		break;
	case 11: // 8-bit Luminance
		texture->internalformats[0] = GL_LUMINANCE8;
		texture->internalformats[1] = GL_RGB8;
		texture->internalformats[2] = GL_RGBA8;
		texture->format = GL_LUMINANCE;
		texture->type = GL_UNSIGNED_BYTE;
		texture->colororder = 5;
		texture->colorsizes[0] = 255;
		texture->colorsizes[1] = 255;
		texture->colorsizes[2] = 255;
		texture->colorsizes[3] = 255;
		texture->colorbits[0] = 8;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 0;
		break;
	case 12: // 8-bit Alpha
		texture->internalformats[0] = GL_ALPHA8;
		texture->format = GL_ALPHA;
		texture->type = GL_UNSIGNED_BYTE;
		texture->colororder = 6;
		texture->colorsizes[0] = 255;
		texture->colorsizes[1] = 255;
		texture->colorsizes[2] = 255;
		texture->colorsizes[3] = 255;
		texture->colorbits[0] = 0;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 8;
		break;
	case 13: // 16-bit Luminance Alpha
		texture->internalformats[0] = GL_LUMINANCE8_ALPHA8;
		texture->internalformats[1] = GL_RGBA8;
		texture->format = GL_LUMINANCE_ALPHA;
		texture->type = GL_UNSIGNED_BYTE;
		texture->colororder = 7;
		texture->colorsizes[0] = 255;
		texture->colorsizes[1] = 255;
		texture->colorsizes[2] = 255;
		texture->colorsizes[3] = 255;
		texture->colorbits[0] = 8;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 8;
		break;
	case 14: // 16-bit Z buffer
		texture->internalformats[0] = GL_DEPTH_COMPONENT16;
		texture->format = GL_DEPTH_COMPONENT;
		texture->type = GL_UNSIGNED_SHORT;
		texture->colororder = 4;
		texture->colorsizes[0] = 65535;
		texture->colorsizes[1] = 65535;
		texture->colorsizes[2] = 65535;
		texture->colorsizes[3] = 65535;
		texture->colorbits[0] = 16;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 0;
		break;
	case 15: // 24-bit Z buffer
		texture->internalformats[0] = GL_DEPTH_COMPONENT24;
		texture->format = GL_DEPTH_COMPONENT;
		texture->type = GL_UNSIGNED_INT;
		texture->colororder = 4;
		texture->colorsizes[0] = 16777215;
		texture->colorsizes[1] = 16777215;
		texture->colorsizes[2] = 16777215;
		texture->colorsizes[3] = 16777215;
		texture->colorbits[0] = 24;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 0;
		break;
	case 16: // 32/24 bit Z buffer
		texture->internalformats[0] = GL_DEPTH_COMPONENT24;
		texture->format = GL_DEPTH_COMPONENT;
		texture->type = GL_UNSIGNED_INT;
		texture->colororder = 4;
		texture->colorsizes[0] = 16777215;
		texture->colorsizes[1] = 16777215;
		texture->colorsizes[2] = 16777215;
		texture->colorsizes[3] = 16777215;
		texture->colorbits[0] = 24;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 0;
		break;
	case 17: // 32-bit Z buffer
		texture->internalformats[0] = GL_DEPTH_COMPONENT32;
		texture->format = GL_DEPTH_COMPONENT;
		texture->type = GL_UNSIGNED_INT;
		texture->colororder = 4;
		texture->colorsizes[0] = 4294967295;
		texture->colorsizes[1] = 4294967295;
		texture->colorsizes[2] = 4294967295;
		texture->colorsizes[3] = 4294967295;
		texture->colorbits[0] = 32;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 0;
		break;
	case 18: // 32-bit Z/Stencil buffer, depth LSB
		texture->internalformats[0] = GL_DEPTH24_STENCIL8;
		texture->format = GL_DEPTH_STENCIL;
		texture->type = GL_UNSIGNED_INT_24_8;
		texture->colororder = 7;
		texture->colorsizes[0] = 16777215;
		texture->colorsizes[1] = 16777215;
		texture->colorsizes[2] = 16777215;
		texture->colorsizes[3] = 255;
		texture->colorbits[0] = 24;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 8;
		break;
	case 19: // 32-bit Z/Stencil buffer, depth MSB
		texture->internalformats[0] = GL_DEPTH24_STENCIL8;
		texture->format = GL_DEPTH_STENCIL;
		texture->type = GL_UNSIGNED_INT_24_8;
		texture->colororder = 7;
		texture->colorsizes[0] = 16777215;
		texture->colorsizes[1] = 16777215;
		texture->colorsizes[2] = 16777215;
		texture->colorsizes[3] = 255;
		texture->colorbits[0] = 24;
		texture->colorbits[1] = 0;
		texture->colorbits[2] = 0;
		texture->colorbits[3] = 8;
		break;
	}
	texture->width = width;
	texture->height = height;
	glGenTextures(1,&texture->id);
	glUtil_SetTexture(util,0,texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture->minfilter);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture->magfilter);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture->wraps);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture->wrapt);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, texture->miplevel - 1);
	x = texture->width;
	y = texture->height;
	for (i = 0; i < texture->miplevel; i++)
	{
		do
		{
			ClearError();
			glTexImage2D(GL_TEXTURE_2D, i, texture->internalformats[0], x, y, 0, texture->format, texture->type, NULL);
			ShrinkMip(&x, &y);
			error = glGetError();
			if (error != GL_NO_ERROR)
			{
				if (texture->internalformats[1] == 0)
				{
					FIXME("Failed to create texture, cannot find internal format");
					break;
				}
				memmove(&texture->internalformats[0], &texture->internalformats[1], 7 * sizeof(GLint));
				texture->internalformats[7] = 0;
			}
			else break;
		} while (1);
	}
}
void
piglit_init(int argc, char **argv)
{
	bool pass = true;
	GLuint tex, fbo;
	int i, c;

	if (piglit_get_gl_version() < 30) {
		printf("Requires GL 3.0\n");
		piglit_report_result(PIGLIT_SKIP);
	}

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

	for (i = 0; required_formats[i].token != GL_NONE; i++) {
		GLenum format, type, attachment, status;
		const struct sized_internalformat *f;

		/* FINISHME: Add support for future GL versions. */
		if (required_formats[i].version != 30)
			continue;

		if (!required_formats[i].rb_required)
			continue;

		f = get_sized_internalformat(required_formats[i].token);

		if (f->token == GL_DEPTH24_STENCIL8 ||
		    f->token == GL_DEPTH32F_STENCIL8) {
			format = GL_DEPTH_STENCIL;
			type = GL_UNSIGNED_INT_24_8;
			attachment = GL_DEPTH_STENCIL_ATTACHMENT;
		} else if (get_channel_size(f, D)) {
			format = GL_DEPTH_COMPONENT;
			type = GL_FLOAT;
			attachment = GL_DEPTH_ATTACHMENT;
		} else {
			format = GL_RGBA;
			type = GL_FLOAT;
			attachment = GL_COLOR_ATTACHMENT0;

			/* Have to specify integer data for integer textures. */
			for (c = R; c <= I; c++) {
				if (get_channel_type(f, c) == GL_UNSIGNED_INT ||
				    get_channel_type(f, c) == GL_INT) {
					format = GL_RGBA_INTEGER;
					type = GL_UNSIGNED_INT;
					break;
				}
			}
		}

		glTexImage2D(GL_TEXTURE_2D, 0, f->token,
			     1, 1, 0,
			     format, type, NULL);

		if (glGetError() != 0) {
			printf("Unexpected error creating %s texture\n",
			       f->name);
			pass = false;
			continue;
		}

		/* Testing of the sizes/types of the channels is left
		 * up to the required-sized-texture-formats test.
		 */

		glGenFramebuffers(1, &fbo);
		glBindFramebuffer(GL_FRAMEBUFFER, fbo);

		glFramebufferTexture2D(GL_FRAMEBUFFER,
				       attachment,
				       GL_TEXTURE_2D,
				       tex, 0);

		if (glGetError() != 0) {
			printf("Unexpected error binding %s texture\n",
			       f->name);
			pass = false;
			continue;
		}

		if (attachment == GL_COLOR_ATTACHMENT0) {
			glDrawBuffer(GL_COLOR_ATTACHMENT0);
		} else {
			glDrawBuffer(GL_NONE);
		}

		status = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT);
		if (status != GL_FRAMEBUFFER_COMPLETE) {
			fprintf(stderr, "%s fbo incomplete (status = 0x%04x)\n",
				f->name, status);
			pass = false;
		} else {
			printf("%s: fbo complete\n", f->name);
		}

		glDeleteFramebuffers(1, &fbo);
	}

	glDeleteTextures(1, &tex);

	piglit_report_result(pass ? PIGLIT_PASS : PIGLIT_FAIL);
}
Exemplo n.º 8
0
// DLL based display plugins MUST initialize GLEW inside the DLL code.
void DebugHmdDisplayPlugin::customizeContext() {
    glewExperimental = true;
    glewInit();
    glGetError(); // clear the potential error from glewExperimental
    Parent::customizeContext();
}
Exemplo n.º 9
0
// the program starts here
void AppMain() {
    // initialise GLFW
    if(!glfwInit())
        throw std::runtime_error("glfwInit failed");

    // open a window with GLFW
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
    if(!glfwOpenWindow((int)SCREEN_SIZE.x, (int)SCREEN_SIZE.y, 8, 8, 8, 8, 16, 0, GLFW_WINDOW))
        throw std::runtime_error("glfwOpenWindow failed. Can your hardware handle OpenGL 3.2?");

    // GLFW settings
    glfwDisable(GLFW_MOUSE_CURSOR);
    glfwSetMousePos(0, 0);
    glfwSetMouseWheel(0);

    // initialise GLEW
    glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/
    if(glewInit() != GLEW_OK)
        throw std::runtime_error("glewInit failed");

    // GLEW throws some errors, so discard all the errors so far
    while(glGetError() != GL_NO_ERROR) {}

    // print out some info about the graphics drivers
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
    std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
    std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;

    // make sure OpenGL version 3.2 API is available
    if(!GLEW_VERSION_3_2)
        throw std::runtime_error("OpenGL 3.2 API is not available.");

    // OpenGL settings
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    // initialise the gWoodenCrate asset
    LoadWoodenCrateAsset();

    // create all the instances in the 3D scene based on the gWoodenCrate asset
    CreateInstances();

    // setup gCamera
    gCamera.setPosition(glm::vec3(-4,0,17));
    gCamera.setViewportAspectRatio(SCREEN_SIZE.x / SCREEN_SIZE.y);
    gCamera.setNearAndFarPlanes(0.5f, 100.0f);

    // setup gLight
    gLight.position = glm::vec3(-4,0,4);
    gLight.intensities = glm::vec3(1,1,1); //white
    gLight.attenuation = 0.2f;
    gLight.ambientCoefficient = 0.005f;

    // run while the window is open
    double lastTime = glfwGetTime();
    while(glfwGetWindowParam(GLFW_OPENED)){
        // update the scene based on the time elapsed since last update
        double thisTime = glfwGetTime();
        Update((float)(thisTime - lastTime));
        lastTime = thisTime;

        // draw one frame
        Render();

        // check for errors
        GLenum error = glGetError();
        if(error != GL_NO_ERROR)
            glPrintError();

        //exit program if escape key is pressed
        if(glfwGetKey(GLFW_KEY_ESC))
            glfwCloseWindow();
    }

    // clean up and exit
    glfwTerminate();
}
Exemplo n.º 10
0
static inline void checkGlError(const char* op = 0) {
    GLenum error = glGetError();
    if (error == GL_NO_ERROR)
        return;
    qWarning("GL error %s (%#x): %s", op, error, glGetString(error));
}
Exemplo n.º 11
0
int main2(int argc, char *argv[])
{
  const char* filename = "src/border.png";

  // Load file and decode image.
  std::vector<unsigned char> image;
  unsigned width, height;
  unsigned error = lodepng::decode(image, width, height, filename);

  // If there's an error, display it.
  if(error != 0)
  {
    std::cout << "error " << error << ": " << lodepng_error_text(error) << std::endl;
    return 1;
  }
  
  // Here the PNG is loaded in "image". All the rest of the code is SDL and OpenGL stuff.

  int screenw = width;
  if(screenw > 1024) screenw = 1024;
  int screenh = height;
  if(screenh > 768) screenw = 768;

  if(SDL_Init(SDL_INIT_VIDEO) < 0)
  {
    std::cout << "Error: Unable to init SDL: " << SDL_GetError() << std::endl;
    return 1;
  }
  
  SDL_Surface* scr = SDL_SetVideoMode(screenw, screenh, 32, SDL_OPENGL);

  if(scr == 0)
  {
    std::cout << "Error: Unable to set video. SDL error message: " << SDL_GetError() << std::endl;
    return 1;
  }

  // The official code for "Setting Your Raster Position to a Pixel Location" (i.e. set up a camera for 2D screen)
  glViewport(0, 0, screenw, screenh);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0, screenw, screenh, 0, -1, 1);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  // Make some OpenGL properties better for 2D and enable alpha channel.
  glDisable(GL_CULL_FACE);
  glDisable(GL_DEPTH_TEST);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glDisable(GL_ALPHA_TEST);

  if(glGetError() != GL_NO_ERROR)
  {
    std::cout << "Error initing GL" << std::endl;
    return 1;
  }
  
  // Texture size must be power of two for the primitive OpenGL version this is written for. Find next power of two.
  size_t u2 = 1; while(u2 < width) u2 *= 2;
  size_t v2 = 1; while(v2 < height) v2 *= 2;
  // Ratio for power of two version compared to actual version, to render the non power of two image with proper size.
  double u3 = (double)width / u2;
  double v3 = (double)height / v2;

  // Make power of two version of the image.
  std::vector<unsigned char> image2(u2 * v2 * 4);
  for(size_t y = 0; y < height; y++)
  for(size_t x = 0; x < width; x++)
  for(size_t c = 0; c < 4; c++)
  {
    image2[4 * u2 * y + 4 * x + c] = image[4 * width * y + 4 * x + c];
  }
  
  // Enable the texture for OpenGL.
  glEnable(GL_TEXTURE_2D);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //GL_NEAREST = no smoothing
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D, 0, 4, u2, v2, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image2[0]);
  
  bool done = false;
  SDL_Event event = {0};
  glColor4ub(255, 255, 255, 255);
  
  while(!done)
  {
    // Quit the loop when receiving quit event.
    while(SDL_PollEvent(&event))
    {
      if(event.type == SDL_QUIT) done = 1;
    }
    
    // Draw the texture on a quad, using u3 and v3 to correct non power of two texture size.
    glBegin(GL_QUADS);
      glTexCoord2d( 0,  0); glVertex2f(    0,      0);
      glTexCoord2d(u3,  0); glVertex2f(width,      0);
      glTexCoord2d(u3, v3); glVertex2f(width, height);
      glTexCoord2d( 0, v3); glVertex2f(    0, height);
    glEnd();
    
    // Redraw and clear screen.
    SDL_GL_SwapBuffers();
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    //Limit frames per second, to not heat up the CPU and GPU too much.
    SDL_Delay(1000);
  }
}
PsychError SCREENOpenOffscreenWindow(void) 
{
    int						screenNumber, depth, targetScreenNumber;
    PsychRectType			rect;
    PsychColorType			color;
    PsychColorModeType  	mode; 
    psych_bool				didWindowOpen;
    PsychWindowRecordType	*exampleWindowRecord, *windowRecord, *targetWindow;
    psych_bool				wasColorSupplied;
    char*					texturePointer;
    size_t					xSize, ySize, nbytes;
    psych_bool				bigendian;
	GLubyte					*rpb;
    int						ix;
	GLenum					fboInternalFormat;
	psych_bool				needzbuffer;
	psych_bool				overridedepth = FALSE;
	int						usefloatformat = 0;
	int						specialFlags = 0;
	int						multiSample = 0;
	
    // Detect endianity (byte-order) of machine:
    ix=255;
    rpb=(GLubyte*) &ix;
    bigendian = ( *rpb == 255 ) ? FALSE : TRUE;
    ix = 0; rpb = NULL;

    //all sub functions should have these two lines
    PsychPushHelp(useString, synopsisString, seeAlsoString);
    if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};

    //cap the number of inputs
    PsychErrorExit(PsychCapNumInputArgs(6));   //The maximum number of inputs
    PsychErrorExit(PsychCapNumOutputArgs(2));  //The maximum number of outputs

    //1-User supplies a window ptr 2-User supplies a screen number 3-User supplies rect and pixel size
    if(PsychIsWindowIndexArg(1)){
        PsychAllocInWindowRecordArg(1, TRUE, &exampleWindowRecord);
		// Assign normalized copy of example windows rect -- Top-Left corner is always (0,0)
		PsychNormalizeRect(exampleWindowRecord->rect, rect);
		
		// Adapt rect for some stereo modes:
		if (PsychIsOnscreenWindow(exampleWindowRecord) && (exampleWindowRecord->specialflags & kPsychHalfWidthWindow)) {
			// Special case: Example window is a dualview stereo onscreen window: Its effective size is only half the real window width,
			// so we cut the width of the examplerect in half to not be wasteful:
			rect[kPsychRight] = rect[kPsychRight] / 2;
		}

		if (PsychIsOnscreenWindow(exampleWindowRecord) && (exampleWindowRecord->specialflags & kPsychHalfHeightWindow)) {
			// Special case: Example window is a dualview stereo onscreen window: Its effective size is only half the real window width,
			// so we cut the width of the examplerect in half to not be wasteful:
			rect[kPsychBottom] = rect[kPsychBottom] / 2;
		}

        // We copy depth only from exampleWindow if it is a offscreen window (=texture). Copying from
        // onscreen windows doesn't make sense, e.g. depth=16 for onscreen means RGBA8 window, but it
        // would map onto a LUMINANCE+ALPHA texture for the offscreen window! We always use 32 bit RGBA8
        // in such a case.
        depth=(PsychIsOffscreenWindow(exampleWindowRecord)) ? exampleWindowRecord->depth : 32;
		// unless it is a FBO backed onscreen window in imaging mode: Then we can use the depth from it.
		if (exampleWindowRecord->imagingMode & kPsychNeedFastBackingStore || exampleWindowRecord->imagingMode & kPsychNeedFastOffscreenWindows) depth = exampleWindowRecord->depth;
        targetScreenNumber=exampleWindowRecord->screenNumber;
        targetWindow=exampleWindowRecord;
    } else if(PsychIsScreenNumberArg(1)){
        PsychCopyInScreenNumberArg(1, TRUE, &screenNumber);
        PsychGetScreenRect(screenNumber, rect);
        depth=32; // Always use RGBA8 in this case! See above...
        targetScreenNumber=screenNumber;
        targetWindow=NULL;
    } else if(PsychIsUnaffiliatedScreenNumberArg(1)){  //that means -1 or maybe also NaN if we add that option.  
        // Default to a depth of 32 bpp:
        depth=32;
        targetScreenNumber=PSYCH_FIRST_SCREEN; // We assign the first screen in the system.
        PsychGetScreenRect(targetScreenNumber, rect);
        targetWindow=NULL;
    } else {
        PsychErrorExit(PsychError_invalidNumdex);
    }

    if (targetWindow==NULL) {
        // Get target window of screen:
        PsychFindScreenWindowFromScreenNumber(targetScreenNumber, &targetWindow);
    }
    
    //Depth and rect argument supplied as arguments override those inherited from reference screen or window.
    //Note that PsychCopyIn* prefix means that value will not be overwritten if the arguments are not present.
    PsychCopyInRectArg(3,FALSE, rect);
    if (IsPsychRectEmpty(rect)) PsychErrorExitMsg(PsychError_user, "Invalid rect value provided: Empty rects are not allowed.");

	// Copy in optional depth: This gets overriden in many ways if imaging pipeline is on:
    if (PsychCopyInIntegerArg(4,FALSE, &depth)) overridedepth = TRUE;

    // If any of the no longer supported values 0, 1, 2 or 4 is provided, we
    // silently switch to 32 bits per pixel, which is the safest and fastest setting:
    if (depth==0 || depth==1 || depth==2 || depth==4) depth=32;

    // Final sanity check:
	if (!(targetWindow->imagingMode & kPsychNeedFastOffscreenWindows) && !(targetWindow->imagingMode & kPsychNeedFastBackingStore) && (depth==64 || depth==128)) {
      PsychErrorExitMsg(PsychError_user, "Invalid depth value provided. Must be 8 bpp, 16 bpp, 24 bpp or 32 bpp, unless you enable the imaging pipeline, which provides you with more options!");
	}
	
    if (depth!=8 && depth!=16 && depth!=24 && depth!=32 && depth!=64 && depth!=128) {
      PsychErrorExitMsg(PsychError_user, "Invalid depth value provided. Must be 8 bpp, 16 bpp, 24 bpp, 32 bpp, or if imagingmode is enabled also 64 bpp or 128 bpp!");
    }

	// If the imaging pipeline is enabled for the associated onscreen window and fast backing store, aka FBO's
	// is requested, then we only accept depths of at least 32 bit, i.e. RGBA windows. We override any lower
	// precision spec. This is because some common hardware only supports rendering to RGBA textures, not to
	// RGB, LA or Luminance textures.
	if ((targetWindow->imagingMode & kPsychNeedFastBackingStore || targetWindow->imagingMode & kPsychNeedFastOffscreenWindows) && (depth < 32)) depth = 32;

    // Find the color for the window background.  
    wasColorSupplied=PsychCopyInColorArg(kPsychUseDefaultArgPosition, FALSE, &color);
	
	// If none provided, use a proper white-value for this window:
    if(!wasColorSupplied) PsychLoadColorStruct(&color, kPsychIndexColor, PsychGetWhiteValueFromWindow(targetWindow));  

    // Get the optional specialmode flag:
    PsychCopyInIntegerArg(5, FALSE, &specialFlags);

	// This command converts whatever color we got into RGBA format:
    PsychCoerceColorMode(&color);

    // printf("R=%i G=%i B=%i A=%i I=%i", color.value.rgba.r, color.value.rgba.g,color.value.rgba.b,color.value.rgba.a,color.value.index); 
    // First allocate the offscreen window record to store stuff into. If we exit with an error PsychErrorExit() should
    // call PsychPurgeInvalidWindows which will clean up the window record. 
    PsychCreateWindowRecord(&windowRecord);  // This also fills the window index field.

    // This offscreen window is implemented as a Psychtoolbox texture:
    windowRecord->windowType=kPsychTexture;

    // We need to assign the screen number of the onscreen-window, so PsychCreateTexture()
    // can query the size of the screen/onscreen-window...
    windowRecord->screenNumber = targetScreenNumber;

    // Assign the computed depth:
    windowRecord->depth=depth;

	// Default number of channels:
	windowRecord->nrchannels=depth / 8;

    // Assign the computed rect, but normalize it to start with top-left at (0,0):
    PsychNormalizeRect(rect, windowRecord->rect);

	// Until here no OpenGL commands executed. Now we need a valid context: Set targetWindow
	// as drawing target. This will perform neccessary context-switch and all backbuffer
	// backup/restore/whatever operations to make sure we can do what we want without
	// possibly screwing any offscreen windows and bindings:
	if (PsychIsOnscreenWindow(targetWindow) || PsychIsOffscreenWindow(targetWindow)) {
		// This is a possible on-/offscreen drawingtarget:
		PsychSetDrawingTarget(targetWindow);
	}
	else {
		// This must be a proxy-window object: Can't transition to it!
		
		// But we can safe-reset the current drawingtarget...
		PsychSetDrawingTarget((PsychWindowRecordType*) 0x1);
		
		// ...and then switch to the OpenGL context of the 'targetWindow' proxy object:
		PsychSetGLContext(targetWindow);

		// Ok, framebuffer and bindings are safe and disabled, context is set. We
		// should be safe to continue with the proxy...
	}
	
	// From here on we have a defined context and state. We can detach the drawing target whenever
	// we want, as everything is backed up somewhere for later reinit.
	
	// Create offscreen window either new style as FBO, or old style as texture:
	if ((targetWindow->imagingMode & kPsychNeedFastBackingStore) || (targetWindow->imagingMode & kPsychNeedFastOffscreenWindows)) {
		// Imaging mode for this window enabled: Use new way of creating the offscreen window:
		
		// We safely unbind any FBO bindings and drawingtargets:
		PsychSetDrawingTarget((PsychWindowRecordType*) 0x1);
		
		// Overriden for imagingmode: There we always have 4 channels...
		windowRecord->nrchannels=4;

		// Start off with standard 8 bpc fixed point:
		fboInternalFormat = GL_RGBA8; windowRecord->depth=32; usefloatformat = 0;
		
		// Need 16 bpc fixed point precision?
		if (targetWindow->imagingMode & kPsychNeed16BPCFixed) { fboInternalFormat = GL_RGBA16; windowRecord->depth=64; usefloatformat = 0; }
		
		// Need 16 bpc floating point precision?
		if (targetWindow->imagingMode & kPsychNeed16BPCFloat) { fboInternalFormat = GL_RGBA_FLOAT16_APPLE; windowRecord->depth=64; usefloatformat = 1; }
		
		// Need 32 bpc floating point precision?
		if (targetWindow->imagingMode & kPsychNeed32BPCFloat) { fboInternalFormat = GL_RGBA_FLOAT32_APPLE; windowRecord->depth=128; usefloatformat = 2; }
		
		// Override depth value provided?
		if (overridedepth) {
			// Manual depth specified: Override with that depth:
			switch(depth) {
				case 32:
					fboInternalFormat = GL_RGBA8; windowRecord->depth=32; usefloatformat = 0;
				break;

				case 64:
					fboInternalFormat = GL_RGBA_FLOAT16_APPLE; windowRecord->depth=64; usefloatformat = 1;
				break;

				case 128:
					fboInternalFormat = GL_RGBA_FLOAT32_APPLE; windowRecord->depth=128; usefloatformat = 2;
				break;
				
				default:
					fboInternalFormat = GL_RGBA8; windowRecord->depth=32; usefloatformat = 0;
			}			
		}
		
		// Do we need additional depth buffer attachments?
		needzbuffer = (PsychPrefStateGet_3DGfx()>0) ? TRUE : FALSE;
		
		// Copy in optional multiSample argument: It defaults to zero, aka multisampling disabled.
		PsychCopyInIntegerArg(6, FALSE, &multiSample);
		if (multiSample < 0) PsychErrorExitMsg(PsychError_user, "Invalid negative multiSample level provided!");

		// Multisampled anti-aliasing requested?
		if (multiSample > 0) {
			// Yep. Supported by GPU?
			if (!(targetWindow->gfxcaps & kPsychGfxCapFBOMultisample)) {
				// No. We fall back to non-multisampled mode:
				multiSample = 0;
				
				// Tell user if warnings enabled:
				if (PsychPrefStateGet_Verbosity() > 1) {
					printf("PTB-WARNING: You requested stimulus anti-aliasing via multisampling by setting the multiSample parameter of Screen('OpenOffscreenWindow', ...) to a non-zero value.\n");
					printf("PTB-WARNING: You also requested use of the imaging pipeline. Unfortunately, your combination of operating system, graphics hardware and driver does not\n");
					printf("PTB-WARNING: support simultaneous use of the imaging pipeline and multisampled anti-aliasing.\n");
					printf("PTB-WARNING: Will therefore continue without anti-aliasing...\n\n");
					printf("PTB-WARNING: A driver upgrade may resolve this issue. Users of MacOS-X need at least OS/X 10.5.2 Leopard for support on recent ATI hardware.\n\n");
				}
			}
		}

		// Allocate framebuffer object for this Offscreen window:
		if (!PsychCreateFBO(&(windowRecord->fboTable[0]), fboInternalFormat, needzbuffer, PsychGetWidthFromRect(rect), PsychGetHeightFromRect(rect), multiSample)) {
			// Failed!
			PsychErrorExitMsg(PsychError_user, "Creation of Offscreen window in imagingmode failed for some reason :(");
		}

		// Assign this FBO as drawBuffer for mono channel of our Offscreen window:
		windowRecord->drawBufferFBO[0] = 0;
		windowRecord->fboCount = 1;
		
		// Assign it as texture as well:
		windowRecord->textureNumber = windowRecord->fboTable[0]->coltexid;
		windowRecord->textureMemorySizeBytes = 0;
		windowRecord->textureMemory = NULL;
		windowRecord->texturetarget = GL_TEXTURE_RECTANGLE_EXT;
		windowRecord->surfaceSizeBytes = PsychGetWidthFromRect(rect) * PsychGetHeightFromRect(rect) * (windowRecord->depth / 8);

		// Set bpc for FBO backed offscreen window:
		windowRecord->bpc = (int) (windowRecord->depth / 4);

		// Initial setup done, continues below after some shared code...
	}
	else {
		// Traditional texture creation code:
		
		// Special case for alpha-channel: DBL_MAX signals maximum alpha
		// value requested. In our own code we need to manually map this to
		// the maximum uint8 alpha value of 255:
		if (color.value.rgba.a == DBL_MAX) color.value.rgba.a = 255;
		
		// Allocate the texture memory:
		// We only allocate the amount really needed for given format, aka numMatrixPlanes - Bytes per pixel.
		xSize = (size_t) PsychGetWidthFromRect(rect);
		ySize = (size_t) PsychGetHeightFromRect(rect);
		windowRecord->textureMemorySizeBytes = ((size_t) (depth/8)) * xSize * ySize;
		windowRecord->textureMemory = malloc(windowRecord->textureMemorySizeBytes);
		texturePointer=(char*) windowRecord->textureMemory;
		// printf("depth=%i xsize=%i ysize=%i mem=%i ptr=%p", depth, xSize, ySize, windowRecord->textureMemorySizeBytes, texturePointer);
		// Fill with requested background color:
		nbytes=0;
		switch (depth) {
			case 8: // Pure LUMINANCE texture:
				memset((void*) texturePointer, color.value.rgba.r, windowRecord->textureMemorySizeBytes);
				break;
				
			case 16: // LUMINANCE + ALPHA
				while (nbytes < windowRecord->textureMemorySizeBytes) {
					*(texturePointer++) = color.value.rgba.r;
					*(texturePointer++) = color.value.rgba.a;
					nbytes+=2;
				}
				break;
				
			case 24: // RGB:
				while (nbytes < windowRecord->textureMemorySizeBytes) {
					*(texturePointer++) = color.value.rgba.r;
					*(texturePointer++) = color.value.rgba.g;
					*(texturePointer++) = color.value.rgba.b;
					nbytes+=3;
				}
				break;        
				
			case 32: // RGBA
				if (bigendian) {
					// Code for big-endian machines, e.g., PowerPC:
					while (nbytes < windowRecord->textureMemorySizeBytes) {
						*(texturePointer++) = color.value.rgba.a;
						*(texturePointer++) = color.value.rgba.r;
						*(texturePointer++) = color.value.rgba.g;
						*(texturePointer++) = color.value.rgba.b;
						nbytes+=4;
					}
				}
				else {
					// Code for little-endian machines, e.g., IntelPC, IntelMAC, aka Pentium.
					while (nbytes < windowRecord->textureMemorySizeBytes) {
						*(texturePointer++) = color.value.rgba.b;
						*(texturePointer++) = color.value.rgba.g;
						*(texturePointer++) = color.value.rgba.r;
						*(texturePointer++) = color.value.rgba.a;
						nbytes+=4;
					}
				}
				break;
		}
	}
	
	// Shared setup code for FBO vs. non-FBO Offscreen windows:
	
	// Assign parent window and copy its inheritable properties:
	PsychAssignParentWindow(windowRecord, targetWindow);
	
    // Texture orientation is type 2 aka upright, non-transposed aka Offscreen window:
    windowRecord->textureOrientation = 2;
    
	if ((windowRecord->imagingMode & kPsychNeedFastBackingStore) || (windowRecord->imagingMode & kPsychNeedFastOffscreenWindows)) {
		// Last step for FBO backed Offscreen window: Clear it to its background color:
		PsychSetDrawingTarget(windowRecord);

		// Set default draw shader:
		PsychSetShader(windowRecord, -1);
	
		// Set background fill color:
		PsychSetGLColor(&color, windowRecord);

		// Setup alpha-blending:
		PsychUpdateAlphaBlendingFactorLazily(windowRecord);

		// Fullscreen fill of a non-onscreen window:
		PsychGLRect(windowRecord->rect);

		// Multisampling requested? If so, we need to enable it:
		if (multiSample > 0) {
			glEnable(GL_MULTISAMPLE);
			while (glGetError() != GL_NO_ERROR);
		}
		
		// Ready. Unbind it.
		PsychSetDrawingTarget(NULL);		
	}
	else {
		// Old-style setup for non-FBO Offscreen windows:
		
		// Let's create and bind a new texture object and fill it with our new texture data.
		PsychCreateTexture(windowRecord);
    }

	// Assign GLSL filter-/lookup-shaders if needed:
	PsychAssignHighPrecisionTextureShaders(windowRecord, targetWindow, usefloatformat, (specialFlags & 2) ? 1 : 0);
	
    // Window ready. Mark it valid and return handle to userspace:
    PsychSetWindowRecordValid(windowRecord);
    
    //Return the window index and the rect argument.
    PsychCopyOutDoubleArg(1, FALSE, windowRecord->windowIndex);
    PsychCopyOutRectArg(2, FALSE, rect);

    // Ready.
    return(PsychError_none);
}
Exemplo n.º 13
0
void RendererOGL::WriteRendererInfo(std::ostream &out) const
{
	out << "OpenGL version " << glGetString(GL_VERSION);
	out << ", running on " << glGetString(GL_VENDOR);
	out << " " << glGetString(GL_RENDERER) << "\n";

	out << "Available extensions:" << "\n";
	{
		out << "Shading language version: " <<  glGetString(GL_SHADING_LANGUAGE_VERSION) << "\n";
		GLint numext = 0;
		glGetIntegerv(GL_NUM_EXTENSIONS, &numext);
		for (int i = 0; i < numext; ++i) {
			out << "  " << glGetStringi(GL_EXTENSIONS, i) << "\n";
		}
	}

	out << "\nImplementation Limits:\n";

	// first, clear all OpenGL error flags
	dump_and_clear_opengl_errors(out);

#define DUMP_GL_VALUE(name) dump_opengl_value(out, #name, name, 1)
#define DUMP_GL_VALUE2(name) dump_opengl_value(out, #name, name, 2)

	DUMP_GL_VALUE(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);
	DUMP_GL_VALUE(GL_MAX_CUBE_MAP_TEXTURE_SIZE);
	DUMP_GL_VALUE(GL_MAX_DRAW_BUFFERS);
	DUMP_GL_VALUE(GL_MAX_ELEMENTS_INDICES);
	DUMP_GL_VALUE(GL_MAX_ELEMENTS_VERTICES);
	DUMP_GL_VALUE(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS);
	DUMP_GL_VALUE(GL_MAX_TEXTURE_IMAGE_UNITS);
	DUMP_GL_VALUE(GL_MAX_TEXTURE_LOD_BIAS);
	DUMP_GL_VALUE(GL_MAX_TEXTURE_SIZE);
	DUMP_GL_VALUE(GL_MAX_VERTEX_ATTRIBS);
	DUMP_GL_VALUE(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
	DUMP_GL_VALUE(GL_MAX_VERTEX_UNIFORM_COMPONENTS);
	DUMP_GL_VALUE(GL_NUM_COMPRESSED_TEXTURE_FORMATS);
	DUMP_GL_VALUE(GL_SAMPLE_BUFFERS);
	DUMP_GL_VALUE(GL_SAMPLES);
	DUMP_GL_VALUE2(GL_ALIASED_LINE_WIDTH_RANGE);
	DUMP_GL_VALUE2(GL_MAX_VIEWPORT_DIMS);
	DUMP_GL_VALUE2(GL_SMOOTH_LINE_WIDTH_RANGE);
	DUMP_GL_VALUE2(GL_SMOOTH_POINT_SIZE_RANGE);

#undef DUMP_GL_VALUE
#undef DUMP_GL_VALUE2

	// enumerate compressed texture formats
	{
		dump_and_clear_opengl_errors(out);
		out << "\nCompressed texture formats:\n";

		GLint nformats;
		GLint formats[128]; // XXX 128 should be enough, right?

		glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &nformats);
		GLenum err = glGetError();
		if (err != GL_NO_ERROR) {
			out << "Get NUM_COMPRESSED_TEXTURE_FORMATS failed\n";
			dump_and_clear_opengl_errors(out, err);
		} else {
			assert(nformats >= 0 && nformats < int(COUNTOF(formats)));
			glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats);
			err = glGetError();
			if (err != GL_NO_ERROR) {
				out << "Get COMPRESSED_TEXTURE_FORMATS failed\n";
				dump_and_clear_opengl_errors(out, err);
			} else {
				for (int i = 0; i < nformats; ++i) {
					out << stringf("  %0{x#}\n", unsigned(formats[i]));
				}
			}
		}
	}
	// one last time
	dump_and_clear_opengl_errors(out);
}
Exemplo n.º 14
0
		bool GLRenderWindow::errorInGL(GLenum& error)
		{
				error = glGetError();
				return (error != GL_NO_ERROR);
		}
static void clearGLError()
{
  while (glGetError() != GL_NO_ERROR);
}
Exemplo n.º 16
0
// Called before render is available
bool ModuleRenderer3D::Init()
{
	LOG("Creating 3D Renderer context");
	bool ret = true;
	
	//Create context
	context = SDL_GL_CreateContext(App->window->window);
	if(context == NULL)
	{
		LOG("OpenGL context could not be created! SDL_Error: %s\n", SDL_GetError());
		ret = false;
	}
	
	if(ret == true)
	{
		//Use Vsync
		if(VSYNC && SDL_GL_SetSwapInterval(1) < 0)
			LOG("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError());

		//Initialize Projection Matrix
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();

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

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

		//Check for error
		error = glGetError();
		if(error != GL_NO_ERROR)
		{
			LOG("Error initializing OpenGL! %s\n", gluErrorString(error));
			ret = false;
		}
		
		glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
		glClearDepth(1.0f);
		
		//Initialize clear color
		glClearColor(0.f, 0.f, 0.f, 1.f);

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

		GLfloat LightModelAmbient[] = {0.0f, 0.0f, 0.0f, 1.0f};
		glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightModelAmbient);
		
		lights[0].ref = GL_LIGHT0;
		lights[0].ambient.Set(0.25f, 0.25f, 0.25f, 1.0f);
		lights[0].diffuse.Set(0.75f, 0.75f, 0.75f, 1.0f);
		lights[0].SetPos(0.0f, 0.0f, 2.5f);
		lights[0].Init();
		
		GLfloat MaterialAmbient[] = {1.0f, 1.0f, 1.0f, 1.0f};
		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, MaterialAmbient);

		GLfloat MaterialDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialDiffuse);

		glEnable(GL_DEPTH_TEST);
		glEnable(GL_CULL_FACE);
		lights[0].Active(true);
		glEnable(GL_LIGHTING);
		glEnable(GL_COLOR_MATERIAL);
	}

	// Projection matrix for
	OnResize(SCREEN_WIDTH, SCREEN_HEIGHT);
	
	App->camera->Look(vec3(1.75f, 1.75f, 5.0f), vec3(0.0f, 0.0f, 0.0f));

	return ret;
}
Exemplo n.º 17
0
void ShaderProgram::Use() {
    glGetError();
    glUseProgram(m_program_id);
    CHECK_ERROR("ShaderProgram::Use", "glUseProgram()");
}
Exemplo n.º 18
0
/* build lists for iso-surfaces */
GLuint listTetraIso(pScene sc,pMesh mesh) {
  FILE      *outv,*outf;
  GLuint     dlist = 0;
  pTetra     pt;
  pPoint     p0,p1;
  pMaterial  pm;
  pSolution  ps0,ps1;
  double     delta,rgb[4],d,ax,ay,az,bx,by,bz;
  float      iso,n[3],cx[4],cy[4],cz[4],cc;
  int        m,k,k1,k2,i,l,pos[4],neg[4],nbpos,nbneg,nbnul,nv,nf;
  static double hsv[3]   = { 0.0f, 1.0f, 0.80f };
  static int tn[4] = {0,0,1,1};
  static int tp[4] = {0,1,1,0};

  /* default */
  if ( !mesh->ntet || !mesh->nbb || mesh->typage == 1 )  return(0);
  if ( ddebug ) printf("create iso-values map list / TETRA\n");
  if ( egal(sc->iso.val[0],sc->iso.val[MAXISO-1]) )  return(0);
  delta = sc->iso.val[MAXISO-1] - sc->iso.val[0];

  /* build display list */
  dlist = glGenLists(1);
  glNewList(dlist,GL_COMPILE);
  if ( glGetError() )  return(0);

  /* build list */
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
  glDepthMask(GL_FALSE);

  if (ddebug) {
	outv = fopen("vertex.mesh","w");
	fprintf(outv,"MeshVersionFormatted 1\n Dimension\n 3\n\nVertices\n \n");
	outf = fopen("faces.mesh2","w");
	fprintf(outv,"Triangles\n \n");
  }
  nv = nf = 0;

  glBegin(GL_TRIANGLES);
  for (i=MAXISO-1; i>=0; i--) {
    iso = sc->iso.val[i];

    /* base color */
    /*hsv[0] = 240.0f*(1.0f - (iso-sc->iso.val[0])/delta);*/
    hsv[0] = sc->iso.col[i];
    hsvrgb(hsv,rgb);
    rgb[0] = min(1.0,rgb[0]+BASETR);
    rgb[1] = min(1.0,rgb[1]+BASETR);
    rgb[2] = min(1.0,rgb[2]+BASETR);
    rgb[3] = BASETR + (float)(i-1)/(float)MAXISO*(1.0-BASETR);
    /*rgb[3] = 0.5; */  
    glColor4dv(rgb);

    if ( i == MAXISO-1 )  iso -= 0.001*fabs(iso)/delta;
    else if ( i == 0 )    iso += 0.001*fabs(iso)/delta;

    for (m=0; m<sc->par.nbmat; m++) {
      pm = &sc->material[m];
      k  = pm->depmat[LTets];
      if ( !k || pm->flag )  continue;

      while ( k != 0 ) {
        pt = &mesh->tetra[k];
        if ( !pt->v[0] ) {
          k = pt->nxt;
          continue;
        }

        /* analyze vertices */
        nbpos = nbneg = nbnul = 0;
        for (l=0; l<4; l++) {
          p0  = &mesh->point[pt->v[l]];
          ps0 = &mesh->sol[pt->v[l]];
          /*if ( ps0->bb < sc->iso.val[0] )  ps0->bb = sc->iso.val[0];*/
          
          if ( ps0->bb > iso )      pos[nbpos++] = l;
          else if ( ps0->bb < iso ) neg[nbneg++] = l;
          else                      nbnul++;
        }
        if ( nbneg == 4 || nbpos == 4 ) {
          k = pt->nxt;
          continue;
        }

        if ( nbneg == 2 && nbpos == 2 ) {
          for (l=0; l<4; l++) {
            k1  = neg[tn[l]];
            k2  = pos[tp[l]];
            p0  = &mesh->point[pt->v[k1]];
            p1  = &mesh->point[pt->v[k2]];
            ps0 = &mesh->sol[pt->v[k1]];
            ps1 = &mesh->sol[pt->v[k2]];
            cc = 0.0f;
            if ( fabs(ps1->bb-ps0->bb) > 0.0f )
              cc = (iso-ps0->bb) / (ps1->bb-ps0->bb);
            cx[l] = p0->c[0]+cc*(p1->c[0]-p0->c[0]);
            cy[l] = p0->c[1]+cc*(p1->c[1]-p0->c[1]);
            cz[l] = p0->c[2]+cc*(p1->c[2]-p0->c[2]);
          }

          /* compute face normal */
          ax = cx[1]-cx[0]; ay = cy[1]-cy[0]; az = cz[1]-cz[0];
          bx = cx[2]-cx[0]; by = cy[2]-cy[0]; bz = cz[2]-cz[0];
          n[0] = ay*bz - az*by;
          n[1] = az*bx - ax*bz;
          n[2] = ax*by - ay*bx;
          d = n[0]*n[0] + n[1]*n[1] + n[2]*n[2];
          if ( d > 0.0f ) {
            d = 1.0f / sqrt(d);
            n[0] *= d;  
            n[1] *= d;  
            n[2] *= d;
          }
          glNormal3fv(n);
          glVertex3f(cx[0],cy[0],cz[0]);
          glVertex3f(cx[1],cy[1],cz[1]);
          glVertex3f(cx[2],cy[2],cz[2]);
          
	      glNormal3fv(n);
          glVertex3f(cx[0],cy[0],cz[0]);
          glVertex3f(cx[2],cy[2],cz[2]);
          glVertex3f(cx[3],cy[3],cz[3]);

          if ( ddebug ) {
            fprintf(outv,"%f %f %f 0\n",cx[0],cy[0],cz[0]);
            fprintf(outv,"%f %f %f 0\n",cx[1],cy[1],cz[1]);
            fprintf(outv,"%f %f %f 0\n",cx[2],cy[2],cz[2]);
            fprintf(outv,"%f %f %f 0\n",cx[3],cy[3],cz[3]);

            fprintf(outf,"%d %d %d 0\n",nv+1,nv+2,nv+3);
            fprintf(outf,"%d %d %d 0\n",nv+1,nv+3,nv+4);
          }
          nv+= 4;
          nf+= 2;
        }
        else if ( !nbnul ) {
          for (l=0; l<3; l++) {
            k1 = nbneg == 3 ? neg[l] : pos[l];
            k2 = nbneg == 3 ? pos[0] : neg[0];
            p0 = &mesh->point[pt->v[k1]];
            p1 = &mesh->point[pt->v[k2]];
            ps0 = &mesh->sol[pt->v[k1]];
            ps1 = &mesh->sol[pt->v[k2]];
            cc = 0.0f;
            if ( fabs(ps1->bb-ps0->bb) > 0.0f ) 
              cc = (iso-ps0->bb) / (ps1->bb-ps0->bb);
            cx[l] = p0->c[0]+cc*(p1->c[0]-p0->c[0]);
            cy[l] = p0->c[1]+cc*(p1->c[1]-p0->c[1]);
            cz[l] = p0->c[2]+cc*(p1->c[2]-p0->c[2]);
          }
          /* compute face normal */
          ax = cx[1]-cx[0]; ay = cy[1]-cy[0]; az = cz[1]-cz[0];
          bx = cx[2]-cx[0]; by = cy[2]-cy[0]; bz = cz[2]-cz[0];
          n[0] = ay*bz - az*by;
          n[1] = az*bx - ax*bz;
          n[2] = ax*by - ay*bx;
          d = n[0]*n[0] + n[1]*n[1] + n[2]*n[2];
          if ( d > 0.0f ) {
            d = 1.0f / sqrt(d);
            n[0] *= d;
            n[1] *= d;
            n[2] *= d;
          }
          glNormal3fv(n);
          glVertex3f(cx[0],cy[0],cz[0]);
          glVertex3f(cx[1],cy[1],cz[1]);
          glVertex3f(cx[2],cy[2],cz[2]);

          if ( ddebug ) {
            fprintf(outv,"%f %f %f 0\n",cx[0],cy[0],cz[0]);
            fprintf(outv,"%f %f %f 0\n",cx[1],cy[1],cz[1]);
            fprintf(outv,"%f %f %f 0\n",cx[2],cy[2],cz[2]);
            fprintf(outf,"%d %d %d 0\n",nv+1,nv+2,nv+3);
          }
          nv += 3;
          nf += 1;
        }
        k = pt->nxt;
      }
    }
  }
  glEnd();
  glDepthMask(GL_TRUE);
  glDisable(GL_BLEND);

  if ( ddebug ) {
    fclose(outv);
    fclose(outf);
  }
  printf("  Vertices %d   Triangles %d\n",nv,nf);
  glEndList();
  return(dlist);
}
Exemplo n.º 19
0
int32_t graphics_3d_subinit(uint32_t *Rmask, uint32_t *Gmask, uint32_t *Bmask,
                        uint32_t *Amask) {
    /* Pepper Graphics3D setup. */
    PPB_Instance *ppb_instance_interface =
        (PPB_Instance *) NaCl_GetInterface(PPB_INSTANCE_INTERFACE);
    if (!ppb_instance_interface) {
        write_log("Could not acquire PPB_Instance interface.\n");
        return 0;
    }
    ppb_g3d_interface =
        (PPB_Graphics3D *) NaCl_GetInterface(PPB_GRAPHICS_3D_INTERFACE);
    if (!ppb_g3d_interface) {
        write_log("Could not acquire PPB_Graphics3D interface.\n");
        return 0;
    }
    pp_instance = NaCl_GetInstance();
    if (!pp_instance) {
        write_log("Could not find current Pepper instance.\n");
        return 0;
    }

    int32_t attribs[] = {
      PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
      PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24,
      PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8,
      PP_GRAPHICS3DATTRIB_SAMPLES, 0,
      PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0,
      PP_GRAPHICS3DATTRIB_WIDTH, gfxvidinfo.width,
      PP_GRAPHICS3DATTRIB_HEIGHT, gfxvidinfo.height,
      PP_GRAPHICS3DATTRIB_GPU_PREFERENCE,
          PP_GRAPHICS3DATTRIB_GPU_PREFERENCE_PERFORMANCE,
      PP_GRAPHICS3DATTRIB_NONE
    };

    graphics_context = ppb_g3d_interface->Create(
            pp_instance,
            0 /* share_context */,
            attribs);
    if (!graphics_context) {
        write_log("Could not obtain a PPB_Graphics3D context.\n");
        return 0;
    }
    if (!ppb_instance_interface->BindGraphics(pp_instance, graphics_context)) {
        write_log("Failed to bind context to instance.\n");
        return 0;
    }
    glSetCurrentContextPPAPI(graphics_context);

    /* UAE gfxvidinfo setup. */
    /* TODO(cstefansen): Implement gfx double-buffering if perf. mandates it. */
    gfxvidinfo.pixbytes = 2; /* 16-bit graphics */
    gfxvidinfo.rowbytes = gfxvidinfo.width * gfxvidinfo.pixbytes;
    gfxvidinfo.bufmem =
            (uint8_t *) calloc(round_up_to_power_of_2(gfxvidinfo.rowbytes),
                              round_up_to_power_of_2(gfxvidinfo.height));
    gfxvidinfo.flush_screen = pepper_graphics3d_flush_screen;
    *Rmask = 0x0000F800, *Gmask = 0x000007E0, *Bmask = 0x0000001F, *Amask = 0;

    /* OpenGL ES setup. */
    glViewport(0, 0, gfxvidinfo.width, gfxvidinfo.height);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glDisable(GL_DEPTH_TEST);

    /* Uniform index. */
    enum {
        UNIFORM_VIDEOFRAME,
        UNIFORM_INPUTCOLOR,
        UNIFORM_THRESHOLD,
        NUM_UNIFORMS
    };
    GLint uniforms[NUM_UNIFORMS];

    /* Attribute index. */
    enum {
        ATTRIB_VERTEX,
        ATTRIB_TEXTUREPOSITON,
        NUM_ATTRIBUTES
    };

    static GLuint g_programObj;
    static GLuint g_textureID;

    char *g_VShaderData =
            "attribute vec4 position;"
            "attribute vec4 inputTextureCoordinate;"
            "varying vec2 textureCoordinate;"
            "void main()"
            "{"
            "gl_Position = position;"
            "textureCoordinate = inputTextureCoordinate.xy;"
            "}";

    char *g_FShaderData =
            "varying highp vec2 textureCoordinate;"
            "uniform sampler2D videoFrame;"
            "void main()"
            "{"
            "gl_FragColor = texture2D(videoFrame, textureCoordinate);"
            "}";

    GLuint g_vertexShader;
    GLuint g_fragmentShader;

    g_vertexShader = compileShader(GL_VERTEX_SHADER, g_VShaderData);
    g_fragmentShader = compileShader(GL_FRAGMENT_SHADER, g_FShaderData);

    g_programObj = glCreateProgram();
    glAttachShader(g_programObj, g_vertexShader);
    glAttachShader(g_programObj, g_fragmentShader);

    glBindAttribLocation(g_programObj, ATTRIB_VERTEX, "position");
    glBindAttribLocation(g_programObj, ATTRIB_TEXTUREPOSITON,
                         "inputTextureCoordinate");

    glLinkProgram(g_programObj);

    uniforms[UNIFORM_VIDEOFRAME] = glGetUniformLocation(g_programObj,
                                                        "videoFrame");
    uniforms[UNIFORM_INPUTCOLOR] = glGetUniformLocation(g_programObj,
                                                        "inputColor");
    uniforms[UNIFORM_THRESHOLD] = glGetUniformLocation(g_programObj,
                                                       "threshold");

    glGenTextures(1, &g_textureID);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, g_textureID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    GLint textureWidth = round_up_to_power_of_2(gfxvidinfo.width);
    GLint textureHeight = round_up_to_power_of_2(gfxvidinfo.height);
    glTexImage2D(GL_TEXTURE_2D, 0 /* level */, GL_RGB,
            textureWidth, textureHeight,
                 0, GL_RGB, pixel_data_type, gfxvidinfo.bufmem);

    static const GLfloat squareVertices[] = {
            -1.0f, -1.0,
             1.0f, -1.0,
            -1.0f,  1.0,
             1.0f,  1.0,
    };

    GLfloat xFraction = ((GLfloat) gfxvidinfo.width)  / (GLfloat) textureWidth;
    GLfloat yFraction = ((GLfloat) gfxvidinfo.height) / (GLfloat) textureHeight;
    static GLfloat textureVertices[] = {
            0.0f,                 0.0f /* yFraction */,
            0.0f /* xFraction */, 0.0f /* yFraction */,
            0.0f,                 0.0f,
            0.0f /* xFraction */, 0.0f,
    };
    textureVertices[1] = yFraction;
    textureVertices[2] = xFraction;
    textureVertices[3] = yFraction;
    textureVertices[6] = xFraction;

    glUseProgram(g_programObj);
    glUniform1i(uniforms[UNIFORM_VIDEOFRAME], 0);
    glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, squareVertices);
    glEnableVertexAttribArray(ATTRIB_VERTEX);
    glVertexAttribPointer(ATTRIB_TEXTUREPOSITON, 2, GL_FLOAT, 0, 0,
                          textureVertices);
    glEnableVertexAttribArray(ATTRIB_TEXTUREPOSITON);

    DEBUG_LOG("Shaders compiled and program linked.\n");

    GLenum glErrorStatus = glGetError();
    if (glErrorStatus) {
        write_log("GL error %d while initializing.\n", glErrorStatus);
        return 0;
    }

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    ppb_g3d_interface->SwapBuffers(graphics_context, PP_BlockUntilComplete());

    gettimeofday(&tv_prev, NULL);

    return 1; /* Success! */
}
Exemplo n.º 20
0
/* build lists for iso-surfaces */
GLuint listTriaIso(pScene sc,pMesh mesh) {
  GLuint     dlist = 0;
  pTriangle  pt;
  pPoint     p0,p1;
  pMaterial  pm;
  pSolution  ps0,ps1;
  double     rgb[3];
  float      iso,cx,cy,cz,cc,kc;
  int        m,k,i,l,l1,nc,ncol;
  static double hsv[3]  = { 0.0, 1.0, 0.9 };
  static int    idir[5] = {0,1,2,0,1};

  /* default */
  if ( !mesh->nt || !mesh->nbb || mesh->typage == 1 )  return(0);
  if ( ddebug ) printf("create iso-values map list / TRIA\n");
  if ( egal(sc->iso.val[0],sc->iso.val[MAXISO-1]) )  return(0);

  /* create display list */
  dlist = glGenLists(1);
  glNewList(dlist,GL_COMPILE);
  if ( glGetError() )  return(0);

  /* build list */
  glBegin(GL_LINES);
  ncol = NBCOL;
  for (i=0; i<=ncol*(MAXISO-1); i++) {
    if ( i < ncol*(MAXISO-1) ) {
      l   = i / ncol;
      kc  = (i % ncol) / (float)ncol;
      iso = sc->iso.val[l]*(1.0-kc)+sc->iso.val[l+1]*kc;
      hsv[0] = sc->iso.col[l]*(1.0-kc)+sc->iso.col[l+1]*kc;
    }
    else {
      iso    = sc->iso.val[MAXISO-1];
      hsv[0] = sc->iso.col[MAXISO-1];
    }

    hsvrgb(hsv,rgb);
    glColor3dv(rgb);

    for (m=0; m<sc->par.nbmat; m++) {
      pm = &sc->material[m];
      k  = pm->depmat[LTria];
      if ( !k || pm->flag )  continue;

      while ( k != 0 ) {
        pt = &mesh->tria[k];
        if ( !pt->v[0] ) {
          k = pt->nxt;
          continue;
        }

        /* analyze edges */
        nc = 0;
        cx = cy = cz = 0.0;
        for (l=0; l<3; l++) {
          l1  = idir[l+1];
          p0  = &mesh->point[pt->v[l]];
          p1  = &mesh->point[pt->v[l1]];
          ps0 = &mesh->sol[pt->v[l]];
          ps1 = &mesh->sol[pt->v[l1]];
          if ( (ps0->bb > iso && ps1->bb <= iso) ||
               (ps0->bb < iso && ps1->bb >= iso) ) {
            cc = 0.0;
            if ( fabs(ps1->bb-ps0->bb) > 0.0 )
              cc = (iso-ps0->bb) / (ps1->bb-ps0->bb);
            if ( cc == 0.0 || cc == 1.0 )  continue;
            cx = p0->c[0]+cc*(p1->c[0]-p0->c[0]);
            cy = p0->c[1]+cc*(p1->c[1]-p0->c[1]);
            nc++;
            if ( mesh->dim == 2 )
              glVertex2f(cx,cy);
            else {
              cz = p0->c[2]+cc*(p1->c[2]-p0->c[2]);
              glVertex3f(cx,cy,cz);
            }
          }
          else if ( ps0->bb == iso && ps1->bb == iso ) {
            nc = 2;
            if ( mesh->dim == 2 ) {
              glVertex2f(p0->c[0],p0->c[1]);
              glVertex2f(p1->c[0],p1->c[1]);
              break;
            }
            else {
              glVertex3f(p0->c[0],p0->c[1],p0->c[2]);
              glVertex3f(p1->c[0],p1->c[1],p1->c[2]);
              break;
            }
          }
        }
        if ( nc > 0 && nc != 2 ) {
          if ( mesh->dim ==2 )  glVertex2f(cx,cy);
          else                  glVertex3f(cx,cy,cz);
        }
        k = pt->nxt;
      }
    }
  }
  glEnd();
  glEndList();
  return(dlist);
}
Exemplo n.º 21
0
void Effect::bind()
{
   glUseProgram(_program) ;
   GLenum test = glGetError();
    __currentEffect = this;
}
Exemplo n.º 22
0
/*     DigiBand (c)2005 Seijinohki PC Services and Software, This code written by Joe Wall with assitance from Velex
*      Loutzenhiser, and respected other parties.  This code is protected under the GPL License.  For any questions
*      regarding this code, please contact Joe @ www.seijinohki.net.
*
*      This software is free software; you can redistribute it and/or
*      modify it under the terms of the GNU Lesser General Public
*      License as published by the Free Software Foundation; either
*      version 2 of the License, or (at your option) any later version.
*
*      This software is distributed in the hope that it will be useful,
*      but WITHOUT ANY WARRANTY; without even the implied warranty of
*      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*      Lesser General Public License for more details.
*
*      You should have received a copy of the GNU Lesser General Public
*      License along with this software;  if not, write to the:
*      Free Software Foundation, Inc.
*      59 Temple Place - Suite 330
*      Boston, MA 02111-1307, USA
*/
int LoadTransTexture2( SDL_Surface *sdlimage,int currpos, int size){
	#ifdef EXCESSIVE
	printf("LoadTransTexture2\n");
	#endif
	if (size<1)size=1;
	if (currpos>=size)currpos=size-1;
	if (currpos<0)currpos=0;
	GLuint retval;
	void *raw;
	int w, h, i, j, bpp;
	Uint8 *srcPixel, *dstPixel;
	Uint32 truePixel;
	GLenum errorCode;
	
	bpp = sdlimage->format->BytesPerPixel;
	if (bpp < 2 || bpp > 4) {
		printf("VideoDriver::LoadSurface passed SDL_Surface * has an unusable bpp.\n");
	}
	
	w=sdlimage->w;
	h=sdlimage->h;
	int width=w/size;
	int ores=0;
	int tres=1;
	if (width<h){
		ores=h;
	}else{
		ores=width;
	}
	while (tres<ores){
		tres=tres*2;	
	}
	int xstart=currpos*tres;
	w = xstart + tres;
	
	raw = (void *)malloc(tres*tres * 4);
	dstPixel = (Uint8 *)raw;
	
	SDL_LockSurface(sdlimage);

	for (i = tres - 1; i >= 0; i--) {
		for (j = xstart; j < w; j++) {
			if (i*(h/tres) >= sdlimage->h || j*(width/tres) >= sdlimage->w) {
				memset(dstPixel, 0, 4);
			} else {
				srcPixel = (Uint8 *)sdlimage->pixels + (i*h/tres) * sdlimage->pitch + (j*width/tres) * bpp;
				switch(bpp){
					case 1:
						truePixel=*srcPixel;
						break;
					case 2:
						truePixel=*(Uint16 *)srcPixel;
						break;
					case 3:
						if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
							truePixel = srcPixel[0] << 16 | srcPixel[1]<<8 | srcPixel[2];
						}else{
							truePixel= srcPixel[0] | srcPixel[1]<<8 | srcPixel[2] << 16;
						}
						break;
					case 4:
						truePixel= *(Uint32 *)srcPixel;
						break;
					default:
						SDL_UnlockSurface(sdlimage);
      					if (sdlimage!=NULL)SDL_FreeSurface(sdlimage);
						free (raw);
						//free(srcPixel);
						//free(dstPixel);
						return 0;
						break;
				}
				SDL_GetRGBA(truePixel, sdlimage->format, &(dstPixel[0]), &(dstPixel[1]), & (dstPixel[2]), &(dstPixel[3]));
			}
			dstPixel += 4;
		}
	}

	SDL_UnlockSurface(sdlimage);

	while (glGetError()) { ; }	// eat any gl errors before we cause some of our own

	glGenTextures(1, &retval);

	errorCode = glGetError();
	if (errorCode != 0) {
		glDeleteTextures(1, &retval);
		free(raw);
		if (errorCode == GL_OUT_OF_MEMORY) {
   			if (sdlimage!=NULL)SDL_FreeSurface(sdlimage);
			printf("Out of Memory...");
			appisrunning=false;
			return 0;
		} else {
			return 0;
		}
	}
	glBindTexture(GL_TEXTURE_2D, retval);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	//gluBuild2DMipmaps( GL_TEXTURE_2D, 4, width, h, GL_RGBA, GL_UNSIGNED_BYTE, (Uint8 *)raw);
    if(allowanisotropic)glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxanisotropy);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, tres, tres, 0, GL_RGBA, GL_UNSIGNED_BYTE, (Uint8 *)raw);
	
	free(raw);
	//free(nimage);
	return retval;
}
Exemplo n.º 23
0
void draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
	const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect,
	const video::SColor* const colors, bool useAlphaChannelOfTexture)
{
	if (!irr_driver->isGLSL())
	{
		irr_driver->getVideoDriver()->draw2DImage(texture, destRect, sourceRect, clipRect, colors, useAlphaChannelOfTexture);
		return;
	}

	core::dimension2d<u32> frame_size =
		irr_driver->getVideoDriver()->getCurrentRenderTargetSize();
	const int screen_w = frame_size.Width;
	const int screen_h = frame_size.Height;
	float center_pos_x = destRect.UpperLeftCorner.X + destRect.LowerRightCorner.X;
	center_pos_x /= screen_w;
	center_pos_x -= 1.;
	float center_pos_y = destRect.UpperLeftCorner.Y + destRect.LowerRightCorner.Y;
	center_pos_y /= screen_h;
	center_pos_y = 1. - center_pos_y;
	float width = destRect.LowerRightCorner.X - destRect.UpperLeftCorner.X;
	width /= screen_w;
	float height = destRect.LowerRightCorner.Y - destRect.UpperLeftCorner.Y;
	height /= screen_h;

	const core::dimension2d<u32>& ss = texture->getOriginalSize();

	float tex_center_pos_x = sourceRect.UpperLeftCorner.X + sourceRect.LowerRightCorner.X;
	tex_center_pos_x /= ss.Width * 2.;
	//tex_center_pos_x -= 1.;
	float tex_center_pos_y = sourceRect.UpperLeftCorner.Y + sourceRect.LowerRightCorner.Y;
	tex_center_pos_y /= ss.Height * 2.;
	//tex_center_pos_y -= 1.;
	float tex_width = sourceRect.LowerRightCorner.X - sourceRect.UpperLeftCorner.X;
	tex_width /= ss.Width * 2.;
	float tex_height = sourceRect.LowerRightCorner.Y - sourceRect.UpperLeftCorner.Y;
	tex_height /= ss.Height * 2.;

	if (texture->isRenderTarget())
    {
		tex_height = - tex_height;
	}

	const f32 invW = 1.f / static_cast<f32>(ss.Width);
	const f32 invH = 1.f / static_cast<f32>(ss.Height);
	const core::rect<f32> tcoords(
		sourceRect.UpperLeftCorner.X * invW,
		sourceRect.UpperLeftCorner.Y * invH,
		sourceRect.LowerRightCorner.X * invW,
		sourceRect.LowerRightCorner.Y *invH);

	if (useAlphaChannelOfTexture)
	{
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}
	else
	{
		glDisable(GL_BLEND);
	}
    if (clipRect)
    {
        if (!clipRect->isValid())
            return;

        glEnable(GL_SCISSOR_TEST);
        const core::dimension2d<u32>& renderTargetSize = irr_driver->getVideoDriver()->getCurrentRenderTargetSize();
        glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y,
            clipRect->getWidth(), clipRect->getHeight());
    }
	if (colors)
	  drawTexColoredQuad(texture, colors, width, height, center_pos_x, center_pos_y,
	      tex_center_pos_x, tex_center_pos_y, tex_width, tex_height);
	else
	  drawTexQuad(texture, width, height, center_pos_x, center_pos_y,
	      tex_center_pos_x, tex_center_pos_y, tex_width, tex_height);
    if (clipRect)
        glDisable(GL_SCISSOR_TEST);
	glUseProgram(0);

    GLenum glErr = glGetError();
    if (glErr != GL_NO_ERROR)
    {
        Log::warn("IrrDriver", "GLWrap : OpenGL error %i\n", glErr);
    }
}
Exemplo n.º 24
0
bool GpuBuffer::create( Window* window, GLenum type, int size, BufferUsage usage )
{
    assert( window );
    
    if( bufferId_ )
    {
        destroy();
    }
    
    if( !window->hasExtOrVersion(VboFunctions::getExtensionId(),
                                 0x0105, 0x0200) )
    {
        FWARNING( ( "OpenGL Shading Language is not supported, couldn't find extension 'GL_ARB_vertex_buffer_object'!\n"));			
        return false;
    }
    
    // Get Function Pointers from Window (GL-Context):
    if( !g_VboFunctions->initFunctionPointers( window ) )
    {
        return false;
    }
    
    window_ = window;
    
    g_VboFunctions->genBuffers( 1, &bufferId_ );		
    
    if( !bufferId_ )
    {
        PWARNING << "[opengl] Could not create vertex_buffer_object!\n";
        return false;
    }
    
    g_VboFunctions->bindBuffer( type, bufferId_ );
    
    switch( usage )
    {
		case BufferUsage_Static_WriteOnly:
		case BufferUsage_Static_ReadWrite:
			glUsage_ = GL_STATIC_DRAW_ARB;
			break;
            
		case BufferUsage_Stream_WriteOnly:
		case BufferUsage_Stream_ReadWrite:
			glUsage_ = GL_STREAM_DRAW_ARB;
			break;

		case BufferUsage_Dynamic_WriteOnly:
		case BufferUsage_Dynamic_ReadWrite:
			glUsage_ = GL_DYNAMIC_DRAW_ARB;
			break;

		default:
			PWARNING << "[opengl] Invalid usage flags!\n";
			g_VboFunctions->deleteBuffers( 1, &bufferId_ );
			bufferId_ = 0;
			return false;
    }

    g_VboFunctions->bufferData( type, size, 0, glUsage_ );
    
    if( glGetError() )
    {
        PWARNING << "[opengl] Could not create vertex_buffer_object!\n";
        
        g_VboFunctions->deleteBuffers( 1, &bufferId_ );
        bufferId_ = 0;
        return false;
    }
    
    glType_			= type;
    isLocked_		= false;
    bufferSize_		= size;
    bufferUsage_	= usage;
    
    return true;
}
Exemplo n.º 25
0
bool TextureCube::Create()
{
    Release();

    if (!graphics_ || !width_ || !height_)
        return false;

    if (graphics_->IsDeviceLost())
    {
        URHO3D_LOGWARNING("Texture creation while device is lost");
        return true;
    }

    glGenTextures(1, &object_);

    // Ensure that our texture is bound to OpenGL texture unit 0
    graphics_->SetTextureForUpdate(this);

    // If not compressed, create the initial level 0 texture with null data
    GLenum format = GetSRGB() ? GetSRGBFormat(format_) : format_;
    GLenum externalFormat = GetExternalFormat(format_);
    GLenum dataType = GetDataType(format_);
    // If multisample, create renderbuffers for each face
    if (multiSample_ > 1)
    {
        for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
            renderSurfaces_[i]->CreateRenderBuffer(width_, height_, format, multiSample_);
    }

    bool success = true;
    if (!IsCompressed())
    {
        glGetError();
        for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
        {
            glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, width_, height_, 0, externalFormat, dataType, nullptr);
            if (GL_NO_ERROR!=glGetError())
                success = false;
        }
    }
    if (!success)
        URHO3D_LOGERROR("Failed to create texture");

    // Set mipmapping
    if (usage_ == TEXTURE_DEPTHSTENCIL)
        requestedLevels_ = 1;
    else if (usage_ == TEXTURE_RENDERTARGET)
    {
        if (requestedLevels_ != 1)
        {
            // Generate levels for the first time now
            RegenerateLevels();
            // Determine max. levels automatically
            requestedLevels_ = 0;
        }
    }
    levels_ = CheckMaxLevels(width_, height_, requestedLevels_);

    glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
    glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);

    // Set initial parameters, then unbind the texture
    UpdateParameters();
    graphics_->SetTexture(0, nullptr);

    return success;
}
Exemplo n.º 26
0
void WaterSurface::init()
{
	// init textures & buffers
	//textureManager->loadTexture(...);
	dudv_ID = textureManager->loadTexture(WATER_DUDV_MAP, "water_dudvmap", 3, false, GL_REPEAT, GL_LINEAR);

	glGenTextures(1, &cb_refl_ID);
		glBindTexture(GL_TEXTURE_2D, cb_refl_ID);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, g_WinWidth, g_WinHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
   
	   
	glGenTextures(1, &db_refl_ID );
		glBindTexture(GL_TEXTURE_2D, db_refl_ID );
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, g_WinWidth, g_WinHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);

	 glGenFramebuffersEXT(1, &fb_refl_ID);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb_refl_ID);
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, cb_refl_ID, 0);
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, db_refl_ID, 0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	
	glGenTextures(1, &cb_refr_ID);
		glBindTexture(GL_TEXTURE_2D, cb_refr_ID);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, g_WinWidth, g_WinHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
   
	   
	glGenTextures(1, &db_refr_ID );
		glBindTexture(GL_TEXTURE_2D, db_refr_ID );
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, g_WinWidth, g_WinHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);

	 glGenFramebuffersEXT(1, &fb_refr_ID);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb_refr_ID);
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, cb_refr_ID, 0);
		//glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_2D, color_tex1_id, 0);
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, db_refr_ID, 0);
	 
	 assert(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT)==GL_FRAMEBUFFER_COMPLETE_EXT);
	 assert( glGetError() == GL_NO_ERROR );
	 // init shaders...
	 int shaderID = shaderManager->loadShader("Water", WATER_VS_FILENAME, WATER_FS_FILENAME);
	 shader = shaderManager->getShader(shaderID);
 	 water_reflection_loc = shader->getLocation("water_reflection");
	 water_refraction_loc = shader->getLocation("water_refraction");
	 water_depth_loc = shader->getLocation("water_depthmap");
	 shader->linkTexture(textureManager->getTexture(dudv_ID));
}
Exemplo n.º 27
0
int main(int argc, char* argv[])
{

	MICROPROFILE_REGISTER_GROUP("Thread0", "Threads", 0x88008800);
	MICROPROFILE_REGISTER_GROUP("Thread1", "Threads", 0x88008800);
	MICROPROFILE_REGISTER_GROUP("Thread2", "Threads", 0x88008800);
	MICROPROFILE_REGISTER_GROUP("Thread2xx", "Threads", 0x88008800);
	MICROPROFILE_REGISTER_GROUP("GPU", "main", 0x88fff00f);
	MICROPROFILE_REGISTER_GROUP("MAIN", "main", 0x88fff00f);

	printf("press 'z' to toggle microprofile drawing\n");
	printf("press 'right shift' to pause microprofile update\n");
	printf("press 'x' to toggle profiling\n");
	printf("press 'c' to toggle enable of all profiler groups\n");
	MicroProfileOnThreadCreate("AA_Main");
	if(SDL_Init(SDL_INIT_VIDEO) < 0) {
		return 1;
	}


	SDL_GL_SetAttribute(SDL_GL_RED_SIZE,    	    8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,  	    8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,   	    8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,  	    8);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,  	    24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,  	    8);	
	SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,		    32);	
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,	    1);	
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetSwapInterval(1);

	SDL_Window * pWindow = SDL_CreateWindow("microprofiledemo", 10, 10, WIDTH, HEIGHT, SDL_WINDOW_OPENGL);
	if(!pWindow)
		return 1;

	SDL_GLContext glcontext = SDL_GL_CreateContext(pWindow);

	glewExperimental=1;
	GLenum err=glewInit();
	if(err!=GLEW_OK)
	{
		__BREAK();
	}
	glGetError(); //glew generates an error
		


#if MICROPROFILE_ENABLED
	MicroProfileGpuInitGL();
	MicroProfileDrawInit();
	MP_ASSERT(glGetError() == 0);
	MicroProfileToggleDisplayMode();
#endif

	StartFakeWork();
	while(!g_nQuit)
	{
		MICROPROFILE_SCOPE(MAIN);

		SDL_Event Evt;
		while(SDL_PollEvent(&Evt))
		{
			HandleEvent(&Evt);
		}

		glClearColor(0.3f,0.4f,0.6f,0.f);
		glViewport(0, 0, WIDTH, HEIGHT);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


#if 1||FAKE_WORK
		{
			MICROPROFILE_SCOPEI("BMain", "Dummy", 0xff3399ff);
			for(uint32_t i = 0; i < 14; ++i)
			{
				MICROPROFILE_SCOPEI("BMain", "1ms", 0xff3399ff);
				MICROPROFILE_META_CPU("Sleep",1);

				usleep(1000);
			}
		}
#endif




		MicroProfileMouseButton(g_MouseDown0, g_MouseDown1);
		MicroProfileMousePosition(g_MouseX, g_MouseY, g_MouseDelta);
		g_MouseDelta = 0;


		MicroProfileFlip();
		{
			MICROPROFILE_SCOPEGPUI("MicroProfileDraw", 0x88dd44);
			float projection[16];
			float left = 0.f;
			float right = WIDTH;
			float bottom = HEIGHT;
			float top = 0.f;
			float near = -1.f;
			float far = 1.f;
			memset(&projection[0], 0, sizeof(projection));

			projection[0] = 2.0f / (right - left);
			projection[5] = 2.0f / (top - bottom);
			projection[10] = -2.0f / (far - near);
			projection[12] = - (right + left) / (right - left);
			projection[13] = - (top + bottom) / (top - bottom);
			projection[14] = - (far + near) / (far - near);
			projection[15] = 1.f; 
 
 			glEnable(GL_BLEND);
 			glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 			glDisable(GL_DEPTH_TEST);
#if MICROPROFILE_ENABLED
			MicroProfileBeginDraw(WIDTH, HEIGHT, &projection[0]);
			MicroProfileDraw(WIDTH, HEIGHT);
			MicroProfileEndDraw();
#endif
			glDisable(GL_BLEND);
		}

		MICROPROFILE_SCOPEI("MAIN", "Flip", 0xffee00);
		SDL_GL_SwapWindow(pWindow);
	}
	StopFakeWork();

	MicroProfileShutdown();

  	SDL_GL_DeleteContext(glcontext);  
 	SDL_DestroyWindow(pWindow);
 	SDL_Quit();


	return 0;
}
Exemplo n.º 28
0
int main(int argc, char* argv[])
{
	b3Clock clock;

	float dt = 1./120.f;
	int width = 1024;
	int height=768;

	app = new SimpleOpenGL3App("AllBullet2Demos",width,height);
	app->m_instancingRenderer->setCameraDistance(13);
	app->m_instancingRenderer->setCameraPitch(0);
	app->m_instancingRenderer->setCameraTargetPosition(b3MakeVector3(0,0,0));
	app->m_window->setMouseMoveCallback(MyMouseMoveCallback);
	app->m_window->setMouseButtonCallback(MyMouseButtonCallback);
	app->m_window->setKeyboardCallback(MyKeyboardCallback);

	GLint err = glGetError();
    assert(err==GL_NO_ERROR);
	
	sth_stash* fontstash=app->getFontStash();
	gui = new GwenUserInterface;
	gui->init(width,height,fontstash,app->m_window->getRetinaScale());

	int numDemos = sizeof(allDemos)/sizeof(BulletDemoEntry);
	
	for (int i=0;i<numDemos;i++)
	{
		allNames.push_back(allDemos[i].m_name);
	}
		
	selectDemo(loadCurrentDemoEntry(startFileName));
	gui->registerComboBox(DEMO_SELECTION_COMBOBOX,allNames.size(),&allNames[0],sCurrentDemoIndex);
		
	//const char* names2[] = {"comboF", "comboG","comboH"};
	//gui->registerComboBox(2,3,&names2[0],0);

	gui->setComboBoxCallback(MyComboBoxCallback);

	unsigned long int	prevTimeInMicroseconds = clock.getTimeMicroseconds();

	do
	{

		GLint err = glGetError();
		assert(err==GL_NO_ERROR);
		app->m_instancingRenderer->init();
		app->m_instancingRenderer->updateCamera();
		
		app->drawGrid();
		
		static int frameCount = 0;
		frameCount++;

		if (0)
		{
		char bla[1024];
		
		sprintf(bla,"Simple test frame %d", frameCount);
		
		app->drawText(bla,10,10);
		}

		if (sCurrentDemo)
		{
			if (!pauseSimulation)
			{
				unsigned long int	curTimeInMicroseconds = clock.getTimeMicroseconds();
				unsigned long int diff = curTimeInMicroseconds-prevTimeInMicroseconds;
				float deltaTimeInSeconds = (diff)*1.e-6;
				//printf("---------------------------------------------------\n");
				//printf("Framecount = %d\n",frameCount);

				sCurrentDemo->stepSimulation(deltaTimeInSeconds);//1./60.f);
				prevTimeInMicroseconds = curTimeInMicroseconds;
			}
			sCurrentDemo->renderScene();
		}

		static int toggle = 1;
		if (1)
		{
		gui->draw(app->m_instancingRenderer->getScreenWidth(),app->m_instancingRenderer->getScreenHeight());
		}
		toggle=1-toggle;
		app->swapBuffer();
	} while (!app->m_window->requestedExit());

	selectDemo(0);
	delete gui;
	delete app;
	return 0;
}
Exemplo n.º 29
0
void col::render::GLPrintLastError() {
    for(GLenum error = glGetError(); error != GL_NO_ERROR; error = glGetError()) {
        COL_LOG_ERROR(col::render::GLGetStatusString(error));
    }
}
Exemplo n.º 30
0
static void Init( void )
{
   GLint errorPos;

   /* Yes, this could be expressed more efficiently */
   static const char *fragProgramText =
      "!!ARBfp1.0\n"
#if DO_FRAGMENT_FOG
      "OPTION ARB_fog_linear; \n"
#endif
      "PARAM Diffuse = state.material.diffuse; \n"
      "PARAM Specular = state.material.specular; \n"
      "PARAM LightPos = program.local[3]; \n"
      "TEMP lightDir, normal, len; \n"
      "TEMP dotProd, specAtten; \n"
      "TEMP diffuseColor, specularColor; \n"

      "# Compute normalized light direction \n"
      "DP3 len.x, LightPos, LightPos; \n"
      "RSQ len.y, len.x; \n"
      "MUL lightDir, LightPos, len.y; \n"

      "# Compute normalized normal \n"
      "DP3 len.x, fragment.texcoord[0], fragment.texcoord[0]; \n"
      "RSQ len.y, len.x; \n"
      "MUL normal, fragment.texcoord[0], len.y; \n"

      "# Compute dot product of light direction and normal vector\n"
      "DP3 dotProd, lightDir, normal; \n"

      "MUL diffuseColor, Diffuse, dotProd;            # diffuse attenuation\n"

      "POW specAtten.x, dotProd.x, {20.0}.x;          # specular exponent\n"

      "MUL specularColor, Specular, specAtten.x;      # specular attenuation\n"

#if DO_FRAGMENT_FOG
      "# need to clamp color to [0,1] before fogging \n"
      "ADD_SAT result.color, diffuseColor, specularColor; # add colors\n"
#else
      "# clamping will be done after program's finished \n"
      "ADD result.color, diffuseColor, specularColor; # add colors\n"
#endif
      "END \n"
      ;

   static const char *vertProgramText =
      "!!ARBvp1.0\n"
      "ATTRIB pos = vertex.position; \n"
      "ATTRIB norm = vertex.normal; \n"
      "PARAM modelview[4] = { state.matrix.modelview }; \n"
      "PARAM modelviewProj[4] = { state.matrix.mvp }; \n"
      "PARAM invModelview[4] = { state.matrix.modelview.invtrans }; \n"

      "# typical modelview/projection transform \n"
      "DP4 result.position.x, pos, modelviewProj[0]; \n"
      "DP4 result.position.y, pos, modelviewProj[1]; \n"
      "DP4 result.position.z, pos, modelviewProj[2]; \n"
      "DP4 result.position.w, pos, modelviewProj[3]; \n"

      "# transform normal by inv transpose of modelview, put in tex0 \n"
      "DP3 result.texcoord[0].x, norm, invModelview[0]; \n"
      "DP3 result.texcoord[0].y, norm, invModelview[1]; \n"
      "DP3 result.texcoord[0].z, norm, invModelview[2]; \n"
      "DP3 result.texcoord[0].w, norm, invModelview[3]; \n"

#if DO_FRAGMENT_FOG
      "# compute fog coordinate = vertex eye-space Z coord (negated)\n"
      "DP4 result.fogcoord, -pos, modelview[2]; \n"
#endif
      "END\n";
      ;

   if (!glutExtensionSupported("GL_ARB_vertex_program")) {
      printf("Sorry, this demo requires GL_ARB_vertex_program\n");
      exit(1);
   }
   if (!glutExtensionSupported("GL_ARB_fragment_program")) {
      printf("Sorry, this demo requires GL_ARB_fragment_program\n");
      exit(1);
   }
         
   /*
    * Get extension function pointers.
    */
   glProgramLocalParameter4fvARB_func = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) glutGetProcAddress("glProgramLocalParameter4fvARB");
   assert(glProgramLocalParameter4fvARB_func);

   glProgramLocalParameter4dARB_func = (PFNGLPROGRAMLOCALPARAMETER4DARBPROC) glutGetProcAddress("glProgramLocalParameter4dARB");
   assert(glProgramLocalParameter4dARB_func);

   glGetProgramLocalParameterdvARB_func = (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) glutGetProcAddress("glGetProgramLocalParameterdvARB");
   assert(glGetProgramLocalParameterdvARB_func);

   glGenProgramsARB_func = (PFNGLGENPROGRAMSARBPROC) glutGetProcAddress("glGenProgramsARB");
   assert(glGenProgramsARB_func);

   glProgramStringARB_func = (PFNGLPROGRAMSTRINGARBPROC) glutGetProcAddress("glProgramStringARB");
   assert(glProgramStringARB_func);

   glBindProgramARB_func = (PFNGLBINDPROGRAMARBPROC) glutGetProcAddress("glBindProgramARB");
   assert(glBindProgramARB_func);

   glIsProgramARB_func = (PFNGLISPROGRAMARBPROC) glutGetProcAddress("glIsProgramARB");
   assert(glIsProgramARB_func);

   glDeleteProgramsARB_func = (PFNGLDELETEPROGRAMSARBPROC) glutGetProcAddress("glDeleteProgramsARB");
   assert(glDeleteProgramsARB_func);

   /*
    * Fragment program
    */
   glGenProgramsARB_func(1, &FragProg);
   assert(FragProg > 0);
   glBindProgramARB_func(GL_FRAGMENT_PROGRAM_ARB, FragProg);
   glProgramStringARB_func(GL_FRAGMENT_PROGRAM_ARB,
                           GL_PROGRAM_FORMAT_ASCII_ARB,
                           strlen(fragProgramText),
                           (const GLubyte *) fragProgramText);
   glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
   if (glGetError() != GL_NO_ERROR || errorPos != -1) {
      int l = FindLine(fragProgramText, errorPos);
      printf("Fragment Program Error (pos=%d line=%d): %s\n", errorPos, l,
             (char *) glGetString(GL_PROGRAM_ERROR_STRING_ARB));
      exit(0);
   }
   assert(glIsProgramARB_func(FragProg));

   /*
    * Do some sanity tests
    */
   {
      GLdouble v[4];
      glProgramLocalParameter4dARB_func(GL_FRAGMENT_PROGRAM_ARB, 8,
                                   10.0, 20.0, 30.0, 40.0);
      glGetProgramLocalParameterdvARB_func(GL_FRAGMENT_PROGRAM_ARB, 8, v);
      assert(v[0] == 10.0);
      assert(v[1] == 20.0);
      assert(v[2] == 30.0);
      assert(v[3] == 40.0);
   }

   /*
    * Vertex program
    */
   glGenProgramsARB_func(1, &VertProg);
   assert(VertProg > 0);
   glBindProgramARB_func(GL_VERTEX_PROGRAM_ARB, VertProg);
   glProgramStringARB_func(GL_VERTEX_PROGRAM_ARB,
                           GL_PROGRAM_FORMAT_ASCII_ARB,
                           strlen(vertProgramText),
                           (const GLubyte *) vertProgramText);
   glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
   if (glGetError() != GL_NO_ERROR || errorPos != -1) {
      int l = FindLine(fragProgramText, errorPos);
      printf("Vertex Program Error (pos=%d line=%d): %s\n", errorPos, l,
             (char *) glGetString(GL_PROGRAM_ERROR_STRING_ARB));
      exit(0);
   }
   assert(glIsProgramARB_func(VertProg));

   /*
    * Misc init
    */
   glClearColor(0.3, 0.3, 0.3, 0.0);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_LIGHT0);
   glEnable(GL_LIGHTING);
   glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, Diffuse);
   glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Specular);
   glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 20.0);

#if DO_FRAGMENT_FOG
   {
      /* Green-ish fog color */
      static const GLfloat fogColor[4] = {0.5, 1.0, 0.5, 0};
      glFogi(GL_FOG_MODE, GL_LINEAR);
      glFogfv(GL_FOG_COLOR, fogColor);
      glFogf(GL_FOG_START, 5.0);
      glFogf(GL_FOG_END, 25.0);
      glEnable(GL_FOG);
   }
#endif

   printf("GL_RENDERER = %s\n", (char *) glGetString(GL_RENDERER));
   printf("Press p to toggle between per-pixel and per-vertex lighting\n");
}