static int eventThread(void *data) { struct pt_data *gdata = (struct pt_data *) data; struct v4l2_control control; SDL_Surface *pscreen = *gdata->ptscreen; struct vdIn *videoIn = gdata->ptvideoIn; SDL_Event *sdlevent = gdata->ptsdlevent; SDL_Rect *drect = gdata->drect; SDL_mutex *affmutex = gdata->affmutex; int x, y; int mouseon = 0; int value = 0; int len = 0; short incpantilt = INCPANTILT; int boucle = 0; action_gui curr_action = A_VIDEO; while (videoIn->signalquit) { SDL_LockMutex(affmutex); float frmrate = gdata->frmrate; while (SDL_PollEvent(sdlevent)) { //scan the event queue switch (sdlevent->type) { case SDL_KEYUP: case SDL_MOUSEBUTTONUP: mouseon = 0; incpantilt = INCPANTILT; boucle = 0; break; case SDL_MOUSEBUTTONDOWN: mouseon = 1; case SDL_MOUSEMOTION: SDL_GetMouseState(&x, &y); curr_action = GUI_whichbutton(x, y, pscreen, videoIn); break; /* case SDL_VIDEORESIZE: pscreen = SDL_SetVideoMode(sdlevent->resize.w, sdlevent->resize.h, 0, SDL_VIDEO_Flags); drect->w = sdlevent->resize.w; drect->h = sdlevent->resize.h; break;*/ case SDL_KEYDOWN: curr_action = GUI_keytoaction(sdlevent->key.keysym.sym); if (curr_action != A_VIDEO) mouseon = 1; break; case SDL_QUIT: printf("\nQuit signal received.\n"); videoIn->signalquit = 0; break; } } //end if poll SDL_UnlockMutex(affmutex); /* traiter les actions */ value = 0; if (mouseon) { boucle++; switch (curr_action) { case A_BRIGHTNESS_UP: if ((value = v4l2UpControl(videoIn, V4L2_CID_BRIGHTNESS)) < 0) printf("Set Brightness up error\n"); break; case A_CONTRAST_UP: if ((value = v4l2UpControl(videoIn, V4L2_CID_CONTRAST)) < 0) printf("Set Contrast up error\n"); break; case A_SATURATION_UP: if ((value = v4l2UpControl(videoIn, V4L2_CID_SATURATION)) < 0) printf("Set Saturation up error\n"); break; case A_GAIN_UP: if ((value = v4l2UpControl(videoIn, V4L2_CID_GAIN)) < 0) printf("Set Gain up error\n"); break; case A_SHARPNESS_UP: if ((value = v4l2UpControl(videoIn, V4L2_CID_SHARPNESS)) < 0) printf("Set Sharpness up error\n"); break; case A_GAMMA_UP: if ((value = v4l2UpControl(videoIn, V4L2_CID_GAMMA)) < 0) printf("Set Gamma up error\n"); break; /* Motor control events */ case A_PAN_UP: if ((value = v4L2UpDownPan(videoIn, -incpantilt)) < 0) printf("Set Pan up error\n"); break; case A_PAN_DOWN: if ((value = v4L2UpDownPan(videoIn, incpantilt)) < 0) printf("Set Pan down error\n"); break; case A_TILT_UP: if ((value = v4L2UpDownTilt(videoIn, -incpantilt)) < 0) printf("Set Tilt up error\n"); break; case A_TILT_DOWN: if ((value = v4L2UpDownTilt(videoIn, incpantilt)) < 0) printf("Set Tilt down error\n"); break; case A_PAN_RESET: if (v4l2ResetPan(videoIn) < 0) printf("Reset pan error\n"); break; case A_TILT_RESET: if (v4l2ResetTilt(videoIn) < 0) printf("Reset tilt error\n"); break; case A_SCREENSHOT: SDL_Delay(200); videoIn->getPict = 1; value = 1; break; case A_RESET: if (v4l2ResetControl(videoIn, V4L2_CID_BRIGHTNESS) < 0) printf("reset Brightness error\n"); if (v4l2ResetControl(videoIn, V4L2_CID_SATURATION) < 0) printf("reset Saturation error\n"); if (v4l2ResetControl(videoIn, V4L2_CID_CONTRAST) < 0) printf("reset Contrast error\n"); if (v4l2ResetControl(videoIn, V4L2_CID_HUE) < 0) printf("reset Hue error\n"); if (v4l2ResetControl(videoIn, V4L2_CID_SHARPNESS) < 0) printf("reset Sharpness error\n"); if (v4l2ResetControl(videoIn, V4L2_CID_GAMMA) < 0) printf("reset Gamma error\n"); if (v4l2ResetControl(videoIn, V4L2_CID_GAIN) < 0) printf("reset Gain error\n"); if (v4l2ResetPanTilt(videoIn) < 0) printf("reset pantilt error\n"); break; case A_BRIGHTNESS_DOWN: if ((value = v4l2DownControl(videoIn, V4L2_CID_BRIGHTNESS)) < 0) printf("Set Brightness down error\n"); break; case A_CONTRAST_DOWN: if ((value = v4l2DownControl(videoIn, V4L2_CID_CONTRAST)) < 0) printf("Set Contrast down error\n"); break; case A_SATURATION_DOWN: if ((value = v4l2DownControl(videoIn, V4L2_CID_SATURATION)) < 0) printf("Set Saturation down error\n"); break; case A_GAIN_DOWN: if ((value = v4l2DownControl(videoIn, V4L2_CID_GAIN)) < 0) printf("Set Gain down error\n"); break; case A_SHARPNESS_DOWN: if ((value = v4l2DownControl(videoIn, V4L2_CID_SHARPNESS)) < 0) printf("Set Sharpness down error\n"); break; case A_GAMMA_DOWN: if ((value = v4l2DownControl(videoIn, V4L2_CID_GAMMA)) < 0) printf("Set Gamma down error\n"); break; case A_RECORD_TOGGLE: SDL_Delay(200); videoIn->toggleAvi = !videoIn->toggleAvi; value = videoIn->toggleAvi; if ( value == 1 ) { printf("avi recording started\n"); videoIn->recordstart=SDL_GetTicks(); } else { int dur=SDL_GetTicks()-videoIn->recordstart; printf("\navi recording stopped (%ds)\n",dur/1000); videoIn->recordtime+=dur; } break; case A_SWITCH_LIGHTFREQFILT: if ((value =v4l2GetControl(videoIn,V4L2_CID_POWER_LINE_FREQUENCY)) < 0) printf("Get value of light frequency filter error\n"); if(value < 2) // round switch 50->60->NoFliker->. value++; // \_______________; else value=0; if(value == 0) printf("Current light frequency filter: 50Hz\n"); else if(value == 1) printf("Current light frequency filter: 60Hz\n"); else if(value == 2) printf("Current light frequency filter: NoFliker\n"); if ((value =v4l2SetLightFrequencyFilter(videoIn,value)) < 0) printf("Switch light frequency filter error\n"); break; case A_QUIT: videoIn->signalquit = 0; break; case A_VIDEO: break; case A_CAPTURE_FRAME: value = 1; videoIn->rawFrameCapture = 1; break; case A_CAPTURE_FRAMESTREAM: value = 1; if (!videoIn->rawFrameCapture) { videoIn->rawFrameCapture = 2; videoIn->rfsBytesWritten = 0; videoIn->rfsFramesWritten = 0; printf("Starting raw frame stream capturing ...\n"); } else if(videoIn->framesWritten >= 5) { videoIn->rawFrameCapture = 0; printf("Stopped raw frame stream capturing. %u bytes written for %u frames.\n", videoIn->rfsBytesWritten, videoIn->rfsFramesWritten); } break; case A_CAPTURE_STREAM: value = 1; if (videoIn->captureFile == NULL) { videoIn->captureFile = fopen("stream.raw", "wb"); if(videoIn->captureFile == NULL) { perror("Unable to open file for raw stream capturing"); } else { printf("Starting raw stream capturing to stream.raw ...\n"); } videoIn->bytesWritten = 0; videoIn->framesWritten = 0; } else if(videoIn->framesWritten >= 5) { fclose(videoIn->captureFile); printf("Stopped raw stream capturing to stream.raw. %u bytes written for %u frames.\n", videoIn->bytesWritten, videoIn->framesWritten); videoIn->captureFile = NULL; } break; case A_EXPOSURE_UP: if ((value = v4l2UpControl(videoIn, V4L2_CID_EXPOSURE_ABSOLUTE)) < 0) printf("Set Absolute Exposure up error\n"); break; case A_EXPOSURE_DOWN: if ((value = v4l2DownControl(videoIn, V4L2_CID_EXPOSURE_ABSOLUTE)) < 0) printf("Set Absolute Exposure down error\n"); break; case A_EXPOSURE_ON: control.id =V4L2_CID_EXPOSURE_AUTO; control.value =1; if ((value = ioctl(videoIn->fd, VIDIOC_S_CTRL, &control)) < 0) printf("Set Auto Exposure on error\n"); else printf("Auto Exposure set to %d\n", control.value); break; case A_EXPOSURE_OFF: control.id =V4L2_CID_EXPOSURE_AUTO; control.value =8; if ((value = ioctl(videoIn->fd, VIDIOC_S_CTRL, &control)) < 0) printf("Set Auto Exposure off error\n"); else printf("Auto Exposure set to %d\n", control.value); break; case A_BALANCE_UP: if ((value = v4l2UpControl(videoIn, V4L2_CID_WHITE_BALANCE_TEMPERATURE)) < 0) printf("Set Balance Temperature up error\n"); break; case A_BALANCE_DOWN: if ((value = v4l2DownControl(videoIn, V4L2_CID_WHITE_BALANCE_TEMPERATURE)) < 0) printf("Set Balance Temperature down error\n"); break; case A_BALANCE_ON: control.id =V4L2_CID_AUTO_WHITE_BALANCE; control.value =1; if ((value = ioctl(videoIn->fd, VIDIOC_S_CTRL, &control)) < 0) printf("Set Auto Balance on error\n"); else printf("Auto Balance set to %d\n", control.value); break; case A_BALANCE_OFF: control.id =V4L2_CID_AUTO_WHITE_BALANCE; control.value =0; if ((value = ioctl(videoIn->fd, VIDIOC_S_CTRL, &control)) < 0) printf("Set Auto Balance off error\n"); else printf("Auto Balance set to %d\n", control.value); break; case A_SAVE: printf("Save controls\n"); save_controls(videoIn->fd); break; case A_LOAD: printf("load controls\n"); load_controls(videoIn->fd); break; default: break; } if(!(boucle%10)) // smooth pan tilt method if(incpantilt < (10*INCPANTILT)) incpantilt += (INCPANTILT/4); if(value) { len = strlen(title_act[curr_action].title)+8; snprintf(videoIn->status, len,"%s %06d",title_act[curr_action].title,value); } } else { // mouseon len = 100 * sizeof(char); // as allocated in init_videoIn snprintf(videoIn->status, len, "%s, %.1f fps", title_act[curr_action].title, frmrate); } SDL_Delay(50); //printf("fp/s %d\n",frmrate); } //end main loop /* Close the stream capture file */ if (videoIn->captureFile) { fclose(videoIn->captureFile); printf("Stopped raw stream capturing to stream.raw. %u bytes written for %u frames.\n", videoIn->bytesWritten, videoIn->framesWritten); } /* Display stats for raw frame stream capturing */ if (videoIn->rawFrameCapture == 2) { printf("Stopped raw frame stream capturing. %u bytes written for %u frames.\n", videoIn->rfsBytesWritten, videoIn->rfsFramesWritten); } }
void CLevelEditor::Input( CGameInput * pGameInput, float dps ) { if( !m_bEditorOn || !m_pCurLevel ) return; int mx, my; auto mouseState = SDL_GetMouseState( &mx, &my ); Vector2< float > cameraTranslate; if( m_pCamera ) { cameraTranslate = m_pCamera->GetTranslate(); } int tX = ( mx - cameraTranslate.GetX() ) / TEXTURE_RENDER_WIDTH; int tY = ( my - cameraTranslate.GetY() ) / TEXTURE_RENDER_HEIGHT; if( mx - cameraTranslate.GetX() < 0 ) tX--; if( my - cameraTranslate.GetY() < 0 ) tY--; int x = tX * TEXTURE_RENDER_WIDTH; int y = tY * TEXTURE_RENDER_HEIGHT; if( mouseState & SDL_BUTTON( SDL_BUTTON_LEFT ) ) { if( m_CurTileIndex > -1 ) { m_SelectedTileIndex = m_CurTileIndex; } else if( m_SelectedTileIndex > -1 ) { m_pCurLevel->RemoveTileAt( mx - cameraTranslate.GetX(), my - cameraTranslate.GetY() ); PlaceTile( m_SelectedTileIndex, x, y ); } } if( m_pCamera ) { if( pGameInput->KeyDown( SDL_SCANCODE_UP ) ) { m_pCamera->Translate( 0.0f, -CAMERA_TRANSLATE_SPEED * dps ); } if( pGameInput->KeyDown( SDL_SCANCODE_DOWN ) ) { m_pCamera->Translate( 0.0f, CAMERA_TRANSLATE_SPEED * dps ); } if( pGameInput->KeyDown( SDL_SCANCODE_LEFT ) ) { m_pCamera->Translate( -CAMERA_TRANSLATE_SPEED * dps, 0.0f ); } if( pGameInput->KeyDown( SDL_SCANCODE_RIGHT ) ) { m_pCamera->Translate( CAMERA_TRANSLATE_SPEED * dps, 0.0f ); } } if( pGameInput->KeyDown( SDL_SCANCODE_1 ) ) { if( m_SelectedTileIndex > -1 ) { m_pCurLevel->RemoveTileAt( mx - cameraTranslate.GetX(), my - cameraTranslate.GetY() ); PlaceTile( m_SelectedTileIndex, x, y ); } } if( pGameInput->KeyDown( SDL_SCANCODE_3 ) ) { m_pCurLevel->RemoveTileAt( mx - cameraTranslate.GetX(), my - cameraTranslate.GetY() ); } if( pGameInput->ShiftMod() && pGameInput->KeyDownOnce( SDLK_0 ) ) { if( m_pCurLevel ) { m_LastSaveTime = SDL_GetTicks(); m_pCurLevel->Save( m_pCurLevel->GetPath() ); } } }
void menuCommand2() { int mx, my; FILE *file; if( SDL_GetMouseState(&mx, &my) &SDL_BUTTON_LMASK ) { if( (mx > MENU_X + 130) && (mx < (MENU_X + 510)) ) { // Main Menu if( HUD.menu == 1 ) { // New game if( (my > (MENU_Y + 40)) && (my < (MENU_Y + 105)) ) { //endGame(); if(!Mix_PlayingMusic()) startMusic(); else if(!players[0].inGame) { Mix_HookMusicFinished(nextSong); Mix_FadeOutMusic(100); } startGame(MAX_PLAYERS); } // Resume else if( (my > (MENU_Y + 122)) && (my < (MENU_Y + 190)) ) { if(players[0].inGame) HUD.menu = 0; } // Save/Load else if( (my > (MENU_Y + 205)) && (my < (MENU_Y + 275)) ) { HUD.menu = 2; } // Options else if( (my > (MENU_Y + 285)) && (my < (MENU_Y + 355)) ) { HUD.menu = 3; } // Quit else if( (my > (MENU_Y + 365)) && (my < (MENU_Y + 435)) ) { exit(0); } } // Save/Load submenu else if( HUD.menu == 2 ) { // Save if( (my > (MENU_Y + 40)) && (my < (MENU_Y + 105)) ) { fprintf(stderr,"Saving not yet implemented.\n"); } // Load else if( (my > (MENU_Y + 122)) && (my < (MENU_Y + 190)) ) { fprintf(stderr,"Loading not yet implemented.\n"); } // Main Menu else if( (my > (MENU_Y + 365)) && (my < (MENU_Y + 435)) ) { HUD.menu = 1; } } // Options submenu else if( HUD.menu == 3 ) { // Sound if( (my > (MENU_Y + 40)) && (my < (MENU_Y + 105)) ) { HUD.menu = 4; } // Controls else if( (my > (MENU_Y + 122)) && (my < (MENU_Y + 190)) ) { HUD.menu = 5; } // HUD else if( (my > (MENU_Y + 205)) && (my < (MENU_Y + 275)) ) { HUD.menu = 6; } // Game else if( (my > (MENU_Y + 285)) && (my < (MENU_Y + 355)) ) { HUD.menu = 7; } // Main Menu else if( (my > (MENU_Y + 365)) && (my < (MENU_Y + 435)) ) { HUD.menu = 1; } } // Sound submenu else if( HUD.menu == 4 ) { // Volume sliders if( (mx > MENU_X + 350) && (mx < (MENU_X + 490)) ) { // Sound effects volume if( (my > (MENU_Y + 40)) && (my < (MENU_Y + 105)) ) { audio.slide = 1; } // Music volume else if( (my > (MENU_Y + 122)) && (my < (MENU_Y + 190)) ) { audio.slide = 2; } } // Mute else if( (my > (MENU_Y + 205)) && (my < (MENU_Y + 275)) ) { audio.mute = 1-audio.mute; } // Options else if( (my > (MENU_Y + 365)) && (my < (MENU_Y + 435)) ) { HUD.menu = 3; // ADD save settings } } // ADD Controls submenu else if( HUD.menu == 5 ) { // if( (my > (MENU_Y + 40)) && (my < (MENU_Y + 105)) ) { } // else if( (my > (MENU_Y + 122)) && (my < (MENU_Y + 190)) ) { } // else if( (my > (MENU_Y + 205)) && (my < (MENU_Y + 275)) ) { } // else if( (my > (MENU_Y + 285)) && (my < (MENU_Y + 355)) ) { } // Options else if( (my > (MENU_Y + 365)) && (my < (MENU_Y + 435)) ) { HUD.menu = 3; } } // HUD submenu else if( HUD.menu == 6 ) { // Alpha slider if( (mx > MENU_X + 350) && (mx < (MENU_X + 490)) ) { if( (my > (MENU_Y + 40)) && (my < (MENU_Y + 105)) ) { aSlide = true; } } // Save /* else if( (my > (MENU_Y + 122)) && (my < (MENU_Y + 190)) ) { saveHUD(); } // Load else if( (my > (MENU_Y + 205)) && (my < (MENU_Y + 275)) ) { file = fopen("config/hud.txt","r"); if(file != NULL) loadHUD(file); else fprintf(stderr,"hud.txt failed to load\n"); } */ // Options else if( (my > (MENU_Y + 365)) && (my < (MENU_Y + 435)) ) { HUD.menu = 3; } } // Game submenu else if( HUD.menu == 7 ) { // Scroll sensitivity slider if( (mx > MENU_X + 350) && (mx < (MENU_X + 490)) ) { if( (my > (MENU_Y + 40)) && (my < (MENU_Y + 105)) ) { HUD.sSlide = true; } } // Tool tips on/off else if( (my > (MENU_Y + 122)) && (my < (MENU_Y + 190)) ) { HUD.ttips = 1 - HUD.ttips; } // Game res else if( (my > (MENU_Y + 205)) && (my < (MENU_Y + 275)) ) { if( (mx > (MENU_X + 350)) && (mx < (MENU_X + 490)) ) { nextRes(); } } // Options else if( (my > (MENU_Y + 365)) && (my < (MENU_Y + 435)) ) { HUD.menu = 3; } } } } }
virtual void handleEvent(SDL_Event& e) { //If an event was detected for this window if (e.window.windowID != mWindowID) return; if (e.type == SDL_WINDOWEVENT) { //Caption update flag bool updateCaption = false; switch (e.window.event) { //Window appeared case SDL_WINDOWEVENT_SHOWN: mShown = true; break; //Window disappeared case SDL_WINDOWEVENT_HIDDEN: mShown = false; break; //Get new dimensions and repaint case SDL_WINDOWEVENT_SIZE_CHANGED: mWidth = e.window.data1; mHeight = e.window.data2; SDL_RenderPresent(mRenderer); break; //Repaint on expose case SDL_WINDOWEVENT_EXPOSED: SDL_RenderPresent(mRenderer); break; //Mouse enter case SDL_WINDOWEVENT_ENTER: mMouseFocus = true; updateCaption = true; break; //Mouse exit case SDL_WINDOWEVENT_LEAVE: mMouseFocus = false; updateCaption = true; break; //Keyboard focus gained case SDL_WINDOWEVENT_FOCUS_GAINED: mKeyboardFocus = true; updateCaption = true; break; //Keyboard focus lost case SDL_WINDOWEVENT_FOCUS_LOST: mKeyboardFocus = false; updateCaption = true; break; //Window minimized case SDL_WINDOWEVENT_MINIMIZED: mMinimized = true; break; //Window maxized case SDL_WINDOWEVENT_MAXIMIZED: mMinimized = false; break; //Window restored case SDL_WINDOWEVENT_RESTORED: mMinimized = false; break; //Hide and quit on close case SDL_WINDOWEVENT_CLOSE: SDL_HideWindow(mWindow); mClosed = true; break; } //Demo Update window caption with new data if (updateCaption) { std::stringstream caption; caption << mTitle << " - ID: " << mWindowID << " MouseFocus:" << ((mMouseFocus) ? "On" : "Off") << " KeyboardFocus:" << ((mKeyboardFocus) ? "On" : "Off"); SDL_SetWindowTitle(mWindow, caption.str().c_str()); } } //Case of Panels int x, y; //Get mouse position SDL_GetMouseState(&x, &y); for (std::list<Panel*>::iterator iter = pList_->begin(); iter != pList_->end(); iter++) { Panel *p = (*iter); p->handleEvent(e, x - p->getX(), y - p->getY()); } }
// This is how we're actually going to handle input events, SDL getch // is simply a wrapper around this. input_event input_manager::get_input_event(WINDOW *win) { // standards note: getch is sometimes required to call refresh // see, e.g., http://linux.die.net/man/3/getch // so although it's non-obvious, that refresh() call (and maybe InvalidateRect?) IS supposed to be there if(win == NULL) win = mainwin; wrefresh(win); lastchar=ERR;//ERR=-1 input_event rval; if (inputdelay < 0) { do { rval.type = CATA_INPUT_ERROR; CheckMessages(); if (lastchar!=ERR) break; SDL_Delay(1); } while (lastchar==ERR); } else if (inputdelay > 0) { unsigned long starttime=SDL_GetTicks(); unsigned long endtime; bool timedout = false; do { rval.type = CATA_INPUT_ERROR; CheckMessages(); endtime=SDL_GetTicks(); if (lastchar!=ERR) break; SDL_Delay(1); timedout = endtime >= starttime + inputdelay; if (timedout) { rval.type = CATA_INPUT_TIMEOUT; } } while (!timedout); } else { CheckMessages(); } if (rval.type != CATA_INPUT_TIMEOUT) { if (lastchar == ERR) { rval.type = CATA_INPUT_ERROR; } else if (lastchar_isbutton) { rval.type = CATA_INPUT_GAMEPAD; rval.add_input(lastchar); } else if (lastchar_is_mouse) { rval.type = CATA_INPUT_MOUSE; rval.add_input(lastchar); SDL_GetMouseState(&rval.mouse_x, &rval.mouse_y); } else { rval.type = CATA_INPUT_KEYBOARD; rval.add_input(lastchar); } } return rval; }
Player::Player() { bomb = nullptr; SDL_GetMouseState(&mouseLastX, &mouseLastY); mouseLeftPressed = false; mouseRightPressed = false; boolKeyboardAngle = false; boolMove = false; allowedToFly = false; boolOnTheGround = false; ySpeed = 0; cameraAngleX = glm::radians(135.f); cameraAngleY = glm::radians(25.f); playerAngleX = cameraAngleX; playerAngleY = cameraAngleY; orientMe(); camlx = playerlx; camlz = playerlz; camly = playerly; x = 0.5f; y = Game::Instance().getMap().getH(0, 0); z = 0.5f; deltaAngle = 0.0; deltaMove=0.0; shootAng = ANG_SHOOT_START; shootForce = SHOOT_FORCE_START; perna1Ang = 245.f; perna2Ang = 40.f; std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; float corDino[3] = {25/255.f, 80/255.f, 25/255.f}; loadOBJ("Geometry/Objects/dinobody.obj", vertices, uvs, normals); std::vector<GLfloat> vColor; for(int i=0; i < (int)vertices.size(); i++){ vColor.push_back(corDino[0]); vColor.push_back(corDino[1]); vColor.push_back(corDino[2]); } std::vector<GLfloat> vPos; for(int i=0; i < (int)vertices.size(); i++){ vPos.push_back(vertices[i].x); vPos.push_back(vertices[i].y); vPos.push_back(vertices[i].z); } std::vector<GLfloat> vNormals; for(int i=0; i < (int)normals.size(); i++){ vNormals.push_back(normals[i].x); vNormals.push_back(normals[i].y); vNormals.push_back(normals[i].z); } playerAvatar = new GlObject(Game::Instance().getNormalShader(), vertices.size(), &vPos[0], &vColor[0], normals.size(), &vNormals[0]); std::vector<glm::vec3> verticesLeg; std::vector<glm::vec2> uvsLeg; std::vector<glm::vec3> normalsLeg; loadOBJ("Geometry/Objects/dinoleg.obj", verticesLeg, uvsLeg, normalsLeg); std::vector<GLfloat> vColorLeg1; for(int i=0; i < (int)verticesLeg.size(); i++){ vColorLeg1.push_back(corDino[0]); vColorLeg1.push_back(corDino[1]); vColorLeg1.push_back(corDino[2]); } std::vector<GLfloat> vPosLeg1; for(int i=0; i < (int)verticesLeg.size(); i++){ vPosLeg1.push_back(verticesLeg[i].x); vPosLeg1.push_back(verticesLeg[i].y); vPosLeg1.push_back(verticesLeg[i].z); } std::vector<GLfloat> vNormalsLeg1; for(int i=0; i < (int)normalsLeg.size(); i++){ vNormalsLeg1.push_back(normalsLeg[i].x); vNormalsLeg1.push_back(normalsLeg[i].y); vNormalsLeg1.push_back(normalsLeg[i].z); } playerLeg1 = new GlObject(Game::Instance().getNormalShader(), verticesLeg.size(), &vPosLeg1[0], &vColorLeg1[0], normalsLeg.size(), &vNormalsLeg1[0]); std::vector<GLfloat> vPosLeg2(vPosLeg1); std::vector<GLfloat> vColorLeg2(vColorLeg1); std::vector<GLfloat> vNormalsLeg2(vNormalsLeg1); playerLeg2 = new GlObject(Game::Instance().getNormalShader(), verticesLeg.size(), &vPosLeg2[0], &vColorLeg2[0], normalsLeg.size(), &vNormalsLeg2[0]); updateAvatarAndCamera(); EventAggregator::Instance().getEvent<Tick>().subscribe( [&](Tick &e){ tick(); }); }
/** * @brief Handle input events like keys presses and joystick movement as well * as window events * @sa CL_Frame * @sa IN_Parse * @sa IN_JoystickMove */ void IN_Frame (void) { int mouse_buttonstate; unsigned short unicode; unsigned int key; SDL_Event event; IN_Parse(); IN_JoystickMove(); if (vid_grabmouse->modified) { vid_grabmouse->modified = qfalse; if (!vid_grabmouse->integer) { /* ungrab the pointer */ Com_Printf("Switch grab input off\n"); SDL_WM_GrabInput(SDL_GRAB_OFF); /* don't allow grabbing the input in fullscreen mode */ } else if (!vid_fullscreen->integer) { /* grab the pointer */ Com_Printf("Switch grab input on\n"); SDL_WM_GrabInput(SDL_GRAB_ON); } else { Com_Printf("No input grabbing in fullscreen mode\n"); Cvar_SetValue("vid_grabmouse", 0); } } oldMousePosX = mousePosX; oldMousePosY = mousePosY; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: mouse_buttonstate = K_MOUSE1; break; case SDL_BUTTON_MIDDLE: mouse_buttonstate = K_MOUSE3; break; case SDL_BUTTON_RIGHT: mouse_buttonstate = K_MOUSE2; break; case SDL_BUTTON_WHEELUP: mouse_buttonstate = K_MWHEELUP; break; case SDL_BUTTON_WHEELDOWN: mouse_buttonstate = K_MWHEELDOWN; break; case 6: mouse_buttonstate = K_MOUSE4; break; case 7: mouse_buttonstate = K_MOUSE5; break; default: mouse_buttonstate = K_AUX1 + (event.button.button - 8) % 16; break; } IN_EventEnqueue(mouse_buttonstate, 0, (event.type == SDL_MOUSEBUTTONDOWN)); break; case SDL_MOUSEMOTION: SDL_GetMouseState(&mousePosX, &mousePosY); mousePosX /= viddef.rx; mousePosY /= viddef.ry; break; case SDL_KEYDOWN: IN_PrintKey(&event, 1); #ifndef _WIN32 if ((event.key.keysym.mod & KMOD_ALT) && event.key.keysym.sym == SDLK_RETURN) { SDL_Surface *surface = SDL_GetVideoSurface(); if (!SDL_WM_ToggleFullScreen(surface)) { int flags = surface->flags ^= SDL_FULLSCREEN; SDL_SetVideoMode(surface->w, surface->h, 0, flags); } if (surface->flags & SDL_FULLSCREEN) { Cvar_SetValue("vid_fullscreen", 1); /* make sure, that input grab is deactivated in fullscreen mode */ Cvar_SetValue("vid_grabmouse", 0); } else { Cvar_SetValue("vid_fullscreen", 0); } vid_fullscreen->modified = qfalse; /* we just changed it with SDL. */ break; /* ignore this key */ } #endif if ((event.key.keysym.mod & KMOD_CTRL) && event.key.keysym.sym == SDLK_g) { SDL_GrabMode gm = SDL_WM_GrabInput(SDL_GRAB_QUERY); Cvar_SetValue("vid_grabmouse", (gm == SDL_GRAB_ON) ? 0 : 1); break; /* ignore this key */ } /* console key is hardcoded, so the user can never unbind it */ if ((event.key.keysym.mod & KMOD_SHIFT) && event.key.keysym.sym == SDLK_ESCAPE) { Con_ToggleConsole_f(); break; } IN_TranslateKey(&event.key.keysym, &key, &unicode); IN_EventEnqueue(key, unicode, qtrue); break; case SDL_VIDEOEXPOSE: break; case SDL_KEYUP: IN_PrintKey(&event, 0); IN_TranslateKey(&event.key.keysym, &key, &unicode); IN_EventEnqueue(key, unicode, qfalse); break; case SDL_ACTIVEEVENT: /* make sure menu no more capture input when the game window lose the focus */ if (event.active.state == SDL_APPINPUTFOCUS && event.active.gain == 0) UI_ReleaseInput(); break; case SDL_QUIT: Cmd_ExecuteString("quit"); break; case SDL_VIDEORESIZE: /* make sure that SDL_SetVideoMode is called again after we changed the size * otherwise the mouse will make problems */ vid_mode->modified = qtrue; break; } } }
int draw( void ) { if(wireframe) { glClearColor(1, 1, 1, 1); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth(2); } else { glClearColor(0.2f, 0.2f, 0.2f, 1); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } // effacer l'image glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(key_state('r')) { clear_key_state('r'); reload_program(); } // recupere les mouvements de la souris int mx, my; unsigned int mb= SDL_GetRelativeMouseState(&mx, &my); int mousex, mousey; SDL_GetMouseState(&mousex, &mousey); // deplace la camera if(mb & SDL_BUTTON(1)) orbiter_rotation(camera, mx, my); // tourne autour de l'objet else if(mb & SDL_BUTTON(2)) orbiter_translation(camera, (float) mx / (float) window_width(), (float) my / (float) window_height()); // deplace le point de rotation else if(mb & SDL_BUTTON(3)) orbiter_move(camera, mx); // approche / eloigne l'objet // recupere les transformations Transform model= make_identity(); Transform view= orbiter_view_transform(camera); Transform projection= orbiter_projection_transform(camera, window_width(), window_height(), 45); Transform viewport= make_viewport(window_width(), window_height()); Transform mvp= projection * view * model; Transform mvpInv= make_inverse(mvp); Transform mv= model * view; // affiche l'objet if(program_failed == false) { if(key_state('w')) { clear_key_state('w'); wireframe= !wireframe; } // configuration minimale du pipeline glBindVertexArray(vao); glUseProgram(program); // affecte une valeur aux uniforms // transformations standards program_uniform(program, "modelMatrix", model); program_uniform(program, "modelInvMatrix", make_inverse(model)); program_uniform(program, "viewMatrix", view); program_uniform(program, "viewInvMatrix", make_inverse(view)); program_uniform(program, "projectionMatrix", projection); program_uniform(program, "projectionInvMatrix", make_inverse(projection)); program_uniform(program, "viewportMatrix", viewport); program_uniform(program, "viewportInvMatrix", make_inverse(viewport)); program_uniform(program, "mvpMatrix", mvp); program_uniform(program, "mvpInvMatrix", mvpInv); program_uniform(program, "mvMatrix", mv); program_uniform(program, "normalMatrix", make_normal_transform(mv)); // interactions program_uniform(program, "viewport", make_vec2(window_width(), window_height())); program_uniform(program, "time", (float) SDL_GetTicks()); program_uniform(program, "motion", make_vec3(mx, my, mb & SDL_BUTTON(1))); program_uniform(program, "mouse", make_vec3(mousex, mousey, mb & SDL_BUTTON(1))); // textures for(unsigned int i= 0; i < (unsigned int) textures.size(); i++) { char uniform[1024]; sprintf(uniform, "texture%d", i); program_use_texture(program, uniform, i, textures[i]); } // go glDrawArrays(GL_TRIANGLES, 0, vertex_count); } // affiche les infos begin(widgets); if(program_failed) { label(widgets, "[error] program '%s'", program_filename.path); begin_line(widgets); text_area(widgets, 20, program_log.c_str(), program_area); } else { label(widgets, "program '%s' running...", program_filename.path); if(mesh_filename[0] != 0) { begin_line(widgets); label(widgets, "mesh '%s', %u positions, %u texcoords, %u normals", mesh_filename.path, (unsigned int) mesh.positions.size(), (unsigned int) mesh.texcoords.size(), (unsigned int) mesh.normals.size()); } for(unsigned int i= 0; i < (unsigned int) texture_filenames.size(); i++) { begin_line(widgets); label(widgets, "texture%u '%s'", i, texture_filenames[i].path); } } end(widgets); draw(widgets, window_width(), window_height()); if(key_state('s')) { clear_key_state('s'); screenshot("shader_kit.png"); } if(key_state('c')) { clear_key_state('c'); write_orbiter(camera, "orbiter.txt"); } if(key_state('v')) { clear_key_state('v'); camera= read_orbiter("orbiter.txt"); } return 1; }
int main(int argc, char* argv[]) { // Create our window MainScreen = new Screen; MainScreen->Clear(); // For backwards-compatibility, we want project files that are drag-and-dropped // onto the executable to be automatically loaded when it starts. // First, we have to make sure the file's actually there. FILE* prjfile = (argc > 1) ? fopen(argv[1], "r") : NULL; #ifdef _WIN32 // Windows build allows a blank window to open, where the user can open a // project file using the menu bar if (prjfile != NULL) { fclose(prjfile); CurProject = new Project(argv[1]); // Process initial display CurProject->Redraw(); } #else if (prjfile == NULL) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "You must supply the project file as a parameter", NULL); exit(1); } fclose(prjfile); CurProject = new Project(argv[1]); // Process initial display CurProject->Redraw(); #endif bool CtrlPress = false; //SDL_EnableKeyRepeat(400,SDL_DEFAULT_REPEAT_INTERVAL); //Main Loop including event Handling bool quit = false; while (!quit) { SDL_Event event; while ((!quit) && SDL_WaitEvent(&event)) { if (event.type == SDL_QUIT) quit = true; if (event.type == SDL_MOUSEBUTTONDOWN) { if (CurProject != NULL) { CurProject->SelectionRect->Unselect(); //Checks if within selector bounds and selects tile CurProject->LevelMap->CheckClickTile(event.button.x, event.button.y); if (event.button.button == SDL_BUTTON_LEFT) //Checks if valid map position and sets tile CurProject->LevelMap->CheckSetTile(event.button.x, event.button.y); else if (event.button.button == SDL_BUTTON_RIGHT) { //Checks if valid map position and selects tile CurProject->LevelMap->CheckSelectTile(event.button.x, event.button.y); CurProject->SelectionRect->SelInit(event.button.x, event.button.y); } } } if (event.type == SDL_MOUSEBUTTONUP) { if (event.button.button == SDL_BUTTON_RIGHT) { if (CurProject != NULL) { //Checks if valid map position and selects tile CurProject->LevelMap->CheckSelectTile(event.button.x, event.button.y); CurProject->SelectionRect->SelFinalize(event.button.x, event.button.y); } } } if (event.type == SDL_MOUSEMOTION) { if (CurProject != NULL) { if (SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)) CurProject->LevelMap->CheckSetTile(event.motion.x, event.motion.y); else { CurProject->LevelMap->RefreshTileScreen(event.motion.x - event.motion.xrel, event.motion.y - event.motion.yrel, true); CurProject->LevelMap->DrawSelectedTile(event.motion.x, event.motion.y); } } } if (event.type == SDL_KEYDOWN) { //secondary cases usually for German keyboard layout support switch(event.key.keysym.sym) { case SDLK_RCTRL: case SDLK_LCTRL: CtrlPress = true; break; case '/': case '-': if (CurProject != NULL) { if (!CurProject->SelectionRect->isActive()) CurProject->LevelMap->CurSwapPriority(); else { CurProject->SelectionRect->SwapPriority(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } } break; case ',': if (CurProject != NULL) { if (!CurProject->SelectionRect->isActive()) CurProject->LevelMap->CurFlipX(); else { CurProject->SelectionRect->FlipX(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } } break; case '.': if (CurProject != NULL) { if (!CurProject->SelectionRect->isActive()) CurProject->LevelMap->CurFlipY(); else { CurProject->SelectionRect->FlipY(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } } break; case SDLK_RIGHT: if (CurProject != NULL) { CurProject->LevelMap->CurShiftRight(); CurProject->SelectionRect->Unselect(); } break; case SDLK_LEFT: if (CurProject != NULL) { CurProject->LevelMap->CurShiftLeft(); CurProject->SelectionRect->Unselect(); } break; case SDLK_DOWN: if (CurProject != NULL) { CurProject->LevelMap->CurShiftDown(); CurProject->SelectionRect->Unselect(); } break; case SDLK_UP: if (CurProject != NULL) { CurProject->LevelMap->CurShiftUp(); CurProject->SelectionRect->Unselect(); } break; case SDLK_DELETE: if (CurProject != NULL) { if (!CurProject->SelectionRect->isActive()) CurProject->LevelMap->ClearCurrentTile(); else { CurProject->SelectionRect->clear(); CurProject->SelectionRect->AssignSection(); CurProject->LevelMap->DrawMap(); } } break; case SDLK_ESCAPE: quit = true; break; case SDLK_RETURN: if (CurProject != NULL) { CurProject->LevelMap->SetTileSelected(); CurProject->SelectionRect->Unselect(); } break; case '=': case '´': if (CurProject != NULL) { CurProject->LevelMap->SelectTileCur(); CurProject->SelectionRect->Unselect(); } break; case SDLK_PAGEDOWN: if (CurProject != NULL) { if (!CurProject->SelectionRect->isActive()) CurProject->LevelMap->SelectedTileIncrID(); else { CurProject->SelectionRect->IncrID(); CurProject->SelectionRect->AssignSection(); CurProject->LevelMap->DrawMap(); } } break; case SDLK_PAGEUP: if (CurProject != NULL) { if (!CurProject->SelectionRect->isActive()) CurProject->LevelMap->SelectedTileDecrID(); else { CurProject->SelectionRect->DecrID(); CurProject->SelectionRect->AssignSection(); CurProject->LevelMap->DrawMap(); } } break; case SDLK_F1: if (CurProject != NULL) { CurProject->LevelMap->SetPalCurrent(0); CurProject->GfxStuff->DrawSelector(); } break; case SDLK_F2: if (CurProject != NULL) { CurProject->LevelMap->SetPalCurrent(1); CurProject->GfxStuff->DrawSelector(); } break; case SDLK_F3: if (CurProject != NULL) { CurProject->LevelMap->SetPalCurrent(2); CurProject->GfxStuff->DrawSelector(); } break; case SDLK_F4: if (CurProject != NULL) { CurProject->LevelMap->SetPalCurrent(3); CurProject->GfxStuff->DrawSelector(); } break; case SDLK_F5: if (CurProject != NULL) { CurProject->GfxStuff->ToggleHighPriority(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } break; case SDLK_F6: if (CurProject != NULL) { CurProject->GfxStuff->ToggleLowPriority(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } break; case SDLK_F9: if (CurProject != NULL) { CurProject->Save(); } break; case SDLK_F10: //redraw whole screen if (CurProject != NULL) { CurProject->Redraw(); } break; case SDLK_BACKSPACE: if (CurProject != NULL) { CurProject->LevelMap->CurShiftLeft(); CurProject->LevelMap->ClearCurrentTile(); CurProject->SelectionRect->Unselect(); } break; case '[': case 'ü': if (CurProject != NULL) { CurProject->GfxStuff->DecScreenOffset(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } break; case '\'': case 'ä': if (CurProject != NULL) { CurProject->GfxStuff->IncScreenOffset(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } break; case ';': case 'ö': if (CurProject != NULL) { CurProject->GfxStuff->DecScreenXOffset(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } break; case '\\': case '#': case '+': case ']': if (CurProject != NULL) { CurProject->GfxStuff->IncScreenXOffset(); CurProject->LevelMap->DrawMap(); CurProject->SelectionRect->SelDrawRect(); } break; case SDLK_END: if (CurProject != NULL) { CurProject->GfxStuff->IncSelOffset(); CurProject->GfxStuff->DrawSelector(); } break; case SDLK_HOME: if (CurProject != NULL) { CurProject->GfxStuff->DecSelOffset(); CurProject->GfxStuff->DrawSelector(); } break; case SDLK_SPACE: if (CurProject != NULL) { CurProject->LevelMap->ClearCurrentTile(); CurProject->LevelMap->CurShiftRight(); } break; default: if (event.key.keysym.sym >= 'a' && event.key.keysym.sym <= 'z') { if (CtrlPress) { switch(event.key.keysym.sym) { case 'c': if (CurProject != NULL) { if (CurProject->SelectionRect->isActive()) { delete CurProject->CopyRect; CurProject->CopyRect = new SelRect(CurProject->SelectionRect); } } break; case 'x': if (CurProject != NULL) { if (CurProject->SelectionRect->isActive()) { delete CurProject->CopyRect; CurProject->CopyRect = new SelRect(CurProject->SelectionRect); CurProject->SelectionRect->clear(); CurProject->SelectionRect->AssignSection(); CurProject->LevelMap->DrawMap(); } } break; case 'v': if (CurProject != NULL) { CurProject->CopyRect->PasteSection(); CurProject->LevelMap->DrawMap(); } break; case 'a': if (CurProject != NULL) { CurProject->SelectionRect->SelInit(0, 0); CurProject->SelectionRect->SelFinalize(CurProject->PrjData->map.xSize*8, CurProject->PrjData->map.ySize*8); } break; } } else { if (CurProject != NULL) { CurProject->LevelMap->SetCurrentTile(event.key.keysym.sym - 'a' + CurProject->GfxStuff->GetTileOffset() + CurProject->PrjData->letterOffset); CurProject->LevelMap->CurShiftRight(); CurProject->SelectionRect->Unselect(); } } } else if (event.key.keysym.sym >= '0' && event.key.keysym.sym <= '9') { if (CurProject != NULL) { CurProject->LevelMap->SetCurrentTile(event.key.keysym.sym - '0' + CurProject->GfxStuff->GetTileOffset() + CurProject->PrjData->numberOffset); CurProject->LevelMap->CurShiftRight(); CurProject->SelectionRect->Unselect(); } } } } if (event.type == SDL_KEYUP) { switch(event.key.keysym.sym) { case SDLK_RCTRL: case SDLK_LCTRL: CtrlPress = false; break; } } #ifdef _WIN32 if (event.type == SDL_SYSWMEVENT) { WinAPI::HandleWindowsEvent(&event); } #endif MainScreen->ProcessDisplay(); } } return 0; }
void SDLViewer::execute() { bool redisplay = true; MouseButton button = NoButton; unsigned char key; int x, y; SDL_Event event; int modifiers = 0; static unsigned int stimer; //Ensure window visible for interaction show(); // Enter event loop processing while ( !quitProgram ) { // Check for events // Delay redisplay & resize until event queue empty if (SDL_PollEvent(&event) == 0) { // Resize window if (resized) { if (stimer < SDL_GetTicks()) { // Create in new dimensions resized = false; open(width, height); redisplay = true; } else continue; //Cycle until timer runs out } if (redisplay) { // Redraw Viewer (Call virtual to display) display(); redisplay = false; } // Wait for next event SDL_WaitEvent( &event ); } //Save shift states modifiers = SDL_GetModState(); keyState.shift = (modifiers & KMOD_SHIFT); keyState.ctrl = (modifiers & KMOD_CTRL); keyState.alt = (modifiers & KMOD_ALT); // Process event switch (event.type) { case SDL_QUIT: quitProgram = true; break; case SDL_VIDEORESIZE: //Adjust viewport metrics etc... resize(event.resize.w, event.resize.h); resized = true; //Start timer to wait for sizing events to cease before calling actual context resize stimer = SDL_GetTicks() + 200; break; case SDL_KEYDOWN: //Pass keystrokes on KEYDOWN only, char info not provided by SDL on KEYUP key = event.key.keysym.unicode; if (!key) { int code = (int)event.key.keysym.sym; if (code == SDLK_KP8 || code == SDLK_UP) key = KEY_UP; if (code == SDLK_KP2 || code == SDLK_DOWN) key = KEY_DOWN; if (code == SDLK_KP4 || code == SDLK_LEFT) key = KEY_LEFT; if (code == SDLK_KP6 || code == SDLK_RIGHT) key = KEY_RIGHT; if (code == SDLK_KP9 || code == SDLK_PAGEUP) key = KEY_PAGEUP; if (code == SDLK_KP3 || code == SDLK_PAGEDOWN) key = KEY_PAGEDOWN; if (code == SDLK_KP7 || code == SDLK_HOME) key = KEY_HOME; if (code == SDLK_KP1 || code == SDLK_END) key = KEY_END; //key = (unsigned char)code; if (!key) continue; } SDL_GetMouseState(&x, &y); if (keyPress(key, x, y)) redisplay = true; break; case SDL_MOUSEMOTION: if (mouseState) { mouseMove(event.motion.x, event.motion.y); redisplay = true; } break; case SDL_MOUSEBUTTONDOWN: button = (MouseButton)event.button.button; // XOR state of three mouse buttons to the mouseState variable if (button <= RightButton) mouseState ^= (int)pow(2.0,button); mousePress( button, true, event.button.x, event.button.y); break; case SDL_MOUSEBUTTONUP: mouseState = 0; button = (MouseButton)event.button.button; mousePress( button, false, event.button.x, event.button.y); redisplay = true; break; case SDL_USEREVENT: // Timer event redisplay = true; break; case SDL_ACTIVEEVENT: if (event.active.state == SDL_APPACTIVE && event.active.gain == 1) // Restored from icon redisplay = true; break; case SDL_VIDEOEXPOSE: redisplay = true; // Repaint break; } } }
void CMain::GameLoop(void) { while (!quit && csdl_setup->GetMainEvent()->type != SDL_QUIT) { csdl_setup->Begin(); SDL_GetMouseState(&MouseX, &MouseY); grass->Draw(); bob->Draw(); float angle = atan2(Follow_Point_Y - bob->GetY(), Follow_Point_X - bob->GetX()); angle = (angle * (180 / 3.14)) + 180; if (!stopAnimation) { if (angle > 45 && angle <= 135) { //up if (distance > 15) bob->PlayAnimation(0, 3, 3, 200); else bob->PlayAnimation(1, 1, 3, 200); } else if (angle > 135 && angle <= 225) { //right if (distance > 15) bob->PlayAnimation(0, 3, 2, 200); else bob->PlayAnimation(1, 1, 2, 200); } else if (angle > 225 && angle <= 315) { //down if (distance > 15) bob->PlayAnimation(0, 3, 0, 200); else bob->PlayAnimation(1, 1, 0, 200); } else if ((angle <= 360 && angle > 315) || (angle >= 0 && angle <= 45)) { //left if (distance > 20) bob->PlayAnimation(0, 3, 1, 200); else bob->PlayAnimation(1, 1, 1, 200); } } if (csdl_setup->GetMainEvent()->type == SDL_MOUSEBUTTONDOWN || csdl_setup->GetMainEvent()->type == SDL_MOUSEMOTION) { if (csdl_setup->GetMainEvent()->button.button == SDL_BUTTON_LEFT) { Follow_Point_X = MouseX; Follow_Point_Y = MouseY; Follow = true; } } if (timeCheck + 10 < SDL_GetTicks() && Follow) { distance = GetDistance(bob->GetX(), bob->GetY(), Follow_Point_X, Follow_Point_Y); if (distance == 0) stopAnimation = true; else stopAnimation = false; if (distance > 15) { if (bob->GetX() != Follow_Point_X) { bob->SetX(bob->GetX() - ((bob->GetX() - Follow_Point_X) / distance) * 1.5f); } if (bob->GetY() != Follow_Point_Y) { bob->SetY(bob->GetY() - ((bob->GetY() - Follow_Point_Y) / distance) * 1.5f); } } else Follow = false; timeCheck = SDL_GetTicks(); } csdl_setup->End(); } }
void update(float dt) { PROFILER_CPU_TIMESLICE("ui->update"); memcpy(keyStatePrev, keyStateCurr, SDL_NUM_SCANCODES); memcpy(keyStateCurr, SDL_GetKeyboardState(NULL), SDL_NUM_SCANCODES); mouseStatePrev = mouseStateCurr; mouseStateCurr = SDL_GetMouseState(&mouseX, &mouseY); SDL_GetRelativeMouseState(&deltaX, &deltaY); mouseWheelUp = mouseWheelDown = false; processInputEvents(); if (profilerState == PROF_STATE_DATA_RETRIEVAL) { profilerState = PROF_STATE_NO_CAPTURE; overlayProfiler->loadProfilerData(); } else if ( profilerState==PROF_STATE_TIMESLICE_CAPTURE && ui::keyIsPressed(SDL_SCANCODE_GRAVE) && ui::keyWasReleased(SDL_SCANCODE_T) ) { profilerState = PROF_STATE_DATA_RETRIEVAL; profilerStopCapture(); } else if (profilerState == PROF_STATE_FRAME_CAPTURE) { profilerState = PROF_STATE_DATA_RETRIEVAL; profilerStopCapture(); } else if ( profilerState==PROF_STATE_NO_CAPTURE && ui::keyIsPressed(SDL_SCANCODE_GRAVE) && ui::keyWasReleased(SDL_SCANCODE_T) ) { profilerState = PROF_STATE_TIMESLICE_CAPTURE; profilerStartCapture(); } else if ( profilerState==PROF_STATE_NO_CAPTURE && ui::keyIsPressed(SDL_SCANCODE_GRAVE) && ui::keyWasReleased(SDL_SCANCODE_F) ) { profilerState = PROF_STATE_FRAME_CAPTURE; profilerStartCapture(); } else if ( profilerState!=PROF_STATE_NO_CAPTURE && profilerState!=PROF_STATE_TIMESLICE_CAPTURE ) { assert(!"Invalid state"); } if (uiState==STATE_PROFILER) { PROFILER_CPU_TIMESLICE("mProfilerOverlay->updateUI"); overlayProfiler->updateUI(dt); } else if (uiState==STATE_DEFAULT) { PROFILER_CPU_TIMESLICE("onUpdate"); } if (overlayShaderEdit->requireReset()) { PROFILER_CPU_TIMESLICE("onShaderRecompile"); fwk::recompilePrograms(); } checkBoxUpdateAll(); }
static void input() { SDL_PumpEvents(); vec3_t inputvec = {0,0,0}; const uint8_t *keyboard = SDL_GetKeyboardState(0); if(takeinput) { if(state_has_controller() && usecontroller) { inputvec.x = leftstick.x; inputvec.z = leftstick.y; rotx += JOYSTICK_SENSITIVITY_LOOK*rightstick.x*dt/1000.0; roty -= JOYSTICK_SENSITIVITY_LOOK*rightstick.y*dt/1000.0; } else { if(keyboard[SDL_SCANCODE_W]) inputvec.z -= 1; if(keyboard[SDL_SCANCODE_A]) inputvec.x -= 1; if(keyboard[SDL_SCANCODE_S]) inputvec.z += 1; if(keyboard[SDL_SCANCODE_D]) inputvec.x += 1; if(keyboard[SDL_SCANCODE_LSHIFT]) inputvec.y -= 1; if(keyboard[SDL_SCANCODE_SPACE]) inputvec.y += 1; int mousex, mousey; SDL_GetMouseState(&mousex, &mousey); state_mouse_center(); double deltamousex = mousex - windoww/2; double deltamousey = mousey - windowh/2; rotx += MOUSE_SENSITIVITY*deltamousex; roty -= MOUSE_SENSITIVITY*deltamousey; roty = roty > M_PI/2-.005 ? M_PI/2-.005 : roty; roty = roty < -M_PI/2+.005 ? -M_PI/2+.005 : roty; rotx = rotx > M_PI*2 ? rotx - M_PI*2: rotx; rotx = rotx < -M_PI*2 ? rotx + M_PI*2: rotx; } } forwardcamera.x = sin(rotx) * cos(roty); forwardcamera.y = sin(roty); forwardcamera.z = -cos(rotx) * cos(roty); vec3_t rotatevec; rotatevec.x = cos(rotx)*inputvec.x - sin(rotx)*inputvec.z; rotatevec.z = sin(rotx)*inputvec.x + cos(rotx)*inputvec.z; rotatevec.y = inputvec.y; if(dt < 500) { if(flying) { rotatevec.x *= PLAYER_FLY_SPEED * dt / 1000.0; rotatevec.y *= PLAYER_FLY_SPEED * dt / 1000.0; rotatevec.z *= PLAYER_FLY_SPEED * dt / 1000.0; entity_move(pos, &rotatevec); } else { rotatevec.x *= PLAYER_WALK_MAX_FORCE; rotatevec.y = 0; rotatevec.z *= PLAYER_WALK_MAX_FORCE; entity_update(pos, &rotatevec, dt/1000.0); } } if(keyboard[SDL_SCANCODE_R]) { block_t b; b.id = SAND; b.metadata.number = SIM_WATER_LEVELS; world_ray_set(&headpos, &forwardcamera, b, 1, 1, 1000); } if(keyboard[SDL_SCANCODE_E]) { world_ray_del(&headpos, &forwardcamera, 1, 1000); } if(keyboard[SDL_SCANCODE_X]) { vec3_t dir; for(dir.x = -1; dir.x < 1; dir.x += .3) for(dir.y = -1; dir.y < 0; dir.y += .3) for(dir.z = -1; dir.z < 1; dir.z += .3) world_ray_del(&headpos, &dir, 1, 50); } headpos = *posptr; headpos.y += PLAYER_EYEHEIGHT; }
int main(int argc,char*argv[]) { int row,cyc,cycC,iterc,f1,f2, hei,wid,xmp,ymp,msx,msy; Uint8 *p,iter,mouse,tmpmouse; double a,b,c, x_p,y_p, x_max=10,y_max=10, x_min=-10,y_min=-10, x_factor,y_factor, bri=10,gf=4,c_m=10; SDL_Surface *scr; SDL_Event event; char flag=1; struct timespec time; time.tv_sec=0; time.tv_nsec=1000000; row =hei=atoi(*++argv); wid =atoi(*++argv); cycC =atoi(*++argv); scr =SDL_SetVideoMode(hei,wid,24,0); SDL_Init(SDL_INIT_VIDEO); while(1) { iter=10; x_p=hei/(x_max-x_min); y_p=wid/(y_max-y_min); x_factor=(x_max-x_min)/2; y_factor=(y_max-y_min)/2; xmp=x_max*x_p; ymp=y_max*y_p; while(iter--) { a=c=1; b=iter<<3; cyc=cycC; iterc=iter/gf; while(cyc--){ EQ1 EQ2 EQ3 if(a<x_max&&a>x_min&&b<y_max&&b>y_min) { f1=ymp-b*y_p; f2=xmp-a*x_p; p=(Uint8*)scr->pixels+f1*scr->pitch+f2*3; if(p[2]<230) { p[2]+=bri; p[1]=iterc; if(p[0]<230) p[0]+=c*c_m; } } } } SDL_UpdateRect(scr,0,0,scr->w,scr->h); flag=1; mouse=0; while(flag) { while(SDL_PollEvent(&event)); nanosleep(&time,0x0); switch(event.type) { case SDL_KEYDOWN: flag=0; switch(event.key.keysym.sym) { case SDLK_SPACE:SDL_Quit();return 0;break; case SDLK_j:bri*=1.25;break; case SDLK_k:bri/=1.25;break; case SDLK_h:c_m*=2;break; case SDLK_l:c_m/=2;break; case SDLK_o:gf*=1.5;break; case SDLK_n:gf/=1.5;break; default:flag=1; } break; case SDL_MOUSEBUTTONDOWN: tmpmouse=SDL_GetMouseState(&msx,&msy); if(tmpmouse)mouse=tmpmouse; break; case SDL_MOUSEBUTTONUP: if(mouse>0) { if(mouse==2) { x_factor*=2; y_factor*=2; cycC/=2; bri/=2; }else if(mouse==4) { x_factor/=2; y_factor/=2; cycC*=2; bri*=2; } x_min+=(x_max-x_min)*((double)(hei-msx)/(double)hei)-x_factor; y_min+=(y_max-y_min)*((double)(wid-msy)/(double)wid)-y_factor; x_max=x_min+x_factor*2;y_max=y_min+y_factor*2; flag=0; } } } SDL_FillRect(scr,0x0,0x0); } }
// // System platform methods // bool System::getPen3() { SDL_PumpEvents(); return (SDL_BUTTON(SDL_BUTTON_LEFT) && SDL_GetMouseState(&_touchCurX, &_touchCurY)); }
/** * Show and process a dialog. Returns the button number that has been * pressed or SDLGUI_UNKNOWNEVENT if an unsupported event occured (will be * stored in parameter pEventOut). */ int SDLGui_DoDialog(SGOBJ *dlg, SDL_Event *pEventOut) { int obj=0; int oldbutton=0; int retbutton=0; int i, j, b; SDL_Event sdlEvent; SDL_Rect rct; Uint32 grey; SDL_Surface *pBgSurface; SDL_Rect dlgrect, bgrect; if (pSdlGuiScrn->h / sdlgui_fontheight < dlg[0].h) { fprintf(stderr, "Screen size too small for dialog!\n"); return SDLGUI_ERROR; } grey = SDL_MapRGB(pSdlGuiScrn->format,181,183,170); dlgrect.x = dlg[0].x * sdlgui_fontwidth; dlgrect.y = dlg[0].y * sdlgui_fontheight; dlgrect.w = dlg[0].w * sdlgui_fontwidth; dlgrect.h = dlg[0].h * sdlgui_fontheight; bgrect.x = bgrect.y = 0; bgrect.w = dlgrect.w; bgrect.h = dlgrect.h; /* Save background */ pBgSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, dlgrect.w, dlgrect.h, pSdlGuiScrn->format->BitsPerPixel, pSdlGuiScrn->format->Rmask, pSdlGuiScrn->format->Gmask, pSdlGuiScrn->format->Bmask, pSdlGuiScrn->format->Amask); if (pSdlGuiScrn->format->palette != NULL) { SDL_SetPaletteColors(pBgSurface->format->palette, pSdlGuiScrn->format->palette->colors, 0, pSdlGuiScrn->format->palette->ncolors-1); } if (pBgSurface != NULL) { SDL_BlitSurface(pSdlGuiScrn, &dlgrect, pBgSurface, &bgrect); } else { fprintf(stderr, "SDLGUI_DoDialog: CreateRGBSurface failed: %s\n", SDL_GetError()); } /* (Re-)draw the dialog */ SDLGui_DrawDialog(dlg); /* Is the left mouse button still pressed? Yes -> Handle TOUCHEXIT objects here */ SDL_PumpEvents(); b = SDL_GetMouseState(&i, &j); /* If current object is the scrollbar, and mouse is still down, we can scroll it */ /* also if the mouse pointer has left the scrollbar */ if (dlg[current_object].type == SGSCROLLBAR) { if (b & SDL_BUTTON(1)) { obj = current_object; dlg[obj].state |= SG_MOUSEDOWN; oldbutton = obj; retbutton = obj; } else { obj = current_object; current_object = 0; dlg[obj].state &= SG_MOUSEUP; retbutton = obj; oldbutton = obj; } } else { obj = SDLGui_FindObj(dlg, i, j); current_object = obj; if (obj > 0 && (dlg[obj].flags&SG_TOUCHEXIT) ) { oldbutton = obj; if (b & SDL_BUTTON(1)) { dlg[obj].state |= SG_SELECTED; retbutton = obj; } } } /* The main loop */ while (retbutton == 0 && !bQuitProgram) { if (SDL_WaitEvent(&sdlEvent) == 1) /* Wait for events */ switch (sdlEvent.type) { case SDL_QUIT: retbutton = SDLGUI_QUIT; break; case SDL_MOUSEBUTTONDOWN: if (sdlEvent.button.button != SDL_BUTTON_LEFT) { /* Not left mouse button -> unsupported event */ if (pEventOut) retbutton = SDLGUI_UNKNOWNEVENT; break; } /* It was the left button: Find the object under the mouse cursor */ obj = SDLGui_FindObj(dlg, sdlEvent.button.x, sdlEvent.button.y); if (obj>0) { if (dlg[obj].type==SGBUTTON) { dlg[obj].state |= SG_SELECTED; SDLGui_DrawButton(dlg, obj); SDL_UpdateRect(pSdlGuiScrn, (dlg[0].x+dlg[obj].x)*sdlgui_fontwidth-2, (dlg[0].y+dlg[obj].y)*sdlgui_fontheight-2, dlg[obj].w*sdlgui_fontwidth+4, dlg[obj].h*sdlgui_fontheight+4); oldbutton=obj; } if (dlg[obj].type==SGSCROLLBAR) { dlg[obj].state |= SG_MOUSEDOWN; oldbutton=obj; } if ( dlg[obj].flags&SG_TOUCHEXIT ) { dlg[obj].state |= SG_SELECTED; retbutton = obj; } } break; case SDL_MOUSEBUTTONUP: if (sdlEvent.button.button != SDL_BUTTON_LEFT) { /* Not left mouse button -> unsupported event */ if (pEventOut) retbutton = SDLGUI_UNKNOWNEVENT; break; } /* It was the left button: Find the object under the mouse cursor */ obj = SDLGui_FindObj(dlg, sdlEvent.button.x, sdlEvent.button.y); if (obj>0) { switch (dlg[obj].type) { case SGBUTTON: if (oldbutton==obj) retbutton=obj; break; case SGSCROLLBAR: dlg[obj].state &= SG_MOUSEUP; if (oldbutton==obj) retbutton=obj; break; case SGEDITFIELD: SDLGui_EditField(dlg, obj); break; case SGRADIOBUT: for (i = obj-1; i > 0 && dlg[i].type == SGRADIOBUT; i--) { dlg[i].state &= ~SG_SELECTED; /* Deselect all radio buttons in this group */ rct.x = (dlg[0].x+dlg[i].x)*sdlgui_fontwidth; rct.y = (dlg[0].y+dlg[i].y)*sdlgui_fontheight; rct.w = sdlgui_fontwidth; rct.h = sdlgui_fontheight; SDL_FillRect(pSdlGuiScrn, &rct, grey); /* Clear old */ SDLGui_DrawRadioButton(dlg, i); SDL_UpdateRects(pSdlGuiScrn, 1, &rct); } for (i = obj+1; dlg[i].type == SGRADIOBUT; i++) { dlg[i].state &= ~SG_SELECTED; /* Deselect all radio buttons in this group */ rct.x = (dlg[0].x+dlg[i].x)*sdlgui_fontwidth; rct.y = (dlg[0].y+dlg[i].y)*sdlgui_fontheight; rct.w = sdlgui_fontwidth; rct.h = sdlgui_fontheight; SDL_FillRect(pSdlGuiScrn, &rct, grey); /* Clear old */ SDLGui_DrawRadioButton(dlg, i); SDL_UpdateRects(pSdlGuiScrn, 1, &rct); } dlg[obj].state |= SG_SELECTED; /* Select this radio button */ rct.x = (dlg[0].x+dlg[obj].x)*sdlgui_fontwidth; rct.y = (dlg[0].y+dlg[obj].y)*sdlgui_fontheight; rct.w = sdlgui_fontwidth; rct.h = sdlgui_fontheight; SDL_FillRect(pSdlGuiScrn, &rct, grey); /* Clear old */ SDLGui_DrawRadioButton(dlg, obj); SDL_UpdateRects(pSdlGuiScrn, 1, &rct); retbutton = obj; // added by andreas_g break; case SGCHECKBOX: dlg[obj].state ^= SG_SELECTED; rct.x = (dlg[0].x+dlg[obj].x)*sdlgui_fontwidth; rct.y = (dlg[0].y+dlg[obj].y)*sdlgui_fontheight; rct.w = sdlgui_fontwidth; rct.h = sdlgui_fontheight; SDL_FillRect(pSdlGuiScrn, &rct, grey); /* Clear old */ SDLGui_DrawCheckBox(dlg, obj); SDL_UpdateRects(pSdlGuiScrn, 1, &rct); retbutton = obj; // added by andreas_g break; case SGPOPUP: dlg[obj].state |= SG_SELECTED; SDLGui_DrawPopupButton(dlg, obj); SDL_UpdateRect(pSdlGuiScrn, (dlg[0].x+dlg[obj].x)*sdlgui_fontwidth-2, (dlg[0].y+dlg[obj].y)*sdlgui_fontheight-2, dlg[obj].w*sdlgui_fontwidth+4, dlg[obj].h*sdlgui_fontheight+4); retbutton=obj; break; } } if (oldbutton > 0 && dlg[oldbutton].type == SGBUTTON) { dlg[oldbutton].state &= ~SG_SELECTED; SDLGui_DrawButton(dlg, oldbutton); SDL_UpdateRect(pSdlGuiScrn, (dlg[0].x+dlg[oldbutton].x)*sdlgui_fontwidth-2, (dlg[0].y+dlg[oldbutton].y)*sdlgui_fontheight-2, dlg[oldbutton].w*sdlgui_fontwidth+4, dlg[oldbutton].h*sdlgui_fontheight+4); oldbutton = 0; } if (obj >= 0 && (dlg[obj].flags&SG_EXIT)) { retbutton = obj; } break; case SDL_JOYAXISMOTION: case SDL_JOYBALLMOTION: case SDL_JOYHATMOTION: case SDL_MOUSEMOTION: break; case SDL_KEYDOWN: /* Key pressed */ if (sdlEvent.key.keysym.sym == SDLK_RETURN || sdlEvent.key.keysym.sym == SDLK_KP_ENTER) { retbutton = SDLGui_SearchFlaggedButton(dlg, SG_DEFAULT); } else if (sdlEvent.key.keysym.sym == SDLK_ESCAPE) { retbutton = SDLGui_SearchFlaggedButton(dlg, SG_CANCEL); } else if (pEventOut) { retbutton = SDLGUI_UNKNOWNEVENT; } break; default: if (pEventOut) retbutton = SDLGUI_UNKNOWNEVENT; break; } } /* Restore background */ if (pBgSurface) { SDL_BlitSurface(pBgSurface, &bgrect, pSdlGuiScrn, &dlgrect); SDL_FreeSurface(pBgSurface); } /* Copy event data of unsupported events if caller wants to have it */ if (retbutton == SDLGUI_UNKNOWNEVENT && pEventOut) memcpy(pEventOut, &sdlEvent, sizeof(SDL_Event)); if (retbutton == SDLGUI_QUIT) bQuitProgram = true; return retbutton; }
bool Player::handleSdlEvent(SDL_Event& event) { switch(event.type) { case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_a: case SDLK_LEFT: { boolKeyboardAngle = true; deltaAngle = -TURN_SPEED; } break; case SDLK_d: case SDLK_RIGHT: { boolKeyboardAngle = true; deltaAngle = TURN_SPEED; } break; case SDLK_w: case SDLK_UP: { boolMove = true; deltaMove = MOVEMENT_SPEED; } break; case SDLK_s: case SDLK_DOWN: { boolMove = true; deltaMove = -MOVEMENT_SPEED; } break; case SDLK_SPACE: { if(boolOnTheGround || allowedToFly) ySpeed = JUMP_START_SPEED; } break; case SDLK_e: { bomb = new Bomba(x, y, z, shootAng, shootForce, playerlx, playerly, playerlz); } break; case SDLK_f: { allowedToFly = !allowedToFly; } break; case SDLK_1: { shootForce -= SHOOT_FORCE_INCREMENT; if(shootForce < SHOOT_FORCE_MIN) shootForce = SHOOT_FORCE_MIN; } break; case SDLK_2: { shootForce += SHOOT_FORCE_INCREMENT; if(shootForce > SHOOT_FORCE_MAX) shootForce = SHOOT_FORCE_MAX; } break; } break; case SDL_KEYUP: switch(event.key.keysym.sym) { case SDLK_a: case SDLK_LEFT: if (deltaAngle < 0.0f) { boolKeyboardAngle = false; deltaAngle = 0.0f; } break; case SDLK_d: case SDLK_RIGHT: if (deltaAngle > 0.0f) { boolKeyboardAngle = false; deltaAngle = 0.0f; } break; case SDLK_w: case SDLK_UP: if (deltaMove > 0) { boolMove = false; deltaMove = 0; } break; case SDLK_s: case SDLK_DOWN: if (deltaMove < 0) { boolMove = false; deltaMove = 0; } break; } break; case SDL_MOUSEWHEEL: if(event.wheel.y > 0) { shootAng += ANG_INCREMENT; if(shootAng > ANG_MAX) shootAng = ANG_MAX; } else if(event.wheel.y < 0) { shootAng -= ANG_INCREMENT; if(shootAng < ANG_MIN) shootAng = ANG_MIN; } break; case SDL_MOUSEBUTTONDOWN: SDL_GetMouseState(&mouseLastX, &mouseLastY); if(event.button.button == SDL_BUTTON_LEFT) mouseLeftPressed = true; else if(event.button.button == SDL_BUTTON_RIGHT) mouseRightPressed = true; break; case SDL_MOUSEBUTTONUP: if(event.button.button == SDL_BUTTON_LEFT) mouseLeftPressed = false; else if(event.button.button == SDL_BUTTON_RIGHT) mouseRightPressed = false; break; case SDL_MOUSEMOTION: if(mouseLeftPressed || mouseRightPressed) { int mouseX, mouseY; SDL_GetMouseState(&mouseX, &mouseY); // ângulo atual após movimento é o ângulo original + diferença // da pos original e a pos atual do mouse * sensibilidade cameraAngleX = cameraAngleX + (mouseX - mouseLastX) * MOUSE_SENSIBILITY; cameraAngleY = cameraAngleY + (mouseY - mouseLastY) * MOUSE_SENSIBILITY; mouseLastX = mouseX; mouseLastY = mouseY; // evita que camera rode de cabeça pra baixo e flipe // (trava quando olhando completamente pra baixo e tenta ir mais) if(cameraAngleY > 1.50) cameraAngleY = 1.50; else if(cameraAngleY < -1.50) cameraAngleY = -1.50; camlx = cos(cameraAngleY)*sin(cameraAngleX); camlz = -cos(cameraAngleY)*cos(cameraAngleX); camly = -sin(cameraAngleY); } break; } //if(evtHandler) // evtHandler(event); return true; }
static void mouseInputCallback(GuiElement_t * elem, bool pressed, int x, int y) { GuiElement_t::defaultInputCallback(elem, pressed, x, y); mouseButtons[button] = elem->toggled || (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(button)); }
int CInput::Update() { // keep the counter between 1..0xFFFF, 0 means not pressed m_InputCounter = (m_InputCounter%0xFFFF)+1; // these states must always be updated manually because they are not in the GetKeyState from SDL int i = SDL_GetMouseState(NULL, NULL); if(i&SDL_BUTTON(1)) m_aInputState[KEY_MOUSE_1] = 1; // 1 is left if(i&SDL_BUTTON(3)) m_aInputState[KEY_MOUSE_2] = 1; // 3 is right if(i&SDL_BUTTON(2)) m_aInputState[KEY_MOUSE_3] = 1; // 2 is middle if(i&SDL_BUTTON(4)) m_aInputState[KEY_MOUSE_4] = 1; if(i&SDL_BUTTON(5)) m_aInputState[KEY_MOUSE_5] = 1; if(i&SDL_BUTTON(6)) m_aInputState[KEY_MOUSE_6] = 1; if(i&SDL_BUTTON(7)) m_aInputState[KEY_MOUSE_7] = 1; if(i&SDL_BUTTON(8)) m_aInputState[KEY_MOUSE_8] = 1; if(i&SDL_BUTTON(9)) m_aInputState[KEY_MOUSE_9] = 1; { SDL_Event Event; bool IgnoreKeys = false; while(SDL_PollEvent(&Event)) { int Key = -1; int Scancode = 0; int Action = IInput::FLAG_PRESS; switch (Event.type) { case SDL_TEXTINPUT: AddEvent(Event.text.text, 0, IInput::FLAG_TEXT); break; // handle keys case SDL_KEYDOWN: // See SDL_Keymod for possible modifiers: // NONE = 0 // LSHIFT = 1 // RSHIFT = 2 // LCTRL = 64 // RCTRL = 128 // LALT = 256 // RALT = 512 // LGUI = 1024 // RGUI = 2048 // NUM = 4096 // CAPS = 8192 // MODE = 16384 // Sum if you want to ignore multiple modifiers. if(!(Event.key.keysym.mod & g_Config.m_InpIgnoredModifiers)) { Key = KeycodeToKey(Event.key.keysym.sym); Scancode = Event.key.keysym.scancode; } break; case SDL_KEYUP: Action = IInput::FLAG_RELEASE; Key = KeycodeToKey(Event.key.keysym.sym); Scancode = Event.key.keysym.scancode; break; // handle mouse buttons case SDL_MOUSEBUTTONUP: Action = IInput::FLAG_RELEASE; if(Event.button.button == 1) // ignore_convention { m_ReleaseDelta = time_get() - m_LastRelease; m_LastRelease = time_get(); } // fall through case SDL_MOUSEBUTTONDOWN: if(Event.button.button == SDL_BUTTON_LEFT) Key = KEY_MOUSE_1; // ignore_convention if(Event.button.button == SDL_BUTTON_RIGHT) Key = KEY_MOUSE_2; // ignore_convention if(Event.button.button == SDL_BUTTON_MIDDLE) Key = KEY_MOUSE_3; // ignore_convention if(Event.button.button == SDL_BUTTON_X1) Key = KEY_MOUSE_4; // ignore_convention if(Event.button.button == SDL_BUTTON_X2) Key = KEY_MOUSE_5; // ignore_convention if(Event.button.button == 6) Key = KEY_MOUSE_6; // ignore_convention if(Event.button.button == 7) Key = KEY_MOUSE_7; // ignore_convention if(Event.button.button == 8) Key = KEY_MOUSE_8; // ignore_convention if(Event.button.button == 9) Key = KEY_MOUSE_9; // ignore_convention Scancode = Key; break; case SDL_MOUSEWHEEL: if(Event.wheel.y > 0) Key = KEY_MOUSE_WHEEL_UP; // ignore_convention if(Event.wheel.y < 0) Key = KEY_MOUSE_WHEEL_DOWN; // ignore_convention Action |= IInput::FLAG_RELEASE; Scancode = Key; break; case SDL_WINDOWEVENT: // Ignore keys following a focus gain as they may be part of global // shortcuts switch (Event.window.event) { case SDL_WINDOWEVENT_RESIZED: #if defined(SDL_VIDEO_DRIVER_X11) Graphics()->Resize(Event.window.data1, Event.window.data2); #elif defined(__ANDROID__) m_VideoRestartNeeded = 1; #endif break; case SDL_WINDOWEVENT_FOCUS_GAINED: if(m_InputGrabbed) MouseModeRelative(); m_MouseFocus = true; IgnoreKeys = true; break; case SDL_WINDOWEVENT_FOCUS_LOST: m_MouseFocus = false; IgnoreKeys = true; if(m_InputGrabbed) { MouseModeAbsolute(); // Remember that we had relative mouse m_InputGrabbed = true; } break; #if defined(CONF_PLATFORM_MACOSX) // Todo: remove this when fixed in SDL case SDL_WINDOWEVENT_MAXIMIZED: MouseModeAbsolute(); MouseModeRelative(); break; #endif } break; // other messages case SDL_QUIT: return 1; } static bool HoldKeys[512] = {false}; if(Key >= 0 && Key < g_MaxKeys && !IgnoreKeys) { if(Action&IInput::FLAG_PRESS) { m_aInputState[Scancode] = 1; m_aInputCount[Key] = m_InputCounter; // EVENT CALL if(!HoldKeys[Key]) { //LastKey = Key; for(int ijdfg = 0; ijdfg < CLua::Client()->Lua()->GetLuaFiles().size(); ijdfg++) { if(CLua::Client()->Lua()->GetLuaFiles()[ijdfg]->State() != CLuaFile::LUAFILE_STATE_LOADED) continue; LuaRef lfunc = CLua::Client()->Lua()->GetLuaFiles()[ijdfg]->GetFunc("OnKeyPress"); if(lfunc) try { lfunc(IInput::KeyName(Key)); } catch(std::exception &e) { CLua::Client()->Lua()->HandleException(e, CLua::Client()->Lua()->GetLuaFiles()[ijdfg]); } } //CLua::LUA_FIRE_EVENT_V("OnKeyPress", IInput::KeyName(Key)); HoldKeys[Key] = true; } } if(Action&IInput::FLAG_RELEASE) { // EVENT CALL for(int ijdfg = 0; ijdfg < CLua::Client()->Lua()->GetLuaFiles().size(); ijdfg++) { if(CLua::Client()->Lua()->GetLuaFiles()[ijdfg]->State() != CLuaFile::LUAFILE_STATE_LOADED) continue; LuaRef lfunc = CLua::Client()->Lua()->GetLuaFiles()[ijdfg]->GetFunc("OnKeyRelease"); if(lfunc) try { lfunc(IInput::KeyName(Key)); } catch(std::exception &e) { CLua::Client()->Lua()->HandleException(e, CLua::Client()->Lua()->GetLuaFiles()[ijdfg]); } } //CLua::LUA_FIRE_EVENT_V("OnKeyRelease", IInput::KeyName(Key)); HoldKeys[Key] = false; } AddEvent(0, Key, Action); } } } return 0; }
void SDL_GetCursorPos( POINT *p ) { SDL_GetMouseState( (int *)&p->x, (int *)&p->y ); }
static void sdl_refresh(DisplayState *ds) { SDL_Event ev1, *ev = &ev1; int mod_state; int buttonstate = SDL_GetMouseState(NULL, NULL); if (last_vm_running != vm_running) { last_vm_running = vm_running; sdl_update_caption(); } vga_hw_update(); SDL_EnableUNICODE(!is_graphic_console()); while (SDL_PollEvent(ev)) { switch (ev->type) { case SDL_VIDEOEXPOSE: sdl_update(ds, 0, 0, real_screen->w, real_screen->h); break; case SDL_KEYDOWN: case SDL_KEYUP: if (ev->type == SDL_KEYDOWN) { if (alt_grab) { mod_state = (SDL_GetModState() & (gui_grab_code | KMOD_LSHIFT)) == (gui_grab_code | KMOD_LSHIFT); } else if (ctrl_grab) { mod_state = (SDL_GetModState() & KMOD_RCTRL) == KMOD_RCTRL; } else { mod_state = (SDL_GetModState() & gui_grab_code) == gui_grab_code; } gui_key_modifier_pressed = mod_state; if (gui_key_modifier_pressed) { int keycode; keycode = sdl_keyevent_to_keycode(&ev->key); switch(keycode) { case 0x21: /* 'f' key on US keyboard */ toggle_full_screen(ds); gui_keysym = 1; break; case 0x16: /* 'u' key on US keyboard */ scaling_active = 0; sdl_resize(ds); vga_hw_invalidate(); vga_hw_update(); break; case 0x02 ... 0x0a: /* '1' to '9' keys */ /* Reset the modifiers sent to the current console */ reset_keys(); console_select(keycode - 0x02); if (!is_graphic_console()) { /* display grab if going to a text console */ if (gui_grab) sdl_grab_end(); } gui_keysym = 1; break; default: break; } } else if (!is_graphic_console()) { int keysym; keysym = 0; if (ev->key.keysym.mod & (KMOD_LCTRL | KMOD_RCTRL)) { switch(ev->key.keysym.sym) { case SDLK_UP: keysym = QEMU_KEY_CTRL_UP; break; case SDLK_DOWN: keysym = QEMU_KEY_CTRL_DOWN; break; case SDLK_LEFT: keysym = QEMU_KEY_CTRL_LEFT; break; case SDLK_RIGHT: keysym = QEMU_KEY_CTRL_RIGHT; break; case SDLK_HOME: keysym = QEMU_KEY_CTRL_HOME; break; case SDLK_END: keysym = QEMU_KEY_CTRL_END; break; case SDLK_PAGEUP: keysym = QEMU_KEY_CTRL_PAGEUP; break; case SDLK_PAGEDOWN: keysym = QEMU_KEY_CTRL_PAGEDOWN; break; default: break; } } else { switch(ev->key.keysym.sym) { case SDLK_UP: keysym = QEMU_KEY_UP; break; case SDLK_DOWN: keysym = QEMU_KEY_DOWN; break; case SDLK_LEFT: keysym = QEMU_KEY_LEFT; break; case SDLK_RIGHT: keysym = QEMU_KEY_RIGHT; break; case SDLK_HOME: keysym = QEMU_KEY_HOME; break; case SDLK_END: keysym = QEMU_KEY_END; break; case SDLK_PAGEUP: keysym = QEMU_KEY_PAGEUP; break; case SDLK_PAGEDOWN: keysym = QEMU_KEY_PAGEDOWN; break; case SDLK_BACKSPACE: keysym = QEMU_KEY_BACKSPACE; break; case SDLK_DELETE: keysym = QEMU_KEY_DELETE; break; default: break; } } if (keysym) { kbd_put_keysym(keysym); } else if (ev->key.keysym.unicode != 0) { kbd_put_keysym(ev->key.keysym.unicode); } } } else if (ev->type == SDL_KEYUP) { if (!alt_grab) { mod_state = (ev->key.keysym.mod & gui_grab_code); } else { mod_state = (ev->key.keysym.mod & (gui_grab_code | KMOD_LSHIFT)); } if (!mod_state) { if (gui_key_modifier_pressed) { gui_key_modifier_pressed = 0; if (gui_keysym == 0) { /* exit/enter grab if pressing Ctrl-Alt */ if (!gui_grab) { /* if the application is not active, do not try to enter grab state. It prevents 'SDL_WM_GrabInput(SDL_GRAB_ON)' from blocking all the application (SDL bug). */ if (SDL_GetAppState() & SDL_APPACTIVE) sdl_grab_start(); } else { sdl_grab_end(); } /* SDL does not send back all the modifiers key, so we must correct it */ reset_keys(); break; } gui_keysym = 0; } } } if (is_graphic_console() && !gui_keysym) sdl_process_key(&ev->key); break; case SDL_QUIT: if (!no_quit) qemu_system_shutdown_request(); break; case SDL_MOUSEMOTION: if (gui_grab || kbd_mouse_is_absolute() || absolute_enabled) { sdl_send_mouse_event(ev->motion.xrel, ev->motion.yrel, 0, ev->motion.x, ev->motion.y, ev->motion.state); } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { SDL_MouseButtonEvent *bev = &ev->button; if (!gui_grab && !kbd_mouse_is_absolute()) { if (ev->type == SDL_MOUSEBUTTONDOWN && (bev->button == SDL_BUTTON_LEFT)) { /* start grabbing all events */ sdl_grab_start(); } } else { int dz; dz = 0; if (ev->type == SDL_MOUSEBUTTONDOWN) { buttonstate |= SDL_BUTTON(bev->button); } else { buttonstate &= ~SDL_BUTTON(bev->button); } #ifdef SDL_BUTTON_WHEELUP if (bev->button == SDL_BUTTON_WHEELUP && ev->type == SDL_MOUSEBUTTONDOWN) { dz = -1; } else if (bev->button == SDL_BUTTON_WHEELDOWN && ev->type == SDL_MOUSEBUTTONDOWN) { dz = 1; } #endif sdl_send_mouse_event(0, 0, dz, bev->x, bev->y, buttonstate); } } break; case SDL_ACTIVEEVENT: if (gui_grab && ev->active.state == SDL_APPINPUTFOCUS && !ev->active.gain && !gui_fullscreen_initial_grab) { sdl_grab_end(); } if (ev->active.state & SDL_APPACTIVE) { if (ev->active.gain) { /* Back to default interval */ dcl->gui_timer_interval = 0; dcl->idle = 0; } else { /* Sleeping interval */ dcl->gui_timer_interval = 500; dcl->idle = 1; } } break; case SDL_VIDEORESIZE: { SDL_ResizeEvent *rev = &ev->resize; int bpp = real_screen->format->BitsPerPixel; if (bpp != 16 && bpp != 32) bpp = 32; do_sdl_resize(rev->w, rev->h, bpp); scaling_active = 1; if (!is_buffer_shared(ds->surface)) { ds->surface = qemu_resize_displaysurface(ds, ds_get_width(ds), ds_get_height(ds)); dpy_resize(ds); } vga_hw_invalidate(); vga_hw_update(); break; } default: break; }
void draw(surface screen) { if(use_color_cursors() == false) { return; } if(current_cursor == NUM_CURSORS) { current_cursor = NORMAL; } if(have_focus == false) { cursor_buf = NULL; return; } if (!color_ready) { // Display start to draw cursor // so it can now display color cursor color_ready = true; // Reset the cursor to be sure that we hide the b&w set(); } /** @todo FIXME: don't parse the file path every time */ const surface surf(image::get_image("cursors/" + color_images[current_cursor])); if(surf == NULL) { // Fall back to b&w cursors std::cerr << "could not load color cursors. Falling back to hardware cursors\n"; preferences::set_color_cursors(false); return; } if(cursor_buf != NULL && (cursor_buf->w != surf->w || cursor_buf->h != surf->h)) { cursor_buf = NULL; } if(cursor_buf == NULL) { cursor_buf = create_compatible_surface(surf); if(cursor_buf == NULL) { std::cerr << "Could not allocate surface for mouse cursor\n"; return; } } int new_cursor_x, new_cursor_y; SDL_GetMouseState(&new_cursor_x,&new_cursor_y); const bool must_update = new_cursor_x != cursor_x || new_cursor_y != cursor_y; cursor_x = new_cursor_x; cursor_y = new_cursor_y; // Save the screen area where the cursor is being drawn onto the back buffer SDL_Rect area = sdl::create_rect(cursor_x - shift_x[current_cursor] , cursor_y - shift_y[current_cursor] , surf->w , surf->h); sdl_copy_portion(screen,&area,cursor_buf,NULL); // Blit the surface sdl_blit(surf,NULL,screen,&area); if(must_update) { update_rect(area); } }
/********************************************* per-frame logic goes here **********************************************/ void App::updateMain(){ //Get the mouse pointer pos in screen space SDL_GetMouseState(&iMouseX, &iMouseY); //Throw away any bad frames if(fTimeScale == infinity || fTimeScale == 0.0f){ return; } float fCamSpeed = fTimeScale * 10.0f; float fDragScale = 0.05f; if (!this->bGlobalDisableKeyMovement) { //Right button means we reset rotation and such //NOTE: I did have this as 'both left and right at once', which seemed //to make more sense, but it doesn't work great on systems that map this //to middle-mouse if(mouseDown(3)){ resetCam(); } //Rotation for the wall /* float camTime = fUptime * 0.1f; float fRotateSpeed = fCamSpeed; fRot[1] += fRotateSpeed; fRot[0] = (sinf(camTime) * 5); fCameraY = cosf(camTime) * 5; fZoom = (sinf(camTime) * 15) + 27; */ //LOG("%f, %f\n", fRot[1], fZoom); //fZoom = -10; //Keyboard rotation if(keyDown(SDLK_RSHIFT) || keyDown(SDLK_LSHIFT)){ fCamSpeed *= 10; } if(keyDown(SDLK_LEFT)) fRot[1] -= fCamSpeed; if(keyDown(SDLK_RIGHT)) fRot[1] += fCamSpeed; if(keyDown(SDLK_UP)) fRot[0] -= fCamSpeed; if(keyDown(SDLK_DOWN)) fRot[0] += fCamSpeed; if(keyDown(SDLK_w)) { fCameraZ -= fCamSpeed; //fRot[0] = 0.0; fRot[1] = 0.0; fRot[2] = 0.0; fLookZ -= fCamSpeed; } if(keyDown(SDLK_s)) { fCameraZ += fCamSpeed; //fRot[0] = 0.0; fRot[1] = 0.0; fRot[2] = 0.0; fLookZ += fCamSpeed; } if(keyDown(SDLK_a)) { fCameraX -= fCamSpeed; fLookX -= fCamSpeed; } if(keyDown(SDLK_d)) { fCameraX += fCamSpeed; fLookX += fCamSpeed; } if(keyDown(SDLK_SPACE)) resetCam(); //If we're actively dragging with the mouse if(bDrag){ //Figure out the drag vectors and stuff Vector2 drag = getMouse(); Vector2 diff = (dragStart - drag) * fDragScale; //Left mouse button means we modify the rotation if(mouseDown(1)){ fRot[1] -= diff.x; fRot[0] -= diff.y; } //Middle mouse means we modify the zoom else if(mouseDown(2)){ fZoom += diff.y; } dragVel = diff; dragStart = getMouse(); }else{ //fRot[1] -= dragVel.x; //fRot[0] -= dragVel.y; } } updateSocket(); //Hack! The shader system doesn't really play nice with the banner, so //we disable it here. if(!isConnected()){ if(ps()->getType() <= PARTICLE_SYSTEM_POINTSPRITES) generateTestData(); else fGUITimeout = 1.0f; } mParticleSystem->update(); }
// button can SDL_BUTTON_LEFT, SDL_BUTTON_RIGHT and SDL_BUTTON_MIDDLE bool SDLWindowManager::isMouseButtonPressed(uint32_t button) const { return SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON(button); }
void CLevelEditor::Draw( CDrawContext * pDrawContext ) { if( !m_bEditorOn || !m_pCurLevel ) return; int mx, my; SDL_GetMouseState( &mx, &my ); Vector2< float > cameraTranslate; if( m_pCamera ) { cameraTranslate = m_pCamera->GetTranslate(); } float gridOffsetX = cameraTranslate.GetX() - ( ( int )( cameraTranslate.GetX() / TEXTURE_RENDER_WIDTH ) * TEXTURE_RENDER_WIDTH ); float gridOffsetY = cameraTranslate.GetY() - ( ( int )( cameraTranslate.GetY() / TEXTURE_RENDER_HEIGHT ) * TEXTURE_RENDER_HEIGHT ); int selectedTileX = mx / TEXTURE_RENDER_WIDTH_EDITOR; int selectedTileY = my / TEXTURE_RENDER_HEIGHT_EDITOR; int tileX = ( mx - gridOffsetX ) / TEXTURE_RENDER_WIDTH; int tileY = ( my - gridOffsetY ) / TEXTURE_RENDER_HEIGHT; pDrawContext->DrawMaterial( *m_pPixel, tileX * TEXTURE_RENDER_WIDTH + gridOffsetX, tileY * TEXTURE_RENDER_HEIGHT + gridOffsetY, TEXTURE_RENDER_WIDTH, TEXTURE_RENDER_HEIGHT, 0.5f, 0.5f, 1.0f, 0.5f ); int numLinesHoriz = m_WindowSize.GetX() / TEXTURE_RENDER_WIDTH; int numLinesVert = m_WindowSize.GetY() / TEXTURE_RENDER_HEIGHT; for( int j = 0; j < numLinesHoriz + 1; j++ ) pDrawContext->DrawMaterial( *m_pPixel, j * TEXTURE_RENDER_WIDTH + gridOffsetX, gridOffsetY - TEXTURE_RENDER_HEIGHT, GRIDLINE_THICKNESS, m_WindowSize.GetY() + TEXTURE_RENDER_HEIGHT * 2, 1.0f, 1.0f, 1.0f, 1.0f ); for( int j = 0; j < numLinesVert + 1; j++ ) pDrawContext->DrawMaterial( *m_pPixel, gridOffsetX - TEXTURE_RENDER_WIDTH, j * TEXTURE_RENDER_HEIGHT + gridOffsetY, m_WindowSize.GetX() + TEXTURE_RENDER_WIDTH * 2, GRIDLINE_THICKNESS, 1.0f, 1.0f, 1.0f, 1.0f ); if( m_CurTileMenu < m_pTileMenus.size() ) { std::vector< CTextureImage * > pTiles = m_pTileMenus[m_CurTileMenu].GetTiles(); int numTilesInMenu = pTiles.size(); const int tileMenuNumColumns = 3; int tileMenuNumRows = ( ( float ) numTilesInMenu / ( float )tileMenuNumColumns + .99f ); int curTileIndex = 0; int tileMenuWidth = tileMenuNumColumns * TEXTURE_RENDER_WIDTH_EDITOR; int tileMenuHeight = tileMenuNumRows * TEXTURE_RENDER_HEIGHT_EDITOR; pDrawContext->DrawMaterial( *m_pPixel, 0, 0, tileMenuWidth, tileMenuHeight, 0.5f, 0.5f, 1.0f, 0.2f ); for( int y = 0; y < tileMenuNumRows; y++ ) { for( int x = 0; x < tileMenuNumColumns; x++ ) { pDrawContext->DrawMaterial( *pTiles[curTileIndex], x * TEXTURE_RENDER_WIDTH_EDITOR, y * TEXTURE_RENDER_HEIGHT_EDITOR, TEXTURE_RENDER_WIDTH_EDITOR, TEXTURE_RENDER_HEIGHT_EDITOR, 1.0f, 1.0f, 1.0f, 1.0f ); if( curTileIndex == m_SelectedTileIndex ) { pDrawContext->DrawMaterial( *m_pPixel, x * TEXTURE_RENDER_WIDTH_EDITOR, y * TEXTURE_RENDER_HEIGHT_EDITOR, TEXTURE_RENDER_WIDTH_EDITOR, TEXTURE_RENDER_HEIGHT_EDITOR, 1.0f, 0.0f, 1.0f, 0.2f ); } if( ++curTileIndex >= numTilesInMenu ) break; } } m_CurTileIndex = -1; if( mx < tileMenuWidth && my < tileMenuHeight ) { m_CurTileIndex = selectedTileX + selectedTileY * tileMenuNumColumns; pDrawContext->DrawMaterial( *m_pPixel, selectedTileX * TEXTURE_RENDER_WIDTH_EDITOR, selectedTileY * TEXTURE_RENDER_HEIGHT_EDITOR, TEXTURE_RENDER_WIDTH_EDITOR, TEXTURE_RENDER_HEIGHT_EDITOR, 1.0f, 1.0f, 1.0f, 0.3f ); } } if( SDL_GetTicks() - m_LastSaveTime < 1000 ) { pDrawContext->DrawMaterial( *m_pPixel, 0.0f, 0.0f, m_WindowSize.GetX(), m_WindowSize.GetY() * .1f, 0.0f, 1.0f, 0.0f, 0.5f ); } }
glm::ivec2 SDLWindowManager::getMousePosition() const { glm::ivec2 mousePos; SDL_GetMouseState(&mousePos.x, &mousePos.y); return mousePos; }
void checkCommands(Uint8 *keys, int *mx, int *my) { int i = 0; SDL_Rect dest; if(HUD.menu == 0) { // Pan around map if( ((*mx > (screen->clip_rect.x+screen->w-15)) || keys[SDLK_RIGHT]) && (Camera.x + 25*sSpeed + Camera.w) < (map->clip_rect.x+map->w) ) { Camera.x += 25*sSpeed; } else if( ((*mx < (screen->clip_rect.x+15)) || keys[SDLK_LEFT]) && (Camera.x - 25*sSpeed > map->clip_rect.x) ) { Camera.x -= 25*sSpeed; } if( ((*my > (screen->clip_rect.y+screen->h-15)) || keys[SDLK_DOWN] ) && (Camera.y + 25*sSpeed + Camera.h) < (map->clip_rect.y+map->h) ) { Camera.y += 25*sSpeed; } else if( ((*my < (screen->clip_rect.y+15)) || keys[SDLK_UP] ) && ((Camera.y - 25*sSpeed) > map->clip_rect.y) ) { Camera.y -= 25*sSpeed; } // Save the HUD settings if(keys[SDLK_h]) { saveSet(); fprintf(stderr,"HUD saved to hud.txt\n"); } if(HUD.grabPanel == 0) { if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON_LMASK) { selectEnt(*mx, *my); } if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON_RMASK) { if(players[0].sEnt != NULL) orderEnt(*mx, *my); } } // HUD if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON_LMASK) { // ADD Minimap // Infobar i = -1; while(++i<MAX_UNIT_TYPES) { if( !HUD.aUnits[i].draw ) continue; //fprintf(stderr,"%i\n",bCollide(&HUD.aUnits[i],*mx,*my)); if(bCollide(&HUD.aUnits[i],*mx,*my)) { HUD.aUnits[i].action(i); fprintf(stderr,"unit button pressed\n"); break; } } i = -1; while(++i<MAX_STRUCT_TYPES) { if( !HUD.aStructs[i].draw ) continue; if(bCollide(&HUD.aStructs[i],*mx,*my)) { HUD.aStructs[i].action(i); fprintf(stderr,"Structure %i button pressed\n",i); break; } } // Music Player i = -1; while(++i < 4) { if( !HUD.pButtons[i].draw ) continue; if(bCollide(&HUD.pButtons[i],*mx,*my)) { HUD.pButtons[i].action(i); fprintf(stderr,"player button pressed\n"); break; } } } } // menu if(keys[SDLK_ESCAPE]) { HUD.menu = 1; } if(keys[SDLK_SPACE]) { if(HUD.pButtons[0].tip.info == NULL) return; dest.x = HUD.pButtons[0].x + 5; dest.y = HUD.pButtons[0].y - HUD.pButtons[0].tip.bbox->h; dest.w = HUD.pButtons[0].tip.bbox->w; dest.h = HUD.pButtons[0].tip.bbox->h; SDL_BlitSurface(HUD.pButtons[0].tip.bbox, NULL, screen, &dest); } }
/** * Manage the scrollbar up or down. */ static void DlgFileSelect_ManageScrollbar(void) { int b, x, y; int scrollY, scrollYmin, scrollYmax, scrollH_half; float scrollMove; b = SDL_GetMouseState(&x, &y); /* If mouse is down on the scrollbar for the first time */ if (fsdlg[SGFSDLG_SCROLLBAR].state & SG_MOUSEDOWN) { if (mouseClicked == 0) { mouseClicked = 1; mouseIsOut = 0; oldMouseY = y; } } /* Mouse button is up on the scrollbar */ else { mouseClicked = 0; oldMouseY = y; mouseIsOut = 0; } /* If mouse Y position didn't change */ if (oldMouseY == y) return; /* Compute scrollbar ymin and ymax values */ scrollYmin = (fsdlg[SGFSDLG_SCROLLBAR].y + fsdlg[0].y) * sdlgui_fontheight; scrollYmax = (fsdlg[SGFSDLG_DOWN].y + fsdlg[0].y) * sdlgui_fontheight; scrollY = fsdlg[SGFSDLG_SCROLLBAR].y * sdlgui_fontheight + fsdlg[SGFSDLG_SCROLLBAR].h + fsdlg[0].y * sdlgui_fontheight; scrollH_half = scrollY + fsdlg[SGFSDLG_SCROLLBAR].w / 2; scrollMove = (float)(y-oldMouseY)/sdlgui_fontheight; /* Verify if mouse is not above the scrollbar area */ if (y < scrollYmin) { mouseIsOut = SCROLLOUT_ABOVE; oldMouseY = y; return; } if (mouseIsOut == SCROLLOUT_ABOVE && y < scrollH_half) { oldMouseY = y; return; } /* Verify if mouse is not under the scrollbar area */ if (y > scrollYmax) { mouseIsOut = SCROLLOUT_UNDER; oldMouseY = y; return; } if (mouseIsOut == SCROLLOUT_UNDER && y > scrollH_half) { oldMouseY = y; return; } mouseIsOut = 0; scrollbar_Ypos += scrollMove; oldMouseY = y; /* Verifiy if scrollbar is in correct inferior boundary */ if (scrollbar_Ypos < 0) scrollbar_Ypos = 0.0; /* Verifiy if scrollbar is in correct superior boundary */ b = (int) (scrollbar_Ypos * ((float)entries/(float)(SGFS_NUMENTRIES-2)) + 0.5); if (b+SGFS_NUMENTRIES >= entries) { ypos = entries - SGFS_NUMENTRIES; DlgFileSelect_Convert_ypos_to_scrollbar_Ypos(); } refreshentries = true; }
int main(int argc, char *argv[]) { // Affiche sur la console freopen("CON","w",stdout); // Initialisation init(); // Surface -> sert à afficher les différents éléments graphiques du programme SDL_Surface *ecran = NULL, *fondEcran = NULL, *caseGrid = NULL, *caseError = NULL, *caseSelected = NULL, *caseProposed = NULL, *wordsUsedLabel = NULL, *timer = NULL, *scoreLabel = NULL, *triple_word_legend_label = NULL, *double_word_legend_label = NULL, *triple_letter_legend_label = NULL, *double_letter_legend_label = NULL, *timer_icon = NULL, *titre = NULL, *wordLabel = NULL, *double_letter_icon = NULL, *triple_letter_icon = NULL, *double_word_icon = NULL, *triple_word_icon = NULL; SDL_Surface *caracteres[4][4], *points[4][4]; // Rect -> sert au positionnement SDL_Rect r,positionTimerIcon,positionFondEcran,positionTitre,positionWordsUsed,positionDoubleWordIcon,positionDoubleWordLegende,positionDoubleLetterIcon,positionDoubleLetterLegende,positionTripleWordIcon,positionTripleWordLegende,positionTripleLetterIcon,positionTripleLetterLegende,positionTimer,positionScore,positionCaractere,positionPoints,positionWord,positionBonus; // Polices de caractères TTF_Font *police = NULL, *policeCaractere = NULL, *policePoints = NULL, *policeLegende = NULL; // Différentes variables int continuer = 1, isPause = 0, weight, height,i,j,k,l,positionSouris_x,positionSouris_y; int caseChoose_x = -1; int caseChoose_y = -1; int tempsActuel = 0, tempsPrecedent = 0, compteur = 120, scoreValue = 0; // Différents tableaux de caractères pour l'affichage char temps[20] = "", score[20] = "", word[16] = "", legend_triple_word[25] = "Mot x 3", legend_triple_letter[25] = "Lettre x 3", legend_double_word[25] = "Mot x 2", legend_double_letter[25] = "Lettre x 2"; // Couleurs SDL_Color couleurNoire = {0, 0, 0}; SDL_Color couleurBlanche = {255, 255, 255}; SDL_Color couleurViolette = {130, 0, 255}; SDL_Color couleurGrise = {96, 96, 96}; // Evenement pour la détection d'appui sur une touche ou un click de la souris par l'utilisateur SDL_Event event; // Initialisation de la fonction rand() srand(time(NULL)); // Initialisation de la grille char grid[16][2]; //initGrid(grid); initGridFile("Grille.txt",grid); // Recherche des mots possibles à partir de la grille générée aléatoirement initWordsPossibles(); // Affichage sur la console de ces mots displayWordsPossibles(); //Affectation des positions des éléments positionFondEcran.x = 0; positionFondEcran.y = 0; positionWordsUsed.x = 20; positionWordsUsed.y = 15; positionScore.x = 380; positionScore.y = 400; positionTimerIcon.x = 60; positionTimerIcon.y = 392; positionTimer.x = 120; positionTimer.y = 400; positionTitre.x = 215; positionTitre.y = 20; positionWord.x = 220; positionWord.y = 115; positionDoubleLetterIcon.x = 470; positionDoubleLetterIcon.y = 207; positionDoubleLetterLegende.x = 500; positionDoubleLetterLegende.y = 200; positionDoubleWordIcon.x = 470; positionDoubleWordIcon.y = 247; positionDoubleWordLegende.x = 500; positionDoubleWordLegende.y = 240; positionTripleLetterIcon.x = 470; positionTripleLetterIcon.y = 287; positionTripleLetterLegende.x = 500; positionTripleLetterLegende.y = 280; positionTripleWordIcon.x = 470; positionTripleWordIcon.y = 327; positionTripleWordLegende.x = 500; positionTripleWordLegende.y = 320; // Initialisation pour la SDL SDL_Init(SDL_INIT_VIDEO); // Initialisation et affectation pour les polices TTF_Init(); police = TTF_OpenFont("Animal Silence.otf", 40); policeCaractere = TTF_OpenFont("orange juice 2.0.ttf", 36); policePoints = TTF_OpenFont("BADABB__.ttf", 15); policeLegende = TTF_OpenFont("INFECTED.ttf", 25); // Mise dans le tableau des caracteres de la grille les libelles des lettres sorties aléatoirement for(int ligne = 0;ligne < 4;ligne++) { for(int colonne = 0;colonne < 4;colonne++) { const char* lettre = &letters_grid[ligne][colonne].letter.letter_libelle; caracteres[ligne][colonne] = TTF_RenderText_Blended(policeCaractere, lettre , couleurNoire); } } // Mise dans le tableau des points de la grille les points des lettres sorties aléatoirement for(int ligne = 0;ligne < 4;ligne++) { for(int colonne = 0;colonne < 4;colonne++) { const char* pointsValue = letters_grid[ligne][colonne].letter.letter_pointsLabel; points[ligne][colonne] = TTF_RenderText_Blended(policePoints, pointsValue, couleurNoire); } } // Initialisation des textes à afficher wordLabel = TTF_RenderText_Blended(police, word, couleurBlanche); double_letter_legend_label = TTF_RenderText_Blended(policeLegende,legend_double_letter, couleurNoire); triple_letter_legend_label = TTF_RenderText_Blended(policeLegende,legend_triple_letter, couleurNoire); double_word_legend_label = TTF_RenderText_Blended(policeLegende,legend_double_word, couleurNoire); triple_word_legend_label = TTF_RenderText_Blended(policeLegende,legend_triple_word, couleurNoire); sprintf(score, "Score : %d", scoreValue); scoreLabel = TTF_RenderText_Blended(police, score, couleurBlanche); if(compteur%60 < 10) sprintf(temps, "%d : 0%d", compteur/60,compteur%60); /* On écrit dans la chaîne "temps" le nouveau temps */ else sprintf(temps, "%d : %d", compteur/60,compteur%60); timer = TTF_RenderText_Blended(police, temps, couleurBlanche); // Initialisation de l'écran ecran = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF); // Titre de la fenêtre SDL_WM_SetCaption("Ruzzle", NULL); // Initialisation des images timer_icon = IMG_Load("timer.png"); double_letter_icon = IMG_Load("double_letter_icon.png"); triple_letter_icon = IMG_Load("triple_letter_icon.png"); double_word_icon = IMG_Load("double_word_icon.png"); triple_word_icon = IMG_Load("triple_word_icon.png"); titre = IMG_Load("Ruzzle_logo.png"); fondEcran = IMG_Load("FondEcran.jpe"); caseProposed = IMG_Load("caseProposed.png"); caseSelected = IMG_Load("caseSelected.png"); caseError = IMG_Load("caseError.png"); caseGrid = IMG_Load("case.png"); // Initialisation de variables pour l'affichage weight = (ecran->w / 3); height = (ecran->h / 3); // Boucle du programme while(continuer) { if(!isPause) { // Récupération du temps tempsActuel = SDL_GetTicks(); if (tempsActuel - tempsPrecedent >= 1000) /* Si 1 s au moins s'est écoulée */ { compteur -= 1; /* On rajoute 1 au compteur */ if(compteur%60 < 10) sprintf(temps, "%d : 0%d", compteur/60,compteur%60); /* On écrit dans la chaîne "temps" le nouveau temps */ else sprintf(temps, "%d : %d", compteur/60,compteur%60); /* On écrit dans la chaîne "temps" le nouveau temps */ SDL_FreeSurface(timer); /* On supprime la surface précédente */ timer = TTF_RenderText_Blended(police, temps, couleurBlanche); tempsPrecedent = tempsActuel; /* On met à jour le tempsPrecedent */ } if(compteur == 0) /* Si le timer est fini */ continuer = 0; } while(SDL_PollEvent(&event)) /* Détection d'évènements de la part de l'utilisateur */ switch(event.type) { case SDL_QUIT: /* Fermeture de la fenetre */ continuer = 0; break; case SDL_MOUSEBUTTONUP: if(!isPause) { if (event.button.button == SDL_BUTTON_LEFT) { SDL_GetMouseState(&positionSouris_x,&positionSouris_y); for(int ligne = 0;ligne < 4;ligne++) { for(int colonne = 0;colonne < 4;colonne++) { if(positionSouris_x >= (letters_grid[ligne][colonne].position_x + 25) && positionSouris_x <= (letters_grid[ligne][colonne].position_x + 75) && positionSouris_y >= (letters_grid[ligne][colonne].position_y + 25) && positionSouris_y <= (letters_grid[ligne][colonne].position_y + 75) && letters_grid[ligne][colonne].isChoose == 0) { if((caseChoose_x == -1 && caseChoose_y == -1) || (ligne >= (caseChoose_x-1) && ligne <= (caseChoose_x+1) && colonne >= (caseChoose_y-1) && colonne <= (caseChoose_y+1) ) ) { if(strchr(word,' ')) { memset(word, 0, sizeof (word)); } lettersSelectedLength++; strcat(word,&letters_grid[ligne][colonne].letter.letter_libelle); SDL_FreeSurface(wordLabel); /* On supprime la surface précédente */ wordLabel = TTF_RenderText_Blended(police, word, couleurBlanche); letters_grid[ligne][colonne].isChoose = 1; for(int ligne_compteur = 0;ligne_compteur < 4;ligne_compteur++) { for(int colonne_compteur = 0;colonne_compteur < 4;colonne_compteur++) { letters_grid[ligne_compteur][colonne_compteur].isProposed = 0; } } for(int compteur_ligne = (ligne - 1) ; compteur_ligne <= (ligne + 1) ; compteur_ligne++) { for(int compteur_colonne = (colonne - 1) ; compteur_colonne <= (colonne + 1) ; compteur_colonne++) { if(compteur_ligne < 4 && compteur_ligne > -1 && compteur_colonne < 4 && compteur_colonne > -1) letters_grid[compteur_ligne][compteur_colonne].isProposed = 1; } } add_lettersSelected_tab(letters_grid[ligne][colonne]); caseChoose_x = ligne; caseChoose_y = colonne; } } } } break; } if(event.button.button == SDL_BUTTON_RIGHT) { if(wordIsExistBis(lettersSelected_tab) && !wordUsedIsExist()) { add_wordsUsed_tab(word); numberWordsFind++; scoreValue += calcul_score_word(); sprintf(score, "Score : %d", scoreValue); SDL_FreeSurface(scoreLabel); /* On supprime la surface précédente */ scoreLabel = TTF_RenderText_Blended(police, score, couleurBlanche); sprintf(word, "+ %d points",calcul_score_word()); } else { if(wordUsedIsExist() == 1) { strcpy(word,"Mot deja utilise"); } else { strcpy(word,"Mot Incorrect !"); } } for(int ligne_compteur = 0;ligne_compteur < 4;ligne_compteur++) { for(int colonne_compteur = 0;colonne_compteur < 4;colonne_compteur++) { letters_grid[ligne_compteur][colonne_compteur].isProposed = 0; } } caseChoose_x = -1; caseChoose_y = -1; lettersSelectedLength = 0; SDL_FreeSurface(wordLabel); /* On supprime la surface précédente */ wordLabel = TTF_RenderText_Blended(police, word, couleurBlanche); reset_lettersSelected_tab(); reset_lettersGrid(); } } case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_p: if(isPause == 0) isPause = 1; else { isPause = 0; } break; } break; } SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 130, 0, 255)); SDL_BlitSurface(fondEcran, NULL, ecran, &positionFondEcran); for(k=0,i=0;i<ecran->w;i+=height,k++) { r.y = i/3 + 140; for(j=0,l=0;j<(ecran->h*1.5);j+=weight,l++) { r.x = j/4 + 195; if(letters_grid[k][l].isChoose==1) { SDL_BlitSurface(caseSelected, NULL, ecran,&r); } else { if(letters_grid[k][l].isProposed==1) { SDL_BlitSurface(caseProposed, NULL, ecran,&r); } else { SDL_BlitSurface(caseGrid, NULL, ecran,&r); } } positionCaractere = r; if(letters_grid[k][l].letter.letter_alphabetOrder == 2 || letters_grid[k][l].letter.letter_alphabetOrder == 4 || letters_grid[k][l].letter.letter_alphabetOrder == 5 || letters_grid[k][l].letter.letter_alphabetOrder == 6 || letters_grid[k][l].letter.letter_alphabetOrder == 8 || letters_grid[k][l].letter.letter_alphabetOrder == 11 || letters_grid[k][l].letter.letter_alphabetOrder == 12 || letters_grid[k][l].letter.letter_alphabetOrder == 14 || letters_grid[k][l].letter.letter_alphabetOrder == 16 || letters_grid[k][l].letter.letter_alphabetOrder == 18 || letters_grid[k][l].letter.letter_alphabetOrder == 19) { positionCaractere.x += 39; positionCaractere.y += 38; } else if(letters_grid[k][l].letter.letter_alphabetOrder == 9) { positionCaractere.x += 42; positionCaractere.y += 38; } else if(letters_grid[k][l].letter.letter_alphabetOrder == 23) { positionCaractere.x += 31; positionCaractere.y += 40; } else { positionCaractere.x += 36; positionCaractere.y += 38; } letters_grid[k][l].position_x = r.x; letters_grid[k][l].position_y = r.y; SDL_BlitSurface(caracteres[k][l], NULL, ecran, &positionCaractere); /* Blit du texte */ if(letters_grid[k][l].letter.letter_points == 10) positionPoints.x = letters_grid[k][l].position_x + 58; else positionPoints.x = letters_grid[k][l].position_x + 61; positionPoints.y = letters_grid[k][l].position_y + 28; SDL_BlitSurface(points[k][l], NULL, ecran, &positionPoints); /* Blit des points */ if(letters_grid[k][l].letter_bonus == DOUBLE_LETTER) { positionBonus.x = letters_grid[k][l].position_x + 23; positionBonus.y = letters_grid[k][l].position_y + 20; SDL_BlitSurface(double_letter_icon, NULL, ecran, &positionBonus); } if(letters_grid[k][l].letter_bonus == DOUBLE_WORD) { positionBonus.x = letters_grid[k][l].position_x + 23; positionBonus.y = letters_grid[k][l].position_y + 20; SDL_BlitSurface(double_word_icon, NULL, ecran, &positionBonus); } if(letters_grid[k][l].letter_bonus == TRIPLE_LETTER) { positionBonus.x = letters_grid[k][l].position_x + 23; positionBonus.y = letters_grid[k][l].position_y + 20; SDL_BlitSurface(triple_letter_icon, NULL, ecran, &positionBonus); } if(letters_grid[k][l].letter_bonus == TRIPLE_WORD) { positionBonus.x = letters_grid[k][l].position_x + 23; positionBonus.y = letters_grid[k][l].position_y + 20; SDL_BlitSurface(triple_word_icon, NULL, ecran, &positionBonus); } } } for(int indexWord = 0; indexWord < numberWordsFind ; indexWord++,positionWordsUsed.y+=15) { if(indexWord/25 == 0) { positionWordsUsed.x = 20; wordsUsedLabel = TTF_RenderText_Blended(policePoints, wordsUsed_tab[indexWord], couleurBlanche); SDL_BlitSurface(wordsUsedLabel, NULL, ecran, &positionWordsUsed); } else { if(indexWord == 25) { positionWordsUsed.y = 15; positionWordsUsed.x = 120; } wordsUsedLabel = TTF_RenderText_Blended(policePoints, wordsUsed_tab[indexWord], couleurBlanche); SDL_BlitSurface(wordsUsedLabel, NULL, ecran, &positionWordsUsed); } } positionWordsUsed.y = 15; SDL_BlitSurface(timer_icon, NULL, ecran, &positionTimerIcon); SDL_BlitSurface(wordLabel, NULL, ecran, &positionWord); SDL_BlitSurface(titre, NULL, ecran, &positionTitre); SDL_BlitSurface(timer, NULL, ecran, &positionTimer); SDL_BlitSurface(scoreLabel, NULL, ecran, &positionScore); SDL_BlitSurface(double_letter_icon, NULL, ecran, &positionDoubleLetterIcon); SDL_BlitSurface(double_letter_legend_label, NULL, ecran, &positionDoubleLetterLegende); SDL_BlitSurface(double_word_icon, NULL, ecran, &positionDoubleWordIcon); SDL_BlitSurface(double_word_legend_label, NULL, ecran, &positionDoubleWordLegende); SDL_BlitSurface(triple_letter_icon, NULL, ecran, &positionTripleLetterIcon); SDL_BlitSurface(triple_letter_legend_label, NULL, ecran, &positionTripleLetterLegende); SDL_BlitSurface(triple_word_icon, NULL, ecran, &positionTripleWordIcon); SDL_BlitSurface(triple_word_legend_label, NULL, ecran, &positionTripleWordLegende); SDL_Flip(ecran); // Mise à jour de l'écran } SDL_FreeSurface(timer); SDL_FreeSurface(scoreLabel); SDL_FreeSurface(titre); SDL_FreeSurface(ecran); TTF_Quit(); SDL_Quit(); return EXIT_SUCCESS; }
void WorldInputCmdProcessor::updateScrollStatus(const iXY &mouse_pos) { double time_slice; long scroll_increment; float scroll_rate; time_slice = TimerInterface::getTimeSlice(); scroll_rate = gameconfig->scrollrate; scroll_increment = (long) (scroll_rate * time_slice); if(right_mouse_scroll) { int x,y; int buttons=SDL_GetMouseState(&x,&y); if(!(buttons&SDL_BUTTON(SDL_BUTTON_RIGHT))) { // sometimes the winning page or something comes up // as you're holding down the right mouse button // and the UP message doesn't come through right_mouse_scroll=false; } else if(mouse_pos.x!=right_mouse_scroll_pos.x || mouse_pos.y!=right_mouse_scroll_pos.y) { // we're holding down the right mouse button, and mouse has moved int x_move=mouse_pos.x-right_mouse_scroll_pos.x; int y_move=mouse_pos.y-right_mouse_scroll_pos.y; SDL_WarpMouse(right_mouse_scroll_pos.x,right_mouse_scroll_pos.y); WorldViewInterface::scroll_right(x_move*4); WorldViewInterface::scroll_down(y_move*4); right_mouse_scrolled_pos.x+=x_move; right_mouse_scrolled_pos.y+=y_move; right_mouse_scroll_moved = true; } return; } if ( GameConfig::video_fullscreen != true ) { // don't do border scrolling on windowed mode because // the window isn't always on the edge of the screen. return; } if((unsigned int)mouse_pos.x >= (screen->getWidth() - 1)) { WorldViewInterface::scroll_right(scroll_increment); } if( mouse_pos.x < 1) { WorldViewInterface::scroll_left(scroll_increment); } if( (unsigned int)mouse_pos.y >= (screen->getHeight() - 1)) { WorldViewInterface::scroll_down(scroll_increment); } if( mouse_pos.y < 1) { WorldViewInterface::scroll_up(scroll_increment); } }