示例#1
0
///@brief Check all available joysticks for an Xbox Controller
/// and store its idx in g_joystickIdx.
/// Unfortunately, this operation is too time-consuming to call every frame
/// in a VR app. The workaround is to call it on key press, space or 'G'.
void FindPreferredJoystick()
{
    g_joystickIdx = -1;
    for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i)
    {
        if (GL_FALSE == glfwJoystickPresent(i))
            continue;

        const char* pJoyName = glfwGetJoystickName(i);
        if (pJoyName == NULL)
            continue;

        int numAxes = 0;
        int numButtons = 0;
        glfwGetJoystickAxes(i, &numAxes);
        glfwGetJoystickButtons(i, &numButtons);
        LOG_INFO("Glfw found Joystick #%d: %s w/ %d axes, %d buttons", i, pJoyName, numAxes, numButtons);

        // Take an educated guess that this is an Xbox controller - glfw's
        // id string says "Microsoft PC Joystick" for most gamepad types.
        ///@todo Why does GLFW on Linux return a different, more descriptive string?
        if (numAxes == 5 && numButtons == 14)
        {
            g_joystickIdx = i;
            return;
        }
    }
}
示例#2
0
		void draw() override {
			ImVec4 clear_color = ImColor(114, 144, 154);
			static float f = 0.0f;
			// ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.5);
			// ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.8, 0, 0, 0.5));
			ImGui::Begin("Test Window");
			ImGui::SetWindowSize(ImVec2(200, 400), ImGuiSetCond_Always);

			int count;
			const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &count);

			ImGui::Text(glfwGetJoystickName(GLFW_JOYSTICK_1));

			for(int i = 0; i < count; i++) {
				joyAx[i] = axes[i];
				char joyname[30];
				sprintf(joyname, "Axis %d", i);
            	ImGui::SliderFloat(joyname, &joyAx[i], -1.0f, 1.0f);
			}

            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);

            ImGui::End();
            // ImGui::PopStyleColor();
		};
示例#3
0
Joystick::Joystick(int _id, float _deadZone) : 
	id(_id),
	name("No controller found"),
	deadZone(_deadZone)
{
	int present = glfwJoystickPresent(id);
	if(present){
		name = glfwGetJoystickName(id);
		
		// we'll need to test a bunch of different devices to bin these properly
		// only the xbox one has actually been checked
		if (name.compare("Wireless Controller") == 0){
			// PS4
			initPlaystation();
		}else if (name.compare("PLAYSTATION(R)3 Controller") == 0){
			// PS3
			initPlaystation();
		}else if (name.compare("Microsoft PC-joystick driver") == 0){
			// XBOX
			initXbox();
		}else{
			// GENERIC
			initXbox();
		}
		std::stringstream ss;
		ss << "Controller connected to slot " << id << ": " << name;
		Log::info(ss.str());
	}
}
示例#4
0
// Joysticks
void VogueWindow::UpdateJoySticks()
{
	for (int i = 0; i < sizeof(m_joysticks) / sizeof(Joystick); i++)
	{
		Joystick* j = m_joysticks + i;

		if (glfwJoystickPresent(GLFW_JOYSTICK_1 + i))
		{
			const float* axes;
			const unsigned char* buttons;
			int axis_count, button_count;

			free(j->m_name);
			j->m_name = strdup(glfwGetJoystickName(GLFW_JOYSTICK_1 + i));

			axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1 + i, &axis_count);
			if (axis_count != j->m_axisCount)
			{
				j->m_axisCount = axis_count;
				j->m_axes = (float*)realloc(j->m_axes, j->m_axisCount * sizeof(float));
			}

			memcpy(j->m_axes, axes, axis_count * sizeof(float));

			buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1 + i, &button_count);
			if (button_count != j->m_buttonCount)
			{
				j->m_buttonCount = button_count;
				j->m_buttons = (unsigned char*)realloc(j->m_buttons, j->m_buttonCount);
			}

			memcpy(j->m_buttons, buttons, button_count * sizeof(unsigned char));

			if (!j->m_present)
			{
				printf("\nFound joystick %i named \'%s\' with %i axes, %i buttons\n",
					i + 1, j->m_name, j->m_axisCount, j->m_buttonCount);

				m_joystickCount++;
			}

			j->m_present = GL_TRUE;
		}
		else
		{
			if (j->m_present)
			{
				printf("\nLost joystick %i named \'%s\'\n", i + 1, j->m_name);

				free(j->m_name);
				free(j->m_axes);
				free(j->m_buttons);
				memset(j, 0, sizeof(Joystick));

				m_joystickCount--;
			}
		}
	}
}
示例#5
0
文件: joysticks.c 项目: eledot/Plum
static void refresh_joysticks(void)
{
    int i;

    for (i = 0;  i < sizeof(joysticks) / sizeof(Joystick);  i++)
    {
        Joystick* j = joysticks + i;

        if (glfwGetJoystickParam(GLFW_JOYSTICK_1 + i, GLFW_PRESENT))
        {
            int axis_count, button_count;

            free(j->name);
            j->name = strdup(glfwGetJoystickName(GLFW_JOYSTICK_1 + i));

            axis_count = glfwGetJoystickParam(GLFW_JOYSTICK_1 + i, GLFW_AXES);
            if (axis_count != j->axis_count)
            {
                j->axis_count = axis_count;
                j->axes = realloc(j->axes, j->axis_count * sizeof(float));
            }

            glfwGetJoystickAxes(GLFW_JOYSTICK_1 + i, j->axes, j->axis_count);

            button_count = glfwGetJoystickParam(GLFW_JOYSTICK_1 + i, GLFW_BUTTONS);
            if (button_count != j->button_count)
            {
                j->button_count = button_count;
                j->buttons = realloc(j->buttons, j->button_count);
            }

            glfwGetJoystickButtons(GLFW_JOYSTICK_1 + i, j->buttons, j->button_count);

            if (!j->present)
            {
                printf("Found joystick %i named \'%s\' with %i axes, %i buttons\n",
                       i + 1, j->name, j->axis_count, j->button_count);

                joystick_count++;
            }

            j->present = GL_TRUE;
        }
        else
        {
            if (j->present)
            {
                printf("Lost joystick %i named \'%s\'\n", i + 1, j->name);

                free(j->name);
                free(j->axes);
                free(j->buttons);
                memset(j, 0, sizeof(Joystick));

                joystick_count--;
            }
        }
    }
}
示例#6
0
				void printAvailables() {
					for (int i = 0; i < GLFW_JOYSTICK_LAST; i++) {
						if (glfwJoystickPresent(i) == GL_TRUE) {
							const char *name = glfwGetJoystickName(i);
							std::cout << "[Joystick] " << name << " id: " << i << std::endl;
						}
					}
				}
 int GlfwApplication::Run() {
   CHECK_STATE(glfwInit() != -1);
   glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
   glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
   glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
   glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
   if (minimized) {
     window = glfwCreateWindow(kMinimizedWidth, kMinimizedHeight, title.c_str(), nullptr, nullptr);
   } else {
     window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr);
   }
   CHECK_STATE(window != nullptr);
   glfwSetKeyCallback(window, HandleKeyboard);
   glfwSetMouseButtonCallback(window, HandleMouseButton);
   glfwSetFramebufferSizeCallback(window, HandleReshape);
   glfwMakeContextCurrent(window);
   glfwSwapInterval(1);
   std::cout << glGetString(GL_VERSION) << std::endl;
   std::cout << glfwGetJoystickName(GLFW_JOYSTICK_1) << std::endl;
   renderer.Create();
   int framebuffer_width, framebuffer_height;
   glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height);
   HandleReshape(window, framebuffer_width, framebuffer_height);
   controller.Setup();
   while (!glfwWindowShouldClose(window)) {
     if (keyboard.GetKeyVelocity(GLFW_KEY_TAB) > 0) {
       if (minimized) {
         glfwSetWindowSize(window, width, height);
         glfwShowWindow(window);
       } else {
         glfwHideWindow(window);
         glfwSetWindowSize(window, kMinimizedWidth, kMinimizedHeight);
       }
       minimized = !minimized;
     }
     if (minimized) {
       glClearColor(1.0, 1.0, 1.0, 1.0);
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     } else {
       renderer.Render();
     }
     controller.Update();
     keyboard.Update();
     mouse.Update();
     double x, y;
     glfwGetCursorPos(window, &x, &y);
     mouse.OnCursorMove(glm::vec2(x, y));
     joystick.Update();
     input.Update();
     glfwSwapBuffers(window);
     glfwPollEvents();
     if (minimized) {
       usleep(16666);
     }
   }
   glfwTerminate();
   return 0;
 }
示例#8
0
JNIEXPORT jstring JNICALL Java_com_badlogic_jglfw_Glfw_glfwGetJoystickName(JNIEnv* env, jclass clazz, jint joy) {


//@line:881

		return env->NewStringUTF(glfwGetJoystickName(joy));
	

}
示例#9
0
bool RawController::activate(int id){
	reset();
	
	_id = id;
	_name = std::string(glfwGetJoystickName(_id));
	_guid = std::string(glfwGetJoystickGUID(_id));
	Log::Info() << Log::Input << "Raw joystick named " << _name << "." << std::endl;
	
	return true;
}
map<int,string> ofxGLFWJoystick::getJoystickList(){

	map<int,string> list;
	for(int i = 0; i < GLFW_JOYSTICK_LAST; i++){
		if(glfwJoystickPresent(i)){
			list[i] = string(glfwGetJoystickName(i));
		}
	}
	return list;
}
示例#11
0
bool Joystick::init(const int index_) {

        _id = index_;
        _name = glfwGetJoystickName(_id);
        _axes = glfwGetJoystickAxes(_id, &_axesNum);
        _polledButtons = glfwGetJoystickButtons(_id, &_buttonsNum);
        for (int i = 0; i < _buttonsNum; ++ i)
                _buttons.push_back(false);
        
	return true;
}
示例#12
0
文件: GamePad.cpp 项目: bakge/bakge
GamePad* GamePad::Detect()
{
    GamePad* Pad = new GamePad;
    for(int i=GLFW_JOYSTICK_1;i<GLFW_JOYSTICK_LAST;++i) {
        if(glfwJoystickPresent(i) == GL_TRUE) {
            Pad->Handle = i;
            Log("GamePad: Detected joystick %d (%s)\n", i,
                                    glfwGetJoystickName(i));
        }
    }

    Pad->GetButtonPressed(0);
    Pad->GetAxis(0);

    return Pad;
}
示例#13
0
 std::vector<JoystickState> GLFW_App::get_joystick_states() const
 {
     std::vector<JoystickState> ret;
     int count;
     for(int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++)
     {
         if(!glfwJoystickPresent(i)) continue;
         
         const float *glfw_axis = glfwGetJoystickAxes(i, &count);
         std::vector<float> axis(glfw_axis, glfw_axis + count);
         
         const uint8_t *glfw_buttons = glfwGetJoystickButtons(i, &count);
         std::vector<uint8_t> buttons(glfw_buttons, glfw_buttons + count);
         
         std::string name(glfwGetJoystickName(i));
         ret.push_back(JoystickState(name, buttons, axis));
     }
     return ret;
 }
示例#14
0
文件: events.c 项目: Archer-sys/glfw
static void joystick_callback(int joy, int event)
{
    if (event == GLFW_CONNECTED)
    {
        int axisCount, buttonCount;

        glfwGetJoystickAxes(joy, &axisCount);
        glfwGetJoystickButtons(joy, &buttonCount);

        printf("%08x at %0.3f: Joystick %i (%s) was connected with %i axes and %i buttons\n",
               counter++, glfwGetTime(),
               joy,
               glfwGetJoystickName(joy),
               axisCount,
               buttonCount);
    }
    else
    {
        printf("%08x at %0.3f: Joystick %i was disconnected\n",
               counter++, glfwGetTime(), joy);
    }
}
void ofxGLFWJoystick::lookForJoysticks(){

	int n = 0;
	for(int i = 0; i < GLFW_JOYSTICK_LAST; i++){
		if(glfwJoystickPresent(i)){
			joyData[i].available = true;
			string name = string(glfwGetJoystickName(i));
			if(name != joyData[i].name){
				joyData[i].name = name;
				ofLogNotice("ofxGLFWJoystick") << "Joystick Found at index " << i << ": '" << name << "'";
				joyData[i].axisData = glfwGetJoystickAxes(i, &joyData[i].numAxis);
				joyData[i].buttonData = glfwGetJoystickButtons(i, &joyData[i].numButtons);
			}
			n++;
		}else{
			if (joyData[i].name.size()){
				ofLogNotice("ofxGLFWJoystick") << "Joystick Lost at index " << i << ": '" << joyData[i].name << "'";
			}
			joyData[i].available = false;
			joyData[i].name = "";
		}
	}
	numJoysticks = n;
}
示例#16
0
int main()
{
	Engine engine(screenWidth, screenHeight);
	if(!engine.init())
	{
		GLFWwindow* window = engine.getWindow();

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

		Model crytekSponza("../obj/crytek-sponza/sponza.obj", camera, engine);
		//Model teapot("../obj/teapot/teapot.obj", camera, engine);
		//Model dabrovicSponza("../obj/dabrovic-sponza/sponza.obj", camera, engine);
		//Model sibenikCathedral("../obj/sibenik-cathedral/sibenik.obj", camera, engine);
		//Model nanosuit("../obj/nanosuit/nanosuit.obj", camera, engine);
		//Shader shader("shaders/vertex.glsl", "shaders/fragment.glsl");

		if(glfwJoystickPresent(0))
		{
			cout << glfwGetJoystickName(0) << " : detected" << endl;
			cout << "Left stick : movement control" << endl;
			cout << "Right stick : camera control" << endl;
		}

		double ellapsed_time = glfwGetTime();

		Framebuffer::vertexQuad();
		Framebuffer frameBuffer(true, screenWidth, screenHeight);

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

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

			glClearDepth(1.0);
			glClearColor(0.8f, 0.8f, 0.8f, 1.0f);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			//frameBuffer.enable();
			//glViewport(0, 0, 1280, 720);
			crytekSponza.Draw();
			//frameBuffer.disable();

			/*
			//glViewport(0, 0, 1280, 720);

			glClearDepth(1.0);
			glClearColor(0.8f, 0.8f, 0.8f, 1.0f);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			shader.Use();

			glEnable(GL_TEXTURE_2D);
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, frameBuffer.getRenderedTexture());

			glActiveTexture(GL_TEXTURE1);
			glBindTexture(GL_TEXTURE_2D, frameBuffer.getDepthTexture());
			
			Framebuffer::drawQuad();

			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, 0);
			glDisable(GL_TEXTURE_2D);
			*/

			/*
			glEnable(GL_SCISSOR_TEST);
			glScissor(0, 0, 1280, 720);
			glClear(GL_DEPTH_BUFFER_BIT);
			glViewport(0, 0, 300, 168);

			glEnable(GL_TEXTURE_2D);
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, frameBuffer.getRenderedTexture());
			glUniform1i(glGetUniformLocation(shader.Program, "texBuffer"), 0);
			
			Framebuffer::drawQuad();

			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, 0);
			glDisable(GL_TEXTURE_2D);
			*/
			
			engine.swapBuffer();

			/*
			if((glfwGetTime() - ellapsed_time) / 1000.0 < 16.67)
				Sleep(static_cast<DWORD>(16.67 - ((glfwGetTime() - ellapsed_time) / 1000.0)));
			ellapsed_time = glfwGetTime();
			*/
		}
	}

	return 0;
}
int main(int argc, char** argv)
{
#if defined(_WIN32)
    LOG_INFO("Windows build.");
#elif defined(_LINUX)
    LOG_INFO("Linux build.");
#elif defined(_MACOS)
    LOG_INFO("MacOS build.");
#endif

    bool useOpenGLCoreContext = false;
#ifdef USE_CORE_CONTEXT
    useOpenGLCoreContext = true;
#endif

    g_renderMode.outputType = RenderingMode::OVR_SDK;

    LOG_INFO("Using GLFW3 backend.");
    LOG_INFO("Compiled against GLFW %i.%i.%i",
        GLFW_VERSION_MAJOR,
        GLFW_VERSION_MINOR,
        GLFW_VERSION_REVISION);
    int major, minor, revision;
    glfwGetVersion(&major, &minor, &revision);
    LOG_INFO("Running against GLFW %i.%i.%i", major, minor, revision);
    LOG_INFO("glfwGetVersionString: %s", glfwGetVersionString());

    // Command line options
    for (int i=0; i<argc; ++i)
    {
        const std::string a = argv[i];
        LOG_INFO("argv[%d]: %s", i, a.c_str());
        if (!a.compare("-sdk"))
        {
            g_renderMode.outputType = RenderingMode::OVR_SDK;
        }
        else if (!a.compare("-client"))
        {
            g_renderMode.outputType = RenderingMode::OVR_Client;
        }
        else if (!a.compare("-core"))
        {
            useOpenGLCoreContext = true;
        }
        else if (!a.compare("-compat"))
        {
            useOpenGLCoreContext = false;
        }
    }

#ifdef USE_OCULUSSDK
    g_app.initHMD();
#else
    g_renderMode.outputType = RenderingMode::Mono_Buffered;
#endif

    GLFWwindow* l_Window = NULL;
    glfwSetErrorCallback(ErrorCallback);
    if (!glfwInit())
    {
        exit(EXIT_FAILURE);
    }

    // Log system monitor information
    const GLFWmonitor* pPrimary = glfwGetPrimaryMonitor();
    int monitorCount = 0;
    GLFWmonitor** ppMonitors = glfwGetMonitors(&monitorCount);
    for (int i=0; i<monitorCount; ++i)
    {
        GLFWmonitor* pCur = ppMonitors[i];
        const GLFWvidmode* mode = glfwGetVideoMode(pCur);
        if (mode != NULL)
        {
            (void)pPrimary;
            LOG_INFO("Monitor #%d: %dx%d @ %dHz %s",
                i,
                mode->width,
                mode->height,
                mode->refreshRate,
                pCur==pPrimary ? "Primary":"");
        }
    }

    bool swapBackBufferDims = false;

    // Context setup - before window creation
    glfwWindowHint(GLFW_DEPTH_BITS, 16);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, useOpenGLCoreContext ? GLFW_OPENGL_CORE_PROFILE : GLFW_OPENGL_COMPAT_PROFILE);
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#ifdef _DEBUG
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif

#if defined(USE_OSVR)
    std::string windowTitle = "";
    windowTitle = PROJECT_NAME "-GLFW-Osvr";

    if (g_app.UsingDebugHmd())
    {
        const hmdRes sz = { 800, 600 };
        // Create a normal, decorated application window
        LOG_INFO("Using Debug HMD mode.");
        windowTitle = PROJECT_NAME "-GLFW-DebugHMD";
        g_renderMode.outputType = RenderingMode::Mono_Buffered;

        l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL);
    }
    else
    {
        const hmdRes sz = {
            g_app.getHmdResolution().h,
            g_app.getHmdResolution().w
        };
        const winPos pos = g_app.getHmdWindowPos();
        g_renderMode.outputType = RenderingMode::SideBySide_Undistorted;

        LOG_INFO("Using Extended desktop mode.");
        windowTitle = PROJECT_NAME "-GLFW-Extended";

        LOG_INFO("Creating GLFW_DECORATED window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y);
        glfwWindowHint(GLFW_DECORATED, 0);
        l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL);
        glfwWindowHint(GLFW_DECORATED, 1);
        glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
        glfwSetWindowPos(l_Window, pos.x, pos.y);
    }

#elif defined(OVRSDK06)
    std::string windowTitle = "";

    LOG_INFO("Using SDK 0.6.0.0's direct mode.");
    windowTitle = PROJECT_NAME "-GLFW-06-Direct";

    GLFWmonitor* monitor = glfwGetPrimaryMonitor();
    const GLFWvidmode* mode = glfwGetVideoMode(monitor);
    ovrSizei sz;
    ovrVector2i pos;
    sz.w = mode->width/2;
    sz.h = mode->height/2;
    pos.x = 100;
    pos.y = 100;
    // Create just a regular window for presenting OVR SDK 0.6's mirror texture
    ///@todo Is it any faster with no mirror at all?
    LOG_INFO("Creating window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y);
    l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL);
    g_app.SetAppWindowSize(sz);
#else
    l_Window = glfwCreateWindow(800, 600, "GLFW Oculus Rift Test", NULL, NULL);
    std::string windowTitle = PROJECT_NAME;
#endif //USE_OSVR|OVRSDK06

    if (!l_Window)
    {
        LOG_INFO("Glfw failed to create a window. Exiting.");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(l_Window);
    glfwSetWindowSizeCallback(l_Window, resize_Aux);
    glfwSetMouseButtonCallback(l_Window, mouseDown_Aux);
    glfwSetCursorPosCallback(l_Window, mouseMove_Aux);
    glfwSetScrollCallback(l_Window, mouseWheel_Aux);
    glfwSetKeyCallback(l_Window, keyboard_Aux);

    memset(m_keyStates, 0, GLFW_KEY_LAST*sizeof(int));

    // joysticks
    for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i)
    {
        if (GL_FALSE == glfwJoystickPresent(i))
            continue;

        const char* pJoyName = glfwGetJoystickName(i);
        if (pJoyName == NULL)
            continue;

        int numAxes = 0;
        int numButtons = 0;
        glfwGetJoystickAxes(i, &numAxes);
        glfwGetJoystickButtons(i, &numButtons);

        LOG_INFO("Glfw opened Joystick #%d: %s w/ %d axes, %d buttons", i, pJoyName, numAxes, numButtons);
        if (g_joystickIdx == -1)
            g_joystickIdx = i;
    }

    printGLContextInfo(l_Window);
    glfwMakeContextCurrent(l_Window);
    g_pHMDWindow = l_Window;


    // Don't forget to initialize Glew, turn glewExperimental on to
    // avoid problems fetching function pointers...
    glewExperimental = GL_TRUE;
    const GLenum l_Result = glewInit();
    if (l_Result != GLEW_OK)
    {
        LOG_INFO("glewInit() error.");
        exit(EXIT_FAILURE);
    }

#ifdef _DEBUG
    // Debug callback initialization
    // Must be done *after* glew initialization.
    glDebugMessageCallback(myCallback, NULL);
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
    glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0,
        GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Start debugging");
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
#endif

#ifdef USE_ANTTWEAKBAR
    LOG_INFO("Using AntTweakbar.");
    TwInit(useOpenGLCoreContext ? TW_OPENGL_CORE : TW_OPENGL, NULL);
    InitializeBar();
#endif

    LOG_INFO("Calling initGL...");
    g_app.initGL();
    LOG_INFO("Calling initVR...");
    g_app.initVR(swapBackBufferDims);
    LOG_INFO("initVR(%d) complete.", swapBackBufferDims);

    SetVsync(0); // SDK 0.6 requires vsync OFF

    while (!glfwWindowShouldClose(l_Window))
    {
        g_app.CheckForTapToDismissHealthAndSafetyWarning();
        glfwPollEvents();
        joystick();
        timestep();
        g_fps.OnFrame();
        if (g_dynamicallyScaleFBO)
        {
            DynamicallyScaleFBO();
        }

#ifdef USE_ANTTWEAKBAR
        TwRefreshBar(g_pTweakbar);
#endif

        g_app.pre_render_pass();

        displayToHMD();

#ifndef _LINUX
        // Indicate FPS in window title
        // This is absolute death for performance in Ubuntu Linux 12.04
        {
            std::ostringstream oss;
            oss << windowTitle
                << " "
                << static_cast<int>(g_fps.GetFPS())
                << " fps";
            glfwSetWindowTitle(l_Window, oss.str().c_str());
        }
#endif
        const float dumpInterval = 1.f;
        if (g_logDumpTimer.seconds() > dumpInterval)
        {
            LOG_INFO("Frame rate: %d fps", static_cast<int>(g_fps.GetFPS()));
            g_logDumpTimer.reset();
        }
    }

    g_app.exitVR();
    glfwDestroyWindow(l_Window);
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
示例#18
0
int main()
{
    setup_resources();

    config::register_var("screen_width", "1000");
    config::register_var("screen_height", "562");
    config::register_var("master_volume", "10");
    config::register_var("music_volume", "5");

    platform platform;
    if (!platform.init(config::get_var_int("screen_width"), config::get_var_int("screen_height"), "Open Horizon 7th demo"))
        return -1;

    std::vector<joystick_config> joysticks;

    for (int i = 0; glfwJoystickPresent(i); ++i)
    {
        const char *name = glfwGetJoystickName(i);

        joystick_config j;
        j.init(name);
        joysticks.push_back(j);

        int axis_count = 0, buttons_count = 0;
        glfwGetJoystickAxes(i, &axis_count);
        glfwGetJoystickButtons(i, &buttons_count);
        printf("joy%d: %s %d axis %d buttons\n", i, name, axis_count, buttons_count);
    }

    renderer::scene scene;
    sound::world sound_world;
    game::world world(scene, sound_world, scene.hud);
    game::mission game_mode_ms(world);
    game::free_flight game_mode_ff(world);
    game::deathmatch game_mode_dm(world);
    game::team_deathmatch game_mode_tdm(world);
    game::hangar hangar(scene);
    game::game_mode *active_game_mode = 0;
    game::plane_controls controls;
    game::network_client client;
    game::network_server server;

    gui::menu menu(sound_world);
    gui::menu_controls menu_controls;

    platform::key_callback kcb = std::bind(&gui::menu::on_input, &menu, std::placeholders::_1);
    platform.set_keyboard_callback(kcb);

    int mx = platform.get_mouse_x(), my = platform.get_mouse_y();
    int screen_width = platform.get_width(), screen_height = platform.get_height();
    scene.resize(screen_width, screen_height);
    scene.loading(true);
    nya_render::clear(true, true);
    scene.draw();
    platform.end_frame();

    sound_world.set_volume(config::get_var_int("master_volume") / 10.0f);
    sound_world.set_music_volume(config::get_var_int("music_volume") / 10.0f);

    menu.init();
    sound_world.set_music("BGM_menu");

    bool viewer_mode = false;
    bool is_client = false, is_server = false;

    gui::menu::on_action on_menu_action = [&](const std::string &event)
    {
        if (event == "start")
        {
            sound_world.stop_music();
            const char *music_names[] = {"BGM_ms10_08", "BGM_ms06", "BGM_ms08x", "BGM_ms11a", "BGM_ms11b", "BGM_ms12_02"};
            sound_world.set_music(music_names[rand() % (sizeof(music_names) / sizeof(music_names[0]))]);

            auto location = menu.get_var("map");
            auto plane = menu.get_var("ac");
            const int color = atoi(menu.get_var("color").c_str());

            is_client = false, is_server = false;

            scene.loading(true);
            nya_render::clear(true, true);
            scene.draw();
            platform.end_frame();
            scene.loading(false);

            auto mode = menu.get_var("mode");
            auto mp_var = menu.get_var("multiplayer");
            if (mp_var == "server")
            {
                world.set_network(&server);
                auto port = menu.get_var_int("port");
                server.open(port, config::get_var("name").c_str(), mode.c_str(), menu.get_var("map").c_str(), menu.get_var_int("max_players"));
                if (menu.get_var("mp_public") == "true")
                    game::servers_list::register_server(port);
                is_server = true;
            }
            else if (mp_var == "client")
            {
                world.set_network(&client);
                client.start();
                is_client = true;
            }

            if (mode == "ms")
            {
                active_game_mode = &game_mode_ms;
                game_mode_ms.start(plane.c_str(), color,  menu.get_var("mission").c_str());
            }
            else if (mode == "dm")
            {
                const int bots_count = (is_client || is_server) ? 0 : 11;

                active_game_mode = &game_mode_dm;
                game_mode_dm.start(plane.c_str(), color, 0, location.c_str(), bots_count);
            }
            else if (mode == "tdm")
            {
                const int bots_count = (is_client || is_server) ? 0 : 7;

                active_game_mode = &game_mode_tdm;
                game_mode_tdm.start(plane.c_str(), color, 0, location.c_str(), bots_count);
            }
            else if (mode == "ff")
            {
                active_game_mode = &game_mode_ff;
                game_mode_ff.start(plane.c_str(), color, location.c_str());
            }
        }
        else if (event == "connect")
        {
            menu.set_error("");
            client.disconnect();
            auto port = menu.get_var_int("port");
            if (client.connect(menu.get_var("address").c_str(), port))
            {
                menu.send_event("map=" + client.get_server_info().location);
                menu.send_event("mode=" + client.get_server_info().game_mode);
                menu.send_event("screen=ac_select");
            }
            else
                menu.set_error(client.get_error());
        }
        else if (event == "viewer_start")
        {
            viewer_mode = true;
            scene.camera.add_delta_rot(0.2f, 2.5f);
        }
        else if (event == "viewer_update_bg")
        {
            hangar.set_bkg(menu.get_var("bkg").c_str());
        }
        else if (event == "viewer_update_ac")
        {
            const auto dr = scene.camera.get_delta_rot();
            hangar.set_plane(menu.get_var("ac").c_str());
            scene.camera.add_delta_rot(dr.x, dr.y - 3.14f);
        }
        else if (event == "viewer_update_color")
        {
            const auto dr = scene.camera.get_delta_rot();
            const int color = atoi(menu.get_var("color").c_str());
            hangar.set_plane_color(color);
            scene.camera.add_delta_rot(dr.x, dr.y - 3.14f);
        }
        else if (event == "viewer_end")
        {
            viewer_mode = false;
            hangar.end();
        }
        else if (event == "update_volume")
        {
            sound_world.set_volume(config::get_var_int("master_volume") / 10.0f);
            sound_world.set_music_volume(config::get_var_int("music_volume") / 10.0f);
        }
        else if (event == "update_joy_config")
        {
            if (!joysticks.empty())
                joysticks.front().update_config();
        }
        else if (event == "exit")
        {
            server.close();
            client.disconnect();
            platform.terminate();
        }
        else
            printf("unknown event: %s\n", event.c_str());
    };

    menu.set_callback(on_menu_action);

    bool reset_camera = false;

    unsigned long app_time = nya_system::get_time();
    while (!platform.should_terminate())
    {
        unsigned long time = nya_system::get_time();
        int dt = int(time - app_time);

        if (dt > 1000 && !is_client && !is_server)
            dt = 1000;

        app_time = time;

        static bool speed10x = false, last_pause = false, paused = false;

        if (platform.get_width() != screen_width || platform.get_height() != screen_height)
        {
            screen_width = platform.get_width(), screen_height = platform.get_height();
            scene.resize(screen_width, screen_height);

            config::set_var("screen_width", std::to_string(screen_width));
            config::set_var("screen_height", std::to_string(screen_height));
        }

        if (!active_game_mode)
            menu.update(dt, menu_controls);

        if (active_game_mode)
        {
            if (!paused)
            {
                active_game_mode->update(speed10x ? dt * 10 : dt, controls);

                //camera - tracking enemy
                auto p = world.get_player();
                if (p && p->change_target_hold_time >= game::plane::change_target_hold_max_time && !p->targets.empty() && !p->targets.front().target.expired())
                {
                    static auto last_target = p->targets.front().target;
                    if (last_target.expired() || last_target.lock() != p->targets.front().target.lock())
                    {
                        last_target = p->targets.front().target;
                        p->change_target_hold_time = game::plane::change_target_hold_max_time;
                    }

                    auto t = p->targets.front().target.lock();
                    auto tdir = t->get_pos() - p->get_pos(); // + (t->get_vel() - p->get_vel()) * (dt * 0.001f)
                    nya_math::quat q(nya_math::vec3::forward(), tdir);
                    q = nya_math::quat::invert(p->get_rot()) * q;

                    auto da = q.get_euler();
                    scene.camera.reset_delta_rot();

                    const float k = nya_math::min((p->change_target_hold_time - game::plane::change_target_hold_max_time) / 500.0f, 1.0);

                    scene.camera.add_delta_rot(da.x * k, -da.y * k);
                    reset_camera = true;
                }
            }

            scene.draw();

            //util debug draw
            nya_render::clear(false, true);
            nya_render::set_state(nya_render::state());
            nya_render::set_modelview_matrix(nya_scene::get_camera().get_view_matrix());
            get_debug_draw().set_line_width(2.0f);
            get_debug_draw().set_point_size(3.0f);
            get_debug_draw().draw();
        }
        else
        {
            nya_render::clear(true, true);

            if (viewer_mode)
            {
                hangar.update(dt);
                scene.draw();
            }

            menu.draw(scene.ui_render);
        }

        const char *ui_ref = 0;
        //ui_ref = "ui_ref4.tga";
        if (ui_ref)
        {
            static nya_scene::texture ui_ref_texture(ui_ref);
            static std::vector<gui::rect_pair> ui_ref_rects(1);
            ui_ref_rects[0].r.w = scene.ui_render.get_width();
            ui_ref_rects[0].r.y = scene.ui_render.get_height();
            ui_ref_rects[0].r.h = -scene.ui_render.get_height();
            ui_ref_rects[0].tc.w = ui_ref_texture.get_width();
            ui_ref_rects[0].tc.h = ui_ref_texture.get_height();
            static int alpha_anim = 0;
            alpha_anim += dt;
            alpha_anim = alpha_anim % 4000;
            //alpha_anim = 1000;
            scene.ui_render.draw(ui_ref_rects, ui_ref_texture, nya_math::vec4(1.0, 1.0, 1.0, fabsf(alpha_anim / 2000.0f - 1.0)));
        }

        platform.end_frame();

        //controls

        controls = game::plane_controls();
        menu_controls = gui::menu_controls();

        if (platform.get_mouse_lbtn())
            scene.camera.add_delta_rot((platform.get_mouse_y() - my) * 0.03, (platform.get_mouse_x() - mx) * 0.03);

        if (platform.get_mouse_rbtn())
            scene.camera.add_delta_pos(0, 0, my - platform.get_mouse_y());

        mx = platform.get_mouse_x(), my = platform.get_mouse_y();

        bool pause = false;
        for (int i = 0; i < (int)joysticks.size(); ++i)
        {
            int axes_count = 0, buttons_count = 0;
            const float *axes = glfwGetJoystickAxes(i, &axes_count);
            const unsigned char *buttons = glfwGetJoystickButtons(i, &buttons_count);
            joysticks[i].update(axes, axes_count, buttons, buttons_count);
            joysticks[i].apply_controls(controls, pause);

            if (!active_game_mode)
            {
                if (i == 0 && !menu.joy_update(axes, axes_count, buttons, buttons_count))
                    joysticks[i].apply_controls(menu_controls);
            }
        }

        if (platform.get_key(GLFW_KEY_W)) controls.throttle = 1.0f;
        if (platform.get_key(GLFW_KEY_S)) controls.brake = 1.0f;
        if (platform.get_key(GLFW_KEY_A)) controls.rot.y = -1.0f;
        if (platform.get_key(GLFW_KEY_D)) controls.rot.y = 1.0f;
        if (platform.get_key(GLFW_KEY_UP)) controls.rot.x = 1.0f, menu_controls.up = true;
        if (platform.get_key(GLFW_KEY_DOWN)) controls.rot.x = -1.0f, menu_controls.down = true;
        if (platform.get_key(GLFW_KEY_LEFT)) controls.rot.z = -1.0f, menu_controls.left = true;
        if (platform.get_key(GLFW_KEY_RIGHT)) controls.rot.z = 1.0f, menu_controls.right = true;

        if (platform.get_key(GLFW_KEY_LEFT_CONTROL)) controls.mgun = true;
        if (platform.get_key(GLFW_KEY_LEFT_SHIFT)) controls.mgun = true;
        if (platform.get_key(GLFW_KEY_SPACE)) controls.missile = true, menu_controls.next = true;
        if (platform.get_key(GLFW_KEY_F)) controls.flares = true;
        if (platform.get_key(GLFW_KEY_Q)) controls.change_weapon = true;
        if (platform.get_key(GLFW_KEY_E)) controls.change_target = true;
        if (platform.get_key(GLFW_KEY_R)) controls.change_radar = true;
        if (platform.get_key(GLFW_KEY_V)) controls.change_camera = true;

        if (platform.was_pressed(GLFW_KEY_ESCAPE)) menu_controls.prev = true;
        if (platform.was_pressed(GLFW_KEY_ENTER)) menu_controls.next = true;

        if (active_game_mode)
        {
            if (((pause && pause != last_pause) || platform.was_pressed(GLFW_KEY_P)) && !is_server && !is_client)
                scene.pause(paused = !paused);
            last_pause = pause;

            bool should_stop = platform.was_pressed(GLFW_KEY_ESCAPE);
            if (is_client && !client.is_up())
                should_stop = true;
            if (is_server && !server.is_up())
                should_stop = true;

            if (should_stop)
            {
                if (paused)
                    scene.pause(paused = !paused);
                active_game_mode->end();
                active_game_mode = 0;
                server.close();
                client.disconnect();
                world.set_network(0);
                sound_world.stop_sounds();
                menu_controls.prev = false;
                if (is_client)
                    menu.send_event("screen=mp_connect");

                sound_world.set_music("BGM_menu");
            }
        }

        speed10x = platform.get_key(GLFW_KEY_RIGHT_SHIFT) && !is_client && !is_server;

        if (controls.change_camera || (reset_camera && !controls.change_target))
        {
            scene.camera.reset_delta_rot();
            reset_camera = false;
        }

        if (!joysticks.empty() && !platform.get_mouse_lbtn() && !controls.change_target)
        {
            scene.camera.reset_delta_rot();
            scene.camera.add_delta_rot(-controls.cam_rot.x * nya_math::constants::pi_2, -controls.cam_rot.y * nya_math::constants::pi);
        }

        if (platform.was_pressed(GLFW_KEY_COMMA))
            debug_variable::set(debug_variable::get() - 1);
        if (platform.was_pressed(GLFW_KEY_PERIOD))
            debug_variable::set(debug_variable::get() + 1);

        if (!active_game_mode) //force limit 60 fps in menu
        {
            int sleep_time = 1000/60 - int(nya_system::get_time() - time);
            if (sleep_time > 0)
                std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time));
        }
    }

    server.close();
    client.disconnect();
    sound::release_context();
    platform.terminate();

    return 0;
}
示例#19
0
static void refresh_joysticks(void)
{
    int i;

    for (i = 0;  i < sizeof(joysticks) / sizeof(Joystick);  i++)
    {
        Joystick* j = joysticks + i;

        if (glfwJoystickPresent(GLFW_JOYSTICK_1 + i))
        {
            const float* axes;
            const unsigned char* buttons;
            int axis_count, button_count;

            free(j->name);
            j->name = strdup(glfwGetJoystickName(GLFW_JOYSTICK_1 + i));

            axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1 + i, &axis_count);
            if (axis_count != j->axis_count)
            {
                j->axis_count = axis_count;
                j->axes = realloc(j->axes, j->axis_count * sizeof(float));
            }

            memcpy(j->axes, axes, axis_count * sizeof(float));

            buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1 + i, &button_count);
            if (button_count != j->button_count)
            {
                j->button_count = button_count;
                j->buttons = realloc(j->buttons, j->button_count);
            }

            memcpy(j->buttons, buttons, button_count * sizeof(unsigned char));

            if (!j->present)
            {
                printf("Found joystick %i named \'%s\' with %i axes, %i buttons\n",
                       i + 1, j->name, j->axis_count, j->button_count);

                joystick_count++;
            }

            j->present = GL_TRUE;
        }
        else
        {
            if (j->present)
            {
                printf("Lost joystick %i named \'%s\'\n", i + 1, j->name);

                free(j->name);
                free(j->axes);
                free(j->buttons);
                memset(j, 0, sizeof(Joystick));

                joystick_count--;
            }
        }
    }
}
示例#20
0
文件: demo.cpp 项目: DreadedX/flare
// TODO: Controllers cause some issues on wine, they are detected, but are null
int main() {

	flare::init();

	print_m("Welcome to Flare Engine");

	// NOTE: This is code to test joystick input
	int present = glfwJoystickPresent(GLFW_JOYSTICK_2);
	print_d("Present: %i", present);

	if (present == 1) {
		const char *name = glfwGetJoystickName(GLFW_JOYSTICK_2);

		print_d("Controller name: %s", name);

	}
	// END

	fuse::Entity *player = flare::getState()->mainState->manager->createEntity("Player");
	player->addComponent<Camera>();
	// Make sure that the controller is plugged in before adding the control
	if (present == 1) {

		player->addComponent<JoyCamera>();
		player->addComponent<JoyDebugControl>();
	}

	// It should really be easier to create new entities
	fuse::Entity *sponza = flare::getState()->mainState->manager->createEntity("Sponza");

	sponza->setAttribute("position", glm::vec3(0.0f, 0.0f, 0.0f));
	sponza->setAttribute("scale", glm::vec3(0.1f, 0.1f, 0.1f));
	sponza->addComponent<flare::component::Object>("demo/model/sponza");

	// Example of post proccessing
	// PostFX *scanline = new PostFX("demo/scanline");
	// scanline->init();
	// flare::getState()->render.renderPasses.add(scanline);

	flare::PauseState *pauseState = new flare::PauseState;
	pauseState->previousState = flare::getState()->mainState;
	pauseState->manager = new fuse::Manager;

	Gausian *gausian = new Gausian;
	gausian->init();
	pauseState->renderPasses.add(gausian);

	while (flare::isRunning()) {

		// Shadow test
		flare::getState()->render.light.direction.x = 100 * cos(glfwGetTime()/5);
		flare::getState()->render.light.direction.z = 100 * sin(glfwGetTime()/5);
		//////

		flare::update();

			flare::Timer timer = flare::Timer("demo code", glfwGetTime());
		static bool blur = false;
		static bool paused = false;
		if (flare::input::keyCheck(GLFW_KEY_P) && player != nullptr) {

			if (!paused) {

				flare::getState()->mainState = pauseState;
				blur = true;
			} else {

				blur = false;
			}

			print_d("Toggling pause");
			paused = !paused;
			flare::input::keySet(GLFW_KEY_P, false);
		}

		if (flare::input::keyCheck(GLFW_KEY_X) && player != nullptr) {

			print_d("Toggling pause effect");
			blur = !blur;
			flare::input::keySet(GLFW_KEY_X, false);
		}

		if (blur) {

			gausian->test = fmin(gausian->test + 7*flare::render::getDeltaTime(), 1.0f);
		}
		if (!blur) {

			gausian->test = fmax(gausian->test - 7*flare::render::getDeltaTime(), 0.0f);
			// This is really not efficient at all
			if (gausian->test == 0.0f) {

				flare::getState()->mainState = pauseState->previousState;
			}
		}
			timer.time = glfwGetTime() - timer.time;
			flare::getState()->timers.push_back(timer);
	}

	// Make sure the state is cleaned up
	for(flare::render::passes::Pass *pass : pauseState->renderPasses) {

		delete pass;
	}
	delete pauseState->manager;
	delete pauseState;

	flare::terminate();
}
示例#21
0
int main(int argc, char** argv)
{
#if defined(_WIN32)
    LOG_INFO("Windows build.");
#elif defined(_LINUX)
    LOG_INFO("Linux build.");
    LOG_INFO("DISPLAY=%s", getenv("DISPLAY"));
#elif defined(_MACOS)
    LOG_INFO("MacOS build.");
#endif

    bool useOpenGLCoreContext = false;
#ifdef USE_CORE_CONTEXT
    useOpenGLCoreContext = true;
#endif

    g_renderMode.outputType = RenderingMode::OVR_SDK;

    LOG_INFO("Using GLFW3 backend.");
    LOG_INFO("Compiled against GLFW %i.%i.%i",
        GLFW_VERSION_MAJOR,
        GLFW_VERSION_MINOR,
        GLFW_VERSION_REVISION);
    int major, minor, revision;
    glfwGetVersion(&major, &minor, &revision);
    LOG_INFO("Running against GLFW %i.%i.%i", major, minor, revision);
    LOG_INFO("glfwGetVersionString: %s", glfwGetVersionString());

    // Command line options
    for (int i=0; i<argc; ++i)
    {
        const std::string a = argv[i];
        LOG_INFO("argv[%d]: %s", i, a.c_str());
        if (!a.compare("-sdk"))
        {
            g_renderMode.outputType = RenderingMode::OVR_SDK;
        }
        else if (!a.compare("-client"))
        {
            g_renderMode.outputType = RenderingMode::OVR_Client;
        }
        else if (!a.compare("-core"))
        {
            useOpenGLCoreContext = true;
        }
        else if (!a.compare("-compat"))
        {
            useOpenGLCoreContext = false;
        }
    }

#ifdef USE_OCULUSSDK
    g_app.initHMD();
#else
    g_renderMode.outputType = RenderingMode::Mono_Buffered;
#endif

    GLFWwindow* l_Window = NULL;
    glfwSetErrorCallback(ErrorCallback);
    if (!glfwInit())
    {
        exit(EXIT_FAILURE);
    }

    // Log system monitor information
    const GLFWmonitor* pPrimary = glfwGetPrimaryMonitor();
    int monitorCount = 0;
    GLFWmonitor** ppMonitors = glfwGetMonitors(&monitorCount);
    for (int i=0; i<monitorCount; ++i)
    {
        GLFWmonitor* pCur = ppMonitors[i];
        const GLFWvidmode* mode = glfwGetVideoMode(pCur);
        if (mode != NULL)
        {
            (void)pPrimary;
            LOG_INFO("Monitor #%d: %dx%d @ %dHz %s",
                i,
                mode->width,
                mode->height,
                mode->refreshRate,
                pCur==pPrimary ? "Primary":"");
        }
    }

    bool swapBackBufferDims = false;

    // Context setup - before window creation
    glfwWindowHint(GLFW_DEPTH_BITS, 16);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, useOpenGLCoreContext ? GLFW_OPENGL_CORE_PROFILE : GLFW_OPENGL_COMPAT_PROFILE);
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#ifdef _DEBUG
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif

#if defined(USE_OSVR)
    LOG_INFO("USE_OSVR=1");
    std::string windowTitle = "";
    windowTitle = PROJECT_NAME "-GLFW-Osvr";

    if (g_app.UsingDebugHmd())
    {
        const hmdRes sz = { 800, 600 };
        // Create a normal, decorated application window
        LOG_INFO("Using Debug HMD mode.");
        windowTitle = PROJECT_NAME "-GLFW-DebugHMD";
        g_renderMode.outputType = RenderingMode::Mono_Buffered;

        l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL);
    }
    else
    {
        const hmdRes sz = {
            g_app.getHmdResolution().h,
            g_app.getHmdResolution().w
        };
        const winPos pos = g_app.getHmdWindowPos();
        g_renderMode.outputType = RenderingMode::SideBySide_Undistorted;

        LOG_INFO("Using Extended desktop mode.");
        windowTitle = PROJECT_NAME "-GLFW-Extended";

        LOG_INFO("Creating GLFW_DECORATED window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y);
        glfwWindowHint(GLFW_DECORATED, 0);
        l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL);
        glfwWindowHint(GLFW_DECORATED, 1);
        glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
        glfwSetWindowPos(l_Window, pos.x, pos.y);
    }

#elif defined(USE_OCULUSSDK)
    LOG_INFO("USE_OCULUSSDK=1");
    ovrSizei sz = g_app.getHmdResolution();
    const ovrVector2i pos = g_app.getHmdWindowPos();
    std::string windowTitle = "";

    if (g_app.UsingDebugHmd() == true)
    {
        // Create a normal, decorated application window
        LOG_INFO("Using Debug HMD mode.");
        windowTitle = PROJECT_NAME "-GLFW-DebugHMD";
        g_renderMode.outputType = RenderingMode::Mono_Buffered;

        l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL);
    }
    else if (g_app.UsingDirectMode())
    {
        // HMD active - position undecorated window to fill HMD viewport
        LOG_INFO("Using Direct to Rift mode.");
        windowTitle = PROJECT_NAME "-GLFW-Direct";

        GLFWmonitor* monitor = glfwGetPrimaryMonitor();
        const GLFWvidmode* mode = glfwGetVideoMode(monitor);
        sz.w = mode->width;
        sz.h = mode->height;
        LOG_INFO("Creating window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y);
        l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), monitor, NULL);
        glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

#ifdef _LINUX
        swapBackBufferDims = true;
#endif

#if defined(_WIN32)
        g_app.AttachToWindow((void*)glfwGetWin32Window(l_Window));
#endif
    }
    else
    {
        LOG_INFO("Using Extended desktop mode.");
        windowTitle = PROJECT_NAME "-GLFW-Extended";

        LOG_INFO("Creating GLFW_DECORATED window %dx%d@%d,%d", sz.w, sz.h, pos.x, pos.y);
        glfwWindowHint(GLFW_DECORATED, 0);
        l_Window = glfwCreateWindow(sz.w, sz.h, windowTitle.c_str(), NULL, NULL);
        glfwWindowHint(GLFW_DECORATED, 1);
        glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
        glfwSetWindowPos(l_Window, pos.x, pos.y);
    }

    resize(l_Window, sz.w, sz.h); // inform AppSkeleton of window size
#else
    const glm::vec2 sz(800, 600);
    // Create a normal, decorated application window
    LOG_INFO("Using No VR SDK.");
    const std::string windowTitle = PROJECT_NAME "-GLFW-NoVRSDK";
    g_renderMode.outputType = RenderingMode::Mono_Buffered;

    l_Window = glfwCreateWindow(sz.x, sz.y, windowTitle.c_str(), NULL, NULL);
#endif //USE_OSVR|USE_OCULUSSDK

    if (!l_Window)
    {
        LOG_INFO("Glfw failed to create a window. Exiting.");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    // Required for SDK rendering (to do the buffer swap on its own)
#ifdef OVRSDK05
  #if defined(_WIN32)
    g_app.setWindow(glfwGetWin32Window(l_Window));
  #elif defined(__linux__)
    g_app.setWindow(NULL);//glfwGetX11Display());
  #endif
#endif //USE_OCULUSSDK

    glfwMakeContextCurrent(l_Window);
    glfwSetWindowSizeCallback(l_Window, resize);
    glfwSetMouseButtonCallback(l_Window, mouseDown);
    glfwSetCursorPosCallback(l_Window, mouseMove);
    glfwSetScrollCallback(l_Window, mouseWheel);
    glfwSetKeyCallback(l_Window, keyboard);

    memset(m_keyStates, 0, GLFW_KEY_LAST*sizeof(int));

    // joysticks
    for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i)
    {
        if (GL_FALSE == glfwJoystickPresent(i))
            continue;

        const char* pJoyName = glfwGetJoystickName(i);
        if (pJoyName == NULL)
            continue;

        int numAxes = 0;
        int numButtons = 0;
        glfwGetJoystickAxes(i, &numAxes);
        glfwGetJoystickButtons(i, &numButtons);

        LOG_INFO("Glfw opened Joystick #%d: %s w/ %d axes, %d buttons", i, pJoyName, numAxes, numButtons);
        if (g_joystickIdx == -1)
            g_joystickIdx = i;
    }

    printGLContextInfo(l_Window);
    glfwMakeContextCurrent(l_Window);
    g_pHMDWindow = l_Window;


    // Don't forget to initialize Glew, turn glewExperimental on to
    // avoid problems fetching function pointers...
    glewExperimental = GL_TRUE;
    const GLenum l_Result = glewInit();
    if (l_Result != GLEW_OK)
    {
        LOG_INFO("glewInit() error.");
        exit(EXIT_FAILURE);
    }

#ifdef _DEBUG
    // Debug callback initialization
    // Must be done *after* glew initialization.
    glDebugMessageCallback(myCallback, NULL);
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
    glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0,
        GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Start debugging");
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
#endif

#ifdef USE_ANTTWEAKBAR
    LOG_INFO("Using AntTweakbar.");
    TwInit(useOpenGLCoreContext ? TW_OPENGL_CORE : TW_OPENGL, NULL);
    InitializeBar();
#endif

    LOG_INFO("Calling initGL...");
    g_app.initGL();
    LOG_INFO("Calling initVR...");
    g_app.initVR(swapBackBufferDims);
    LOG_INFO("initVR(%d) complete.", swapBackBufferDims);

    while (!glfwWindowShouldClose(l_Window))
    {
        g_app.CheckForTapToDismissHealthAndSafetyWarning();
        glfwPollEvents();
        joystick();
        timestep();
        g_fps.OnFrame();
        if (g_dynamicallyScaleFBO)
        {
            DynamicallyScaleFBO();
        }

#ifdef USE_ANTTWEAKBAR
        TwRefreshBar(g_pTweakbar);
#endif

        displayToHMD();

#ifndef _LINUX
        // Indicate FPS in window title
        // This is absolute death for performance in Ubuntu Linux 12.04
        {
            std::ostringstream oss;
            oss << windowTitle
                << " "
                << static_cast<int>(g_fps.GetFPS())
                << " fps";
            glfwSetWindowTitle(l_Window, oss.str().c_str());
            if (g_AuxWindow != NULL)
                glfwSetWindowTitle(g_AuxWindow, oss.str().c_str());
        }
#endif
        const float dumpInterval = 1.f;
        if (g_logDumpTimer.seconds() > dumpInterval)
        {
            LOG_INFO("Frame rate: %d fps", static_cast<int>(g_fps.GetFPS()));
            g_logDumpTimer.reset();
        }

        // Optionally display to auxiliary mono view
        if (g_AuxWindow != NULL)
        {
            glfwMakeContextCurrent(g_AuxWindow);
            glClearColor(0.f, 0.f, 0.f, 0.f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            ///@note VAOs *cannot* be shared between contexts.
            ///@note GLFW windows are inextricably tied to their own unique context.
            /// For these two reasons, calling draw a third time for the auxiliary window
            /// is not possible. Furthermore, it is not strictly desirable for the extra
            /// rendering cost.
            /// Instead, we share the render target texture from the stereo render and present
            /// just the left eye to the aux window.
            if (g_drawToAuxWindow)
            {
                presentSharedFboTexture();
            }

#ifdef USE_ANTTWEAKBAR
            TwDraw(); ///@todo Should this go first? Will it write to a depth buffer?
#endif

            glfwSwapBuffers(g_AuxWindow);

            if (glfwWindowShouldClose(g_AuxWindow))
            {
                destroyAuxiliaryWindow(g_AuxWindow);
            }

            // Set context to Rift window when done
            glfwMakeContextCurrent(l_Window);
        }
    }

    g_app.exitVR();
    glfwDestroyWindow(l_Window);
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
示例#22
0
	const asd::achar* Joystick_Imp::GetJoystickName()
	{

		m_joystickName = ToAString(glfwGetJoystickName(m_connectId));
		return m_joystickName.c_str();
	}
示例#23
0
文件: test.c 项目: glfw/gleq
int main(int argc, char** argv)
{
    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    gleqInit();

    GLFWwindow* window = glfwCreateWindow(640, 480, "Event Queue Test", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);

    gleqTrackWindow(window);

    while (!glfwWindowShouldClose(window))
    {
        GLEQevent event;

        glfwSwapBuffers(window);
        glfwWaitEvents();

        while (gleqNextEvent(&event))
        {
            switch (event.type)
            {
                case GLEQ_WINDOW_MOVED:
                    printf("Window moved to %i,%i\n", event.pos.x, event.pos.y);
                    break;

                case GLEQ_WINDOW_RESIZED:
                    printf("Window resized to %ix%i\n",
                           event.size.width,
                           event.size.height);
                    break;

                case GLEQ_WINDOW_CLOSED:
                    printf("Window close request\n");
                    break;

                case GLEQ_WINDOW_REFRESH:
                    printf("Window refresh request\n");
                    break;

                case GLEQ_WINDOW_FOCUSED:
                    printf("Window focused\n");
                    break;

                case GLEQ_WINDOW_DEFOCUSED:
                    printf("Window defocused\n");
                    break;

                case GLEQ_WINDOW_ICONIFIED:
                    printf("Window iconified\n");
                    break;

                case GLEQ_WINDOW_UNICONIFIED:
                    printf("Window uniconified\n");
                    break;

#if GLFW_VERSION_MINOR >= 3
                case GLEQ_WINDOW_MAXIMIZED:
                    printf("Window maximized\n");
                    break;

                case GLEQ_WINDOW_UNMAXIMIZED:
                    printf("Window unmaximized\n");
                    break;

                case GLEQ_WINDOW_SCALE_CHANGED:
                    printf("Window content scale %0.2fx%0.2f\n",
                           event.scale.x, event.scale.y);
                    break;
#endif // GLFW_VERSION_MINOR

                case GLEQ_FRAMEBUFFER_RESIZED:
                    printf("Framebuffer resized to %ix%i\n",
                           event.size.width,
                           event.size.height);
                    break;

                case GLEQ_BUTTON_PRESSED:
                    printf("Mouse button %i pressed (mods 0x%x)\n",
                           event.mouse.button,
                           event.mouse.mods);
                    break;

                case GLEQ_BUTTON_RELEASED:
                    printf("Mouse button %i released (mods 0x%x)\n",
                           event.mouse.button,
                           event.mouse.mods);
                    break;

                case GLEQ_CURSOR_MOVED:
                    printf("Cursor moved to %i,%i\n", event.pos.x, event.pos.y);
                    break;

                case GLEQ_CURSOR_ENTERED:
                    printf("Cursor entered window\n");
                    break;

                case GLEQ_CURSOR_LEFT:
                    printf("Cursor left window\n");
                    break;

                case GLEQ_SCROLLED:
                    printf("Scrolled %0.2f,%0.2f\n",
                           event.scroll.x, event.scroll.y);
                    break;

                case GLEQ_KEY_PRESSED:
                    printf("Key 0x%02x pressed (scancode 0x%x mods 0x%x)\n",
                           event.keyboard.key,
                           event.keyboard.scancode,
                           event.keyboard.mods);
                    break;

                case GLEQ_KEY_REPEATED:
                    printf("Key 0x%02x repeated (scancode 0x%x mods 0x%x)\n",
                           event.keyboard.key,
                           event.keyboard.scancode,
                           event.keyboard.mods);
                    break;

                case GLEQ_KEY_RELEASED:
                    printf("Key 0x%02x released (scancode 0x%x mods 0x%x)\n",
                           event.keyboard.key,
                           event.keyboard.scancode,
                           event.keyboard.mods);
                    break;

                case GLEQ_CODEPOINT_INPUT:
                    printf("Codepoint U+%05X input\n", event.codepoint);
                    break;

#if GLFW_VERSION_MINOR >= 1
                case GLEQ_FILE_DROPPED:
                {
                    int i;

                    printf("%i files dropped\n", event.file.count);
                    for (i = 0;  i < event.file.count;  i++)
                        printf("\t%s\n", event.file.paths[i]);

                    break;
                }
#endif // GLFW_VERSION_MINOR

                case GLEQ_MONITOR_CONNECTED:
                    printf("Monitor \"%s\" connected\n",
                           glfwGetMonitorName(event.monitor));
                    break;

                case GLEQ_MONITOR_DISCONNECTED:
                    printf("Monitor \"%s\" disconnected\n",
                           glfwGetMonitorName(event.monitor));
                    break;

#if GLFW_VERSION_MINOR >= 2
                case GLEQ_JOYSTICK_CONNECTED:
                    printf("Joystick %i \"%s\" connected\n",
                           event.joystick,
                           glfwGetJoystickName(event.joystick));
                    break;

                case GLEQ_JOYSTICK_DISCONNECTED:
                    printf("Joystick %i disconnected\n", event.joystick);
                    break;
#endif // GLFW_VERSION_MINOR

                default:
                    fprintf(stderr, "Error: Unknown event %i\n", event.type);
                    break;
            }

            gleqFreeEvent(&event);
        }

        // Workaround for msvcrt stdout not being properly flushed by
        // newlines when running inside mintty
        fflush(stdout);
    }

    glfwDestroyWindow(window);
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
示例#24
0
static const char* joystick_label(int jid)
{
    static char label[1024];
    snprintf(label, sizeof(label), "%i: %s", jid + 1, glfwGetJoystickName(jid));
    return label;
}