int main() { Wingman3D joystick(0); if( !joystick.isStatusOk() ) { fprintf(stderr, "%s\n", joystick.getStatusMessage()); return EXIT_FAILURE; } sleep(1); joystick.printDeviceInfo(3); while(1) { fprintf(stdout, "\nx: %03d y: %03d z: %03d slide: %03d hat: %03d buttons: ", joystick.getX(), joystick.getY(), joystick.getTwist(), joystick.getSliderValue(), joystick.getHatSwitchStatus()); for(int i = 1; i < joystick.getNumButtons(); i++) if( joystick.isButtonPressed(i) ) fprintf(stdout, "%01d ", i); if( !joystick.isStatusOk() ) return -1; } return EXIT_SUCCESS; }
std::vector<JoystickDescription> Joystick::get_joysticks() { std::vector<JoystickDescription> joysticks; for(int i = 0; i < 32; ++i) { try { std::ostringstream str; str << "/dev/input/js" << i; Joystick joystick(str.str()); joysticks.push_back(JoystickDescription(joystick.get_filename(), joystick.get_name(), joystick.get_axis_count(), joystick.get_button_count())); } catch(std::exception& err) { // ok } } return joysticks; }
void LLFloaterJoystick::draw() { bool joystick_inited = LLViewerJoystick::getInstance()->isJoystickInitialized(); childSetEnabled("enable_joystick", joystick_inited); childSetEnabled("joystick_type", joystick_inited); std::string desc = LLViewerJoystick::getInstance()->getDescription(); if (desc.empty()) desc = getString("NoDevice"); childSetText("joystick_type", desc); LLViewerJoystick* joystick(LLViewerJoystick::getInstance()); for (U32 i = 0; i < 6; i++) { F32 value = joystick->getJoystickAxis(i); mAxisStats[i]->addValue(value * gFrameIntervalSeconds); if (mAxisStatsBar[i]->mMinBar > value) { mAxisStatsBar[i]->mMinBar = value; } if (mAxisStatsBar[i]->mMaxBar < value) { mAxisStatsBar[i]->mMaxBar = value; } } LLFloater::draw(); }
int main () { Joystick joystick(1); while (true) { // Restrict rate usleep(1000); // Attempt to sample an event from the joystick JoystickEvent event; if (joystick.sample(&event)) { if (event.isButton()) { printf("Button %u is %s\n", event.number, event.value == 0 ? "up" : "down"); } else if (event.isAxis()) { printf("Axis %u is at position %d\n", event.number, event.value); } } } return 0; }
void LLFloaterJoystick::draw() { bool joystick_inited = LLViewerJoystick::getInstance()->isJoystickInitialized(); childSetEnabled("enable_joystick", joystick_inited); childSetEnabled("joystick_type", joystick_inited); std::string desc = LLViewerJoystick::getInstance()->getDescription(); if (desc.empty()) desc = getString("NoDevice"); childSetText("joystick_type", desc); LLViewerJoystick* joystick(LLViewerJoystick::getInstance()); for (U32 i = 0; i < 6; i++) { F32 value = joystick->getJoystickAxis(i); mAxisStats[i]->addValue(value * gFrameIntervalSeconds); if (mAxisStatsBar[i]) { F32 minbar, maxbar; mAxisStatsBar[i]->getRange(minbar, maxbar); if (llabs(value) > maxbar) { F32 range = llabs(value); mAxisStatsBar[i]->setRange(-range, range, range * 0.25f, range * 0.5f); } } } LLFloater::draw(); }
void OnJoyMotion(int inDeviceId, int inAxis, float inValue) { Event joystick(etJoyAxisMove); joystick.id = inDeviceId; joystick.code = inAxis; joystick.value = inValue; HandleEvent(joystick); }
void OnJoy(int inDeviceId, int inCode, bool inDown) { //__android_log_print(ANDROID_LOG_INFO, "NME", "OnJoy %d %d %d", inDeviceId, inCode, inDown); Event joystick( inDown ? etJoyButtonDown : etJoyButtonUp ); joystick.id = inDeviceId; joystick.code = inCode; HandleEvent(joystick); }
int main(int argc, char* argv[]) { MJoystickLinux joystick(JOY1_DEV); while(1) { joystick.updateData(); printf("Axis x = %f\n", joystick.getDeltaAxis(0)); fflush(stdout); } }
void LLViewerJoystick::HotPlugRemovalCallback(NDOF_Device *dev) { LLViewerJoystick* joystick(LLViewerJoystick::getInstance()); if (joystick->mNdofDev == dev) { llinfos << "HotPlugRemovalCallback: joystick->mNdofDev=" << joystick->mNdofDev << "; removed device:" << llendl; ndof_dump(dev); joystick->mDriverState = JDS_UNINITIALIZED; } joystick->updateEnabled(true); }
void vsyncarch_presync(void) { #if defined(HAVE_MOUSE) && !defined(MACOSX_COCOA) { extern void x11_lightpen_update(void); x11_lightpen_update(); } #endif /* HAVE_MOUSE !MACOSX_COCOA */ kbdbuf_flush(); #ifdef HAS_JOYSTICK joystick(); #endif }
int main(int argc, char** argv) { for(int i = 1; i < argc; ++i) { Joystick joystick(argv[i]); std::cout << "Filename: '" << joystick.get_filename() << "'\n"; std::cout << "Name: '" << joystick.get_name() << "'\n"; std::cout << "Axis: " << joystick.get_axis_count() << "\n"; std::cout << "Button: " << joystick.get_button_count() << "\n"; std::cout << "Evdev: '" << joystick.get_evdev() << "'\n"; } return 0; }
task main() { HolonomicBase holo; TVexJoysticks JoyChDriveX = ChJoyLX; TVexJoysticks JoyChDriveY = ChJoyLY; TVexJoysticks JoyChDriveR = ChJoyRX; tMotor ports[] = { mpDriveA, mpDriveB, mpDriveC }; InitHolonomicBase(holo, ports, 3); while(true){ // First obtain the joystick components: X, Y, and R float driveY = joystick(JoyChDriveY); float driveX = joystick(JoyChDriveX); float driveRotation = -joystick(JoyChDriveR); // Negative of the the rotational joystick because leftward rotation // is actually positive rotation about the vertical axis. setDriveXYR(holo, driveX, driveY, driveRotation); } }
NDOF_HotPlugResult LLViewerJoystick::HotPlugAddCallback(NDOF_Device *dev) { NDOF_HotPlugResult res = NDOF_DISCARD_HOTPLUGGED; LLViewerJoystick* joystick(LLViewerJoystick::getInstance()); if (joystick->mDriverState == JDS_UNINITIALIZED) { llinfos << "HotPlugAddCallback: will use device:" << llendl; ndof_dump(dev); joystick->mNdofDev = dev; joystick->mDriverState = JDS_INITIALIZED; res = NDOF_KEEP_HOTPLUGGED; } joystick->updateEnabled(true); return res; }
void main(void) { static u8 i,joy,joyprev,image; image=0; joyprev=0; show_picture(image,0,1); while(1) { i=joystick(); joy=i^joyprev&i; joyprev=i; if(joy&JOY_LEFT) { --image; if(image>4) image=4; show_picture(image,0,1); } if(joy&JOY_RIGHT) { ++image; if(image>4) image=0; show_picture(image,1,1); } if(joy&JOY_UP) { --image; if(image>4) image=4; show_picture(image,0,0); } if(joy&JOY_DOWN) { ++image; if(image>4) image=0; show_picture(image,0,0); } } }
int main() { t_variable var; init_var(&var, laby); trace(&var); mlx_expose_hook(var.win_ptr, refresh, &var); mlx_hook(var.win_ptr, KeyPress, KeyPressMask, key, &var); mlx_hook(var.win_ptr, ButtonPress, ButtonPressMask, gun, &var); mlx_hook(var.win_ptr, MotionNotify, PointerMotionMask, mouse, &var); if (var.fd != -1) joystick(&var); else mlx_loop(var.mlx_ptr); return (0); }
void LLFloaterJoystick::onCommitJoystickEnabled(LLUICtrl*, void *joy_panel) { LLFloaterJoystick* self = (LLFloaterJoystick*)joy_panel; BOOL joystick_enabled = self->mCheckJoystickEnabled->get(); BOOL flycam_enabled = self->mCheckFlycamEnabled->get(); if (!joystick_enabled || !flycam_enabled) { // Turn off flycam LLViewerJoystick* joystick(LLViewerJoystick::getInstance()); if (joystick->getOverrideCamera()) { joystick->toggleFlycam(); } } }
void vsyncarch_presync(void) { #if defined(GP2X) || defined(WIZ) (*ui_dispatch_hook)(); #endif #if defined(HAVE_MOUSE) && !defined(GP2X) && !defined(WIZ) && !defined(MACOSX_COCOA) { extern void x11_lightpen_update(void); x11_lightpen_update(); } #endif /* HAVE_MOUSE !GP2X !WIZ !MACOSX_COCOA */ kbdbuf_flush(); #ifdef HAS_JOYSTICK joystick(); #endif }
GameLoop::GameLoop() : m_input_devices(), m_screen_factory(), m_screen(nullptr) { const Configuration& configuration = *the_context.configuration; if(NetworkMode::SERVER == configuration.network_mode || NetworkMode::WITH_SERVER == configuration.network_mode) { auto server_backend = std::make_unique<ENetServer>(configuration.port); auto server_impl = std::make_unique<BasicServer>(std::move(server_backend)); m_server.reset(new ServerThread(std::move(server_impl))); m_screen_factory.set_server(m_server.get()); } // configure player control if(configuration.player_number.has_value()) { const int player_number = *configuration.player_number; if(2 <= player_number) { throw GameException("Cannot control player " + std::to_string(player_number) + ". More than two players are currently not yet supported."); } m_input_devices.set_player_number(player_number); } // attach joystick input if(configuration.joystick_number.has_value()) { const int joystick_number = *configuration.joystick_number; const int joysticks_count = SDL_NumJoysticks(); if(joystick_number < 0 || joystick_number >= joysticks_count) { throw GameException("Joystick " + std::to_string(joystick_number) + " not found. There are " + std::to_string(joysticks_count) + " joysticks."); } JoystickPtr joystick(SDL_JoystickOpen(joystick_number)); sdlok(joystick.get()); m_input_devices.set_joystick(std::move(joystick)); } next_screen(); }
static void checkover() { for ( int y = 0; y < ARENA_H; y++ ) { for ( int x = 0; x < ARENA_W - 1; x++ ) { if ( arena[y][x] && ( arena[y][x] == arena[y][x+1] || arena[y][x] == arena[y+1][x] ) ) { return; } } } playing = 0; gotoxy(X_OFFSET + (ARENA_W / 2) - 4, Y_OFFSET + (ARENA_H / 2)); cputs("GAME OVER!!"); #ifdef JOYSTICK_NUM while ( joystick(JOYSTICK_NUM) == 0 ) #else while ( getk() == 0 ) #endif ; }
int main( int argc, char* argv[] ) { frc::Joystick joystick(0); if (joystick.isConnected() == false) { std::cerr << "Error: could not connect to joystick." << std::endl; return 1; } std::cout << "Info: Beginning joystick test." << std::endl; std::cout << "Move joystick up to continue." << std::endl; while (joystick.GetY() <= 0.9); std::cout << "Move joystick right to continue." << std::endl; while (joystick.GetX() <= 0.9); std::cout << "Move joystick down to continue." << std::endl; while (joystick.GetY() >= -0.9); std::cout << "Move joystick left to continue." << std::endl; while (joystick.GetX() >= -0.9); std::cout << "Found " << joystick.GetButtonCount() << " buttons." << std::endl; for (size_t buttonIdx = 0; buttonIdx < joystick.GetButtonCount(); ++buttonIdx) { std::cout << "Push joystick button " << buttonIdx << std::endl; while (joystick.GetRawButton(buttonIdx) == false); } std::cout << "Info: joystick test successful." << std::endl; return 0; }
int main() { while(true) { auto joysticks=msl::joystick_t::list(); size_t joystick_number=0; if(joysticks.size()<=joystick_number) { std::cout<<"joystick "<<joystick_number<<" does not exist"<<std::endl; } else { msl::joystick_t joystick(joysticks[joystick_number]); joystick.open(); if(!joystick.good()) { std::cout<<"could not open joystick "<<joystick_number<<std::endl; } else { std::cout<<"using joystick number "<<joystick_number<<" with "<<joystick.axis_count()<< " axes and "<<joystick.button_count()<<" buttons"<<std::endl; } while(joystick.good()) { for(size_t ii=0;ii<4;++ii) std::cout<<std::setw(16)<<joystick.axis(ii); std::cout<<std::endl; } } msl::delay_ms(100); } return 0; }
//----------------------------------------------------------------------------------------------- bool InputHandler::ProcessJoystick(Vector2f& out_Direction, float& magnitude, uint playerIndex, uint requestedJoystick) { Vector2f joystick(0.f,0.f); _XINPUT_GAMEPAD state = InputHandler::m_currentGamePadState[playerIndex].Gamepad; if(requestedJoystick == XINPUT_GAMEPAD_LEFT_JOY) { joystick.x = (float)state.sThumbLX; joystick.y = (float)state.sThumbLY; } else if(requestedJoystick == XINPUT_GAMEPAD_RIGHT_JOY) { joystick.x = (float)state.sThumbRX; joystick.y = (float)state.sThumbRY; } else { return false; } NormalizeThumbStick(joystick); float radius = (float)sqrt(joystick.x * joystick.x + joystick.y * joystick.y); if(radius > DEAD_ZONE_RADIUS) { radius = (radius - DEAD_ZONE_RADIUS) * ONE_MINUS_DEAD_ZONE_RADIUS_INVERSE; magnitude = radius; out_Direction = joystick; return true; } else { magnitude = 0.f; out_Direction = Vector2f(0,0); return false; } }
static void handle_keys() { #ifdef JOYSTICK_NUM uint8_t joy = joystick(JOYSTICK_NUM); #else uint8_t joy = readkeys(); #endif if ( joy & MOVE_LEFT ) { if ( cx > 0 ) { --cx; moved(); } } else if ( joy & MOVE_RIGHT ) { if ( cx < ARENA_W - 1 ) { ++cx; moved(); } } else if ( joy & MOVE_DOWN ) { if ( cy < ARENA_H - 1 ) { ++cy; moved(); } } else if ( joy & MOVE_UP ) { if ( cy > 0 ) { --cy; moved(); } } else if ( joy & MOVE_FIRE ) { if ( selected > 1 ) { score += (selected -2 ) * (selected -2); crunchy(); crunchx(); moved(); checkover(); } } }
int main(){ initArduino(); while (1) { if (joystick() != 0) { if(joy0.hat==0){ //send a character to be read by Arduino program arduinoWrite('1'); //arduinoWrite(armArduinoHandle, '0'); } else if(joy0.hat==90) { arduinoWrite('2'); //arduinoWrite(armArduinoHandle, '0'); } else if(joy0.hat==180) { arduinoWrite('3'); //arduinoWrite(armArduinoHandle, '0'); } else if(joy0.hat==270) { arduinoWrite('4'); //arduinoWrite(armArduinoHandle, '0'); } else if(joy0.buttons& A_BTN) { arduinoWrite('5'); //arduinoWrite(armArduinoHandle, '5'); } else if(joy0.buttons& B_BTN) { arduinoWrite('6'); //arduinoWrite(armArduinoHandle, '6'); } else if(joy0.buttons& X_BTN) { arduinoWrite('7'); //arduinoWrite(armArduinoHandle, '0'); } else if(joy0.buttons& Y_BTN) { arduinoWrite('8'); // arduinoWrite(armArduinoHandle, '0'); } else { arduinoWrite('0'); //arduinoWrite(armArduinoHandle, '0'); } } } return 0; }
int main(int argc, char** argv) { LoadConfigFile(); initHMD(); glfwSetErrorCallback(ErrorCallback); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);// : GLFW_OPENGL_COMPAT_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif const std::string windowName = "RiftRay v" + std::string(pRiftRayVersion); GLFWwindow* l_Window = glfwCreateWindow(g_mirrorWindowSz.x, g_mirrorWindowSz.y, windowName.c_str(), NULL, NULL); if (!l_Window) { LOG_ERROR("Glfw failed to create a window. Exiting."); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(l_Window); glfwSetKeyCallback(l_Window, keyboard); glfwSetMouseButtonCallback(l_Window, mouseDown); glfwSetCursorPosCallback(l_Window, mouseMove); glfwSetScrollCallback(l_Window, mouseWheel); glfwSetWindowSizeCallback(l_Window, resize); glfwSetInputMode(l_Window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); g_pMirrorWindow = l_Window; memset(m_keyStates, 0, GLFW_KEY_LAST*sizeof(int)); FindPreferredJoystick(); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { LOG_INFO("glewInit() error."); exit(EXIT_FAILURE); } #ifdef _DEBUG // Debug callback initialization // Must be done *after* glew initialization. glDebugMessageCallback(myCallback, NULL); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0, GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Start debugging"); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif #ifdef USE_ANTTWEAKBAR TwInit(TW_OPENGL_CORE, NULL); initAnt(); #endif g_pScene = &g_gallery;// new ShaderGalleryScene(); if (g_pScene != NULL) { g_pScene->initGL(); } g_gallery.SetHmdPositionPointer(&m_hmdRo); g_gallery.SetHmdDirectionPointer(&m_hmdRd); g_gallery.SetChassisPosPointer(&m_chassisPos); g_gallery.SetChassisYawPointer(&m_chassisYaw); g_gallery.SetHeadSizePointer(&m_headSize); initVR(); StartShaderLoad(); glfwSwapInterval(0); while (!glfwWindowShouldClose(l_Window)) { glfwPollEvents(); joystick(); timestep(); #ifdef USE_ANTTWEAKBAR TwRefreshBar(g_pMainTweakbar); TwRefreshBar(g_pShaderTweakbar); #endif g_gallery.RenderPrePass(); displayHMD(); glfwSwapBuffers(l_Window); } exitVR(); g_pScene->exitGL(); glfwDestroyWindow(l_Window); glfwTerminate(); exit(EXIT_SUCCESS); }
// The Window Procedure LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; unsigned int x,y; unsigned char kb_char; kb_char=(unsigned char)wParam; static unsigned char OEMscan=0; static char ascii=0; static RECT ClientSize; static unsigned long Width,Height; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: // Added for Dynamic menu system if ( (wmId >=ID_SDYNAMENU) & (wmId <=ID_EDYNAMENU) ) { DynamicMenuActivated (wmId - ID_SDYNAMENU); //Calls to the loaded DLL so it can do the right thing break; } switch (wmId) { case IDM_HELP_ABOUT: DialogBox(EmuState.WindowInstance, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case ID_CONFIGURE_OPTIONS: if (EmuState.ConfigDialog==NULL) { EmuState.ConfigDialog = CreateDialog (NULL,(LPCTSTR)IDD_TCONFIG,EmuState.WindowHandle,(DLGPROC) Config) ; ShowWindow (EmuState.ConfigDialog, SW_SHOWNORMAL) ; } // DialogBox(EmuState.WindowInstance, (LPCTSTR)IDD_TCONFIG, hWnd, (DLGPROC)Config); break; case IDOK: SendMessage (hWnd, WM_CLOSE, 0, 0); break; case ID_FILE_EXIT: BinaryRunning=0; break; case ID_FILE_RESET: if (EmuState.EmulationRunning) EmuState.ResetPending=2; break; case ID_FILE_RUN: EmuState.EmulationRunning=TRUE; InvalidateBoarder(); break; case ID_FILE_RESET_SFT: if (EmuState.EmulationRunning) EmuState.ResetPending=1; break; case ID_FILE_LOAD: LoadIniFile(); EmuState.ResetPending=2; SetClockSpeed(1); //Default clock speed .89 MHZ break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; // case WM_CREATE: // // break; // case WM_SETFOCUS: // Set8BitPalette(); // break; case WM_CLOSE: BinaryRunning=0; break; case WM_CHAR: // OEMscan=(unsigned char)((lParam & 0xFF0000)>>16); // ascii=kb_char; // sprintf(ttbuff,"Getting REAL CHAR %i",ascii); // WriteLine ( ttbuff); // KeyboardEvent(kb_char,OEMscan,1); //Capture ascii value for scancode return 0; break; case WM_KEYUP: case WM_SYSKEYUP: OEMscan=(unsigned char)((lParam & 0xFF0000)>>16); KeyboardEvent(kb_char,OEMscan,0); return 0; break; case WM_KEYDOWN: case WM_SYSKEYDOWN: OEMscan=(unsigned char)((lParam & 0xFF0000)>>16); switch (OEMscan) { case 61: //F3 break; case 62: //F4 break; case 63: //F5 if (EmuState.EmulationRunning) EmuState.ResetPending=1; break; case 64: //F6 SetMonitorType(!SetMonitorType(QUERY)); break; // case 65: //F7 // SetArtifacts(!SetArtifacts(QUERY)); // break; case 66: //F8 SetSpeedThrottle(!SetSpeedThrottle(QUERY)); break; case 67: //F9 EmuState.EmulationRunning=!EmuState.EmulationRunning; if (EmuState.EmulationRunning) EmuState.ResetPending=2; else SetStatusBarText("",&EmuState); break; case 68: //F10 SetInfoBand(!SetInfoBand(QUERY)); InvalidateBoarder(); break; case 87: //F11 if (FlagEmuStop==TH_RUNNING) { FlagEmuStop=TH_REQWAIT; EmuState.FullScreen=!EmuState.FullScreen; } break; // case 88: //F12 // CpuDump(); // break; default: if (EmuState.EmulationRunning) KeyboardEvent(kb_char,OEMscan,2); break; } return 0; break; case WM_LBUTTONDOWN: //0 = Left 1=right SetButtonStatus(0,1); break; case WM_LBUTTONUP: SetButtonStatus(0,0); break; case WM_RBUTTONDOWN: SetButtonStatus(1,1); break; case WM_RBUTTONUP: SetButtonStatus(1,0); break; case WM_MOUSEMOVE: if (EmuState.EmulationRunning) { x = LOWORD( lParam ) ; y = HIWORD( lParam ) ; GetClientRect(EmuState.WindowHandle,&ClientSize); x/=((ClientSize.right-ClientSize.left)>>6); y/=(((ClientSize.bottom-ClientSize.top)-20)>>6); joystick(x,y); } return(0); break; // default: // return DefWindowProc(hWnd, message, wParam, lParam); }
void cbzone_main( int argc, const char* const argv[]) { #ifdef DEVELOPER int passes = 0; struct timeval game_start; struct timeval game_end; #endif //DEVELOPER gprinqconfig(&argc, argv); limit = opt->delay * 1.2e4; /* now that we have parsed the options, we know how large to */ /* make the world. Use calloc here as most of the array */ /* should start off 0. */ pl = o = (Genericp) calloc(opt->mobjects,sizeof(Generic)); if (o == NULL) { printf("Malloc failed...trying to create too many objects?\n"); #ifdef WIN32 return; #else //X11 myexit(1); #endif } initarray(o); /* prepare the main array */ srandom(time((long *) 0)); /* start things off randomly */ screeninit(); updatedisplay(missilerun, lander, score, opt->numleft, sens, False); xhairs(aligned); gprinqcursor((Position_t *)position); event = gprcondeventwait(&key, (Position_t *)position); joystick(position, sens, pl); /* place the objects out there to start the game. if the player is */ /* is_new, then the objects are placed at a random distance, else */ /* the objects get placed on the horizon. */ placeobjects(o, missilerun, score); pl->attr &= ~IS_NEW; /* now the objects can be */ /* placed at the horizon. */ /* now calculate ranges to all the objects and translate them */ /* into a player-centric coordinate system */ pl->ca = cos(pl->azm); pl->sa = sin(pl->azm); for (g=o+opt->estart; g<o+opt->mobjects; g++) if (g->attr & IS_ALIVE) { dx = g->x - pl->x; dy = g->y - pl->y; g->range = sqrt(dx*dx + dy*dy); g->proy = -dx * pl->sa + dy * pl->ca; g->prox = dx * pl->ca + dy * pl->sa; } scanner(o); drawhorizon(pl->azm); /* now the work really starts....we just iterate through */ /* the following loop until the player dies or quits */ #ifdef DEVELOPER gettimeofday(&game_start, 0); #endif }
void cbzone_while(void) { #ifdef WIN32 if (GetAsyncKeyState( VK_F1 ) < 0) { free(o); return; // myexit(scores(score)); //HACK OUT by Eric Fogelin } #endif gettimeofday(&tstart, 0); gprinqcursor((Position_t *)position); event = gprcondeventwait(&key, (Position_t *)position); if (event && key == 'Q') { free(o); return; // myexit(scores(score)); //HACK OUT by Eric Fogelin } if (event && key == 'R') { clearentirescreen(); staticscreen(); updatedisplay(False, False, -1, 0, False, True); updatedisplay(missilerun, lander, score, opt->numleft, sens, False); if (sight_flag) message(1, False); if (pl->attr & IS_BLOCKED) message(2, False); if (salvo_flag) message(3, False); scanner(o); xhairs(aligned); drawhorizon(pl->azm); } joystick(position, sens, pl); if (!paused) { for (i=0; i<opt->msalvos; i++) { /* now find a shot we can use */ s = pl->salvo+i; if (!(s->attr & STILL_THERE)) break; s = NULL; } if (event && pl->attr & IS_ALIVE) if (keylast) { for (i=0; i<opt->msalvos; i++) { /* now find a shot we can use */ s = pl->salvo+i; if (!(s->attr & STILL_THERE)) break; s = NULL; } if (key == 'a' && s!=NULL) { /* fire up one shot */ playsound(opt->loud?sfire:suser_shoots); s->attr = START_LIVING; s->ecount = 0; s->x = pl->x; s->y = pl->y; s->z = 0.0; s->prox = 0; s->proy = 0; s->azm = pl->azm; s->speed = 40.0; keylast = False; } else if (key == 'b') { /* center our joystick */ position[0] = 500; position[1] = 355; gprsetcursorposition((Position_t *)position); joystick(position, sens, pl); keylast = False; } else if (key == 'c') { /* toggle sensitivity */ sens = !sens; joystick(position, sens, pl); keylast = False; } } else if (key == 'A' || key == 'B' || key == 'C') keylast = True; /* button released */ /* if we can move, update our rotation, bearing (azimuth), and */ /* position. */ if (pl->attr & IS_ALIVE && !(pl->attr & IS_BLOCKED)) { pl->azm += pl->rotate; if (pl->azm > PI2) pl->azm -= PI2; if (pl->azm <= 0.0) pl->azm += PI2; pl->ca = cos(pl->azm); pl->sa = sin(pl->azm); } if (pl->attr & IS_ALIVE) { pl->x -= pl->sa * pl->speed; pl->y += pl->ca * pl->speed; } else pl->speed = 0.0; /* now call the move generation routines for the objects */ /* which require thought, speed and/or rotation may be */ /* affected. */ for (g=o+opt->estart; g<o+opt->sstart; g++) if (g->attr & IS_ALIVE) switch (g->type) { case IS_TANK: movetank(g, pl); break; case IS_SUPER: movesuper(g, pl); break; case IS_MISSILE: movemissile(g, pl, first); break; case IS_COPTER: movecopter(g, pl); break; case IS_LANDER: movelander(g, pl); break; default: printf("Help! Something's alive and I don't know what...\n"); #ifdef WIN32 return; #else //X11 myexit(1); #endif } /* now update their bearing and position */ for (g=o+opt->estart; g<o+opt->lstart; g++) { if (g->attr & IS_ALIVE && !(g->attr & IS_BLOCKED)) g->azm += g->rotate; g->ca = cos(g->azm); g->sa = sin(g->azm); g->x -= g->sa * g->speed; g->y += g->ca * g->speed; } for (g=o+opt->lstart; g<o+opt->bstart; g++) if (g->attr & IS_ALIVE) { g->ca = cos(g->azm); g->sa = sin(g->azm); g->x -= g->sa * g->speed; g->y += g->ca * g->speed; } /* now compute ranges from objects to the player */ for (g=o+opt->estart; g<o+opt->mobjects; g++) if (g->attr & STILL_THERE) g->range = sqrt(DIST(g, pl)); for (g=o; g<o+opt->lstart; g++) /* assume all objects are */ g->attr &= ~IS_BLOCKED; /* unblocked */ /* now check to see if they really were unblocked. If not, then */ /* project them back along their path until they are. This */ /* section just checks for being blocked by blocks. */ for (g=o+opt->bstart; g<o+opt->mobjects; g++) { if (g->range < blocksize) { pl->attr |= BLOCKED_BY_BLOCK; dx = pl->x - g->x; dy = pl->y - g->y; diff = dy * pl->ca - dx * pl->sa; if (pl->speed > 0.0) v = diff + sqrt(diff*diff + blocksizesqrd - g->range*g->range); else if (pl->speed < 0.0) v = diff - sqrt(diff*diff + blocksizesqrd - g->range*g->range); pl->x += pl->sa * v; pl->y -= pl->ca * v; } for (g2=o+opt->estart; g2<o+opt->lstart; g2++) if (g2->attr & IS_ALIVE && (dist = DIST(g, g2)) < blocksizesqrd) { g2->attr |= BLOCKED_BY_BLOCK; if (!(g2->type & (IS_MISSILE | IS_COPTER))) { dx = g2->x - g->x; dy = g2->y - g->y; diff = dy * g2->ca - dx * g2->sa; if (g2->speed > 0.0) v = diff + sqrt(diff*diff + blocksizesqrd - dist); else if (g2->speed < 0.0) v = diff - sqrt(diff*diff + blocksizesqrd - dist); g2->x += g2->sa * v; g2->y -= g2->ca * v; } } } /* if the player moved, or if an enemy did, we need to recompute */ /* the range to that enemy. */ for (g=o+opt->estart; g<o+opt->lstart; g++) if (g->attr & IS_ALIVE && (g->attr & IS_BLOCKED || pl->attr & IS_BLOCKED)) g->range = sqrt(DIST(g, pl)); /* now check to see if the player is blocked by any enemy. */ /* if so, project them back. */ for (g=o+opt->estart; g<o+opt->lstart; g++) if (g->attr & IS_ALIVE && g->range < blocksize) if (!(g->type & (IS_MISSILE | IS_COPTER))) { if (g->attr & IS_BLOCKED) { pl->speed = 0.0; if (fabs(g->speed) < 0.001) g->speed = sign(0.001, g->speed); } pl->attr |= BLOCKED_BY_ENEMY; g->attr |= BLOCKED_BY_ENEMY; ddx = pl->speed * pl->sa - g->speed * g->sa; ddy = pl->speed * pl->ca - g->speed * g->ca; ddx2 = ddx*ddx; ddy2 = ddy*ddy; dx = pl->x - g->x; dy = pl->y - g->y; dif = ddy * dy - ddx * dx; alpha = (dif + sqrt(dif*dif + (blocksizesqrd - g->range*g->range) * (ddx2 + ddy2))) / (ddx2 + ddy2); pl->x += alpha * pl->speed * pl->sa; pl->y -= alpha * pl->speed * pl->ca; g->x += alpha * g->speed * g->sa; g->y -= alpha * g->speed * g->ca; } /* if we've moved, recompute distance to all the salvos */ if (pl->attr & IS_BLOCKED) for (g=o+opt->sstart; g<o+opt->bstart; g++) if (g->attr & IS_ALIVE) g->range = sqrt(DIST(g, pl)); /* enemies disappear if their range is greater than 2200. */ /* We check last[0] to see if they need to be erased. In */ /* most cases probably not, unless we really screw with */ /* their speed. */ tank_stranded = False; for (g=o+opt->estart; g<o+opt->lstart; g++) { g->ecount++; if (g->attr & IS_ALIVE) if (g->range > 2200.0) if (g->dc[0].last) g->attr = ERASE; else g->attr = 0; else if (g->type & (IS_SUPER | IS_TANK) && g->ecount > TANK_STRAND_COUNT) tank_stranded = True; } /* landers are out of range at 2750 */ for (g=o+opt->lstart; g<o+opt->sstart; g++) { g->ecount++; if (g->attr & IS_ALIVE && g->range > 2750.0) if (g->dc[0].last) g->attr = ERASE; else g->attr = 0; } /* blocks also at 2200 */ for (g=o+opt->bstart; g<o+opt->mobjects; g++) if (g->range > 2200.0) if (g->dc[0].last) g->attr = ERASE; else g->attr = 0; /* salvos are never out of range, but their lifetime is limited */ for (g=o+opt->sstart; g<o+opt->bstart; g++) { g->ecount++; if (g->attr & IS_ALIVE && g->ecount > 50) if (g->dc[0].last) g->attr = ERASE; else g->attr = 0; } /* we never set the 'salvo fired' message in this routine. */ /* however, we do have to turn it off. if salvos are alive */ /* we assume the message is on, once no enemy salvos are */ /* alive we turn it off. */ new_salvo_flag = False; for (g=o+opt->sstart; g<o+opt->bstart; g++) if (g->attr & IS_ALIVE) { /* if salvo exist and */ if (g->salvo != pl) /* not owned by player */ new_salvo_flag = True; /* then the flag is set */ /* check to see if a salvo hits a block */ for (g2=o+opt->bstart; g2<o+opt->mobjects; g2++) if (fabs(g2->x - g->x) < g2->criticalx && fabs(g2->y - g->y) < g2->criticaly) { g->attr = START_EXPLODING; g->ecount = 0; } /* now check to see if the salvo kills a lander. */ /* If so, and the player fired the salvo, update */ /* the score. */ for (g2=o+opt->lstart; g2<o+opt->sstart; g2++) if (g2->attr & IS_ALIVE) if (DIST(g, g2) < g2->criticalx) { g->attr = START_EXPLODING; g2->attr = START_EXPLODING; g->ecount = 0; g2->ecount = 0; if (g->salvo == pl) { score += 10000; icheck = score / 100000; if (icheck > scorebase) { opt->numleft++; if (opt->numleft > 4) opt->numleft = 4; scorebase = icheck; } } } /* now check to see if the salvo hit any enemy. The salvo */ /* cannot hit the one who fired it. This prevents range */ /* checking problems when first fired. */ for (g2=o+opt->estart; g2<o+opt->lstart; g2++) if (g2->attr & IS_ALIVE && g->salvo != g2) { dx = g->x - g2->x; dy = g->y - g2->y; testx = fabs( dx * g2->ca + dy * g2->sa); testy = fabs(-dx * g2->sa + dy * g2->ca); if (testx < g2->criticalx && testy < g2->criticaly && (!(g2->type & (IS_MISSILE | IS_COPTER)) || g2->z < 80.0)) { g->attr = START_EXPLODING; g2->attr = START_EXPLODING; g->ecount = 0; g2->ecount = 0; /* if the player fired, give him credit */ if (g->salvo == pl) { if (g2->type & IS_SUPER) score += 5000; else if (g2->type & (IS_MISSILE | IS_COPTER)) { score += 5000; nummissile--; } else score += 3000; icheck = score / 100000; if (icheck > scorebase) { opt->numleft++; if (opt->numleft > 4) opt->numleft = 4; scorebase = icheck; } } } } } /* check to see if a missile or copter rams a lander */ for (g=o+opt->estart; g<o+opt->lstart; g++) if (g->type & (IS_MISSILE | IS_COPTER) && g->attr & IS_ALIVE) for (g2=o+opt->lstart; g2<o+opt->sstart; g2++) if (g2->attr & IS_ALIVE && DIST(g, g2) < g2->criticalx && g->z < 80) { nummissile--; g->attr = START_EXPLODING; g2->attr = START_EXPLODING; g->ecount = 0; g2->ecount = 0; } /* now check if we need to draw the object. */ /* convert into player-centric coordinates */ /* and project a cone forward to see if the */ /* enemy is within it. Also align the gun */ /* gun sights if necessary. */ new_sight_flag = False; aligned = False; lander = False; for (g=o+opt->estart; g<o+opt->mobjects; g++) if (g->attr & (IS_ALIVE|IS_EXPLODING)) { g->dc[0].seen = False; if (g->range < 2000.0) { dx = g->x - pl->x; dy = g->y - pl->y; g->proy = -dx * pl->sa + dy * pl->ca; g->prox = dx * pl->ca + dy * pl->sa; check = g->proy / (fabs(g->prox) + 1.0); if (check > threshold) { g->dc[0].seen = True; if (g->type & IS_ENEMY && g->attr & IS_ALIVE) new_sight_flag = True; if (fabs(g->prox) < 50 && g->attr & IS_ALIVE && !(g->type & (IS_ABLOCK | IS_SALVO))) aligned = True; } if (g->type & IS_LANDER && g->attr & IS_ALIVE && check > landerthreshold) { lander = True; if (fabs(g->prox) < 60) aligned = True; } } } /* change the various messages, if necessary. Never use */ /* the bell, unless opt->loud is True. */ if (sight_flag && !new_sight_flag) { message(-1, False); sight_flag = False; } else if (!sight_flag && new_sight_flag) { message(1, False); sight_flag = True; playsound(senemy_seen); } if (pl->attr & IS_BLOCKED && !blocked_flag) { message(2, True); blocked_flag = True; playsound(smove_blocked); } else if (!(pl->attr & IS_BLOCKED) && blocked_flag) { message(-2, False); blocked_flag = False; } if (salvo_flag && !new_salvo_flag) { message(-3, False); salvo_flag = False; } else if (!salvo_flag && new_salvo_flag) { salvo_flag = True; playsound(ssalvo_fired); } scanner(o); updatedisplay(missilerun, lander, score, opt->numleft, sens, False); xhairs(aligned); drawhorizon(pl->azm); /* now draw all the objects */ for (g=o+opt->estart; g<o+opt->mobjects; g++) { if (g->attr & (IS_ALIVE | ERASE)) drawobject(g, pl); else if (g->attr & (IS_EXPLODING | EXERASE)) switch (g->type) { case IS_SALVO: explodesalvo(g, pl); break; case IS_COPTER: case IS_MISSILE: case IS_LANDER: case IS_TANK: case IS_SUPER: if (g->ecount == 1) playsound(opt->loud?skill:sobject_explodes); explodeobject(g, pl); break; default: printf("Help! Cannot explode what doesn't exist.\n"); #ifdef WIN32 return; #else //X11 myexit(1); #endif } g->attr &= ~(ERASE | EXERASE); } /* now start checking for player death. if there is a missile, */ /* check to see if it rammed the player. */ if (missilerun) for (g=o+opt->estart; g<o+opt->lstart; g++) if (g->attr & IS_ALIVE && g->type & (IS_MISSILE | IS_COPTER) && g->range < blocksize && g->z < 80) { g->attr = START_EXPLODING; drawcracks(); pl->attr &= ~IS_ALIVE; dead = True; deadcount = 0; } /* check to see if any salvos hit. */ for (g=o+opt->sstart; g<o+opt->bstart; g++) if (g->attr & IS_ALIVE && g->salvo != pl && g->range < 100.0 && fabs(g->prox) < pl->criticalx && fabs(g->proy) < pl->criticaly) { drawobject(g, pl); g->attr = 0; drawcracks(); pl->attr &= ~IS_ALIVE; dead = True; deadcount = 0; } /* if we are dead, redraw the cracks every five turns. after 50 */ /* turns, we can start playing again if we have any lives left. */ if (dead) { if (deadcount == 0) playsound(opt->loud?suser_died:sobject_explodes); if (deadcount%5 == 0) drawcracks(); if (deadcount > 50) { dead = False; if (!opt->training && (--opt->numleft < 0)) { #ifdef DEVELOPER gettimeofday(&game_end, 0); if (opt->output) printf("The game took an average %10.8f secs.\n", (game_end.tv_sec-game_start.tv_sec + (game_end.tv_usec-game_start.tv_usec)*1.0e-6)/passes); #endif //DEVELOPER free(o); #ifdef WIN32 return; #else //X11 myexit(scores(score)); #endif } if (missilerun) { nummissile -= 2; if (nummissile <= 0 && opt->mtanks) { missilerun = False; nextmissile = 750 * frand() + 750; } } clearscreen(); pl->x = 0.0; /* reset all our attributes */ pl->y = 0.0; pl->speed = 0.0; pl->azm = 0.0; pl->ca = 1.0; pl->sa = 0.0; pl->attr = START_LIVING; message(-1, False); /* turn off all the messages */ sight_flag = False; message(-2, False); // blocked_flag = False; message(-3, False); salvo_flag = False; for (g=o+opt->estart; g<o+opt->mobjects; g++) g->attr = 0; /* remove all objects */ } } /* Now schedule the missile runs. There will be a missile run if */ /* mtanks==0 or we are in copter practice or if a tank has been */ /* around too long or we haven't had a missile in a while. */ if (pl->attr & IS_ALIVE && opt->mmissiles && (!opt->mtanks || opt->copters || tank_stranded || missilecount > nextmissile)) if (!missilerun) { missilecount = 0; for (g=o+opt->estart; g<o+opt->bstart; g++) if (!(g->type & (IS_LANDER | IS_MISSILE | IS_COPTER))) if (g->attr & IS_ALIVE) g->attr = ERASE; else if (g->attr & IS_EXPLODING) g->attr = EXERASE; nummissile = frand() * 3 * opt->mmissiles + 1; if (firstmissile) nummissile = 1; first = firstmissile; firstmissile = False; missilerun = True; } /* once this run is over, schedule another one for a later date */ if (missilerun && opt->mtanks && nummissile <= 0) { missilerun = False; nextmissile = 750 * frand() + 750; } /* now place whatever objects need to be placed. */ if (!dead) placeobjects(o, missilerun, score); pl->attr &= ~IS_NEW; /* in case the player was new */ deadcount++; if (!missilerun) missilecount++; /* use timeclock here instead of gettimeofday to get a sync(d, 0) * just in case there are graphics we need to draw. */ timeclock(&tend); tdiff = limit - ((tend.tv_sec-tstart.tv_sec)*1e6+tend.tv_usec-tstart.tv_usec); if (tdiff > 0) { tend.tv_sec = 0; tend.tv_usec = tdiff; select(0, 0, 0, 0, &tend); } #ifdef DEVELOPER passes++; #endif //DEVELOPER } }
int main(){ int i = 0; int mapCount = 0, clearMapCount = 0, dumpCount=0; int revFrameCount = 0; #ifdef USE_NORTH targetsGPS[maxTargets].lat = ADVANCED5LAT; targetsGPS[maxTargets].lon = ADVANCED5LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED6LAT; targetsGPS[maxTargets].lon = ADVANCED6LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED7LAT; targetsGPS[maxTargets].lon = ADVANCED7LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED8LAT; targetsGPS[maxTargets].lon = ADVANCED8LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED2LAT; targetsGPS[maxTargets].lon = ADVANCED2LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED1LAT; targetsGPS[maxTargets].lon = ADVANCED1LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED3LAT; targetsGPS[maxTargets].lon = ADVANCED3LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED12LAT; targetsGPS[maxTargets].lon = ADVANCED12LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED4LAT; targetsGPS[maxTargets].lon = ADVANCED4LON; maxTargets++; #else targetsGPS[maxTargets].lat = ADVANCED4LAT; targetsGPS[maxTargets].lon = ADVANCED4LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED1LAT; targetsGPS[maxTargets].lon = ADVANCED1LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED2LAT; targetsGPS[maxTargets].lon = ADVANCED2LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED3LAT; targetsGPS[maxTargets].lon = ADVANCED3LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED11LAT; targetsGPS[maxTargets].lon = ADVANCED11LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED8LAT; targetsGPS[maxTargets].lon = ADVANCED8LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED7LAT; targetsGPS[maxTargets].lon = ADVANCED7LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED6LAT; targetsGPS[maxTargets].lon = ADVANCED6LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED11LAT; targetsGPS[maxTargets].lon = ADVANCED11LON; maxTargets++; targetsGPS[maxTargets].lat = ADVANCED5LAT; targetsGPS[maxTargets].lon = ADVANCED5LON; maxTargets++; #endif maxTargetIndex=maxTargets-1; for(i=0;i<maxTargets;i++){// this is converting all GPS point data to XY data. targetListXY[i].x = GPSX(targetsGPS[i].lon, startLongitude); targetListXY[i].y = GPSY(targetsGPS[i].lat, startLatitude); } currentXY.x = GPSX(gpsvar.longitude,startLongitude);// converts current robot X location compared to start longitude currentXY.y = GPSY(gpsvar.latitude,startLatitude);// converts current robot Y location compared to start latitude targetXY = targetListXY[currentTargetIndex];//sets first target GPS point nextTargetIndex = (currentTargetIndex + 1)%maxTargets;//sets next target GPS point nextXY = targetListXY[nextTargetIndex];// ?? previousXY.x = GPSX(startLongitude, startLongitude);// why? previousXY.y = GPSY(startLatitude, startLatitude);//Why? initRoboteq(); /* Initialize roboteq */ initGuide();//what is guide? #ifdef USE_VISION // if USE_vision is defined, then initialize vision. initVision(); #endif //USE_VISION #ifdef USE_GPS// if USE_GPS is defined, then initialize GPS. initGPS(); initParser(); #endif //USE_GPS #ifdef USE_LIDAR// if USE_LIDAR is defined, then initialize LIDAR. initObjects(); initSICK(); #endif //USE_LIDAR #ifdef DEBUG_VISUALIZER// if defined, then use visualizer. initVisualizer(); #endif //DEBUG_VISUALIZER #ifdef USE_MAP//////>>>>>>>>>>>???? initMap(0,0,0); #endif //USE_MAP #ifdef DUMP_GPS// dump GPS data into file FILE *fp; fp = fopen("gpsdump.txt", "w"); #endif // DUMP_GPS while(1){ double dir = 1.0; double speed = 0.0, turn = 0.0; static double turnBoost = 0.750;//Multiplier for turn. Adjust to smooth jerky motions. Usually < 1.0 static int lSpeed = 0, rSpeed = 0;//Wheel Speed Variables if (joystick() != 0) {// is joystick is connected if (joy0.buttons & LB_BTN) {// deadman switch, but what does joy0.buttons do????????????????????????????????? speed = -joy0.axis[1]; //Up is negative on joystick negate so positive when going forward turn = joy0.axis[0]; lSpeed = (int)((speed + turnBoost*turn)*maxSpeed);//send left motor speed rSpeed = (int)((speed - turnBoost*turn)*maxSpeed);//send right motor speed }else{ //stop the robot rSpeed=lSpeed=0; } if(((joy0.buttons & B_BTN)||autoOn)&& (saveImage==0)){//what is the single & ??????????????????? saveImage =DEBOUNCE_FOR_SAVE_IMAGE;//save each image the camera takes, save image is an int declared in vision_nav.h }else{ if (saveImage) saveImage--; // turn off if button wasn't pressed? } if(joy0.buttons & RB_BTN){//turn on autonmous mode if start??? button is pressed autoOn = 1; mode=1; } if(joy0.buttons & Y_BTN){ // turn off autonomous mode autoOn = 0; mode =0; } lastButtons = joy0.buttons;//is this just updating buttons? } else{ // printf("No Joystick Found!\n"); rSpeed=lSpeed=0; } // // printf("3: %f %f\n",BASIC3LAT,BASIC3LON); // printf("4: %f %f\n",BASIC4LAT,BASIC4LON); // printf("5: %f %f\n",BASIC5LAT,BASIC5LON); // getchar(); #ifdef AUTO_SWAP//what is this if((currentTargetIndex>1&&targetIndexMem!=currentTargetIndex)||!autoOn||!mode==3){ startTime=currentTime=(float)(clock()/CLOCKS_PER_SEC); targetIndexMem = currentTargetIndex; }else{ currentTime=(float)(clock()/CLOCKS_PER_SEC); } totalTime = currentTime-startTime; if(totalTime>=SWAPTIME&&autoOn){ swap(); targetIndexMem = 0; } #endif //AUTO_SWAP #ifdef USE_GPS readGPS(); currentXY.x = GPSX(gpsvar.longitude,startLongitude); currentXY.y = GPSY(gpsvar.latitude,startLatitude); robotTheta = ADJUST_RADIANS(DEG2RAD(gpsvar.course)); #else currentXY.x = 0.0; currentXY.y = 0.0; robotTheta = 0.0; #endif //USE_GPS if(autoOn&&!flagPointSet){//this whole thing????? flagXY.x=currentXY.x+FLAG_X_ADJUST; flagXY.y=currentXY.y; flagPointSet=1; startAutoTime=currentAutoTime=(float)(clock()/CLOCKS_PER_SEC); } if(autoOn){ currentAutoTime=(float)(clock()/CLOCKS_PER_SEC); totalAutoTime = currentAutoTime-startAutoTime; if(totalAutoTime>=MODE2DELAY){ mode1TimeUp=1;//what is mode1 time up? } printf("TIMEING\n"); } // if(currentTargetIndex <= OPEN_FIELD_INDEX || currentTargetIndex >= maxTargetIndex){ if(currentTargetIndex <= OPEN_FIELD_INDEX){//if you are on your last target, then set approaching thresh, and dest thresh to larger values? //OPEN_FIELD_INDEX is set to 0 above...? approachingThresh=4.0; destinationThresh=3.0; }else{//otherwise set your thresholds to a bit closer. // destinationThresh=1.0; destinationThresh=0.75; approachingThresh=2.5; } //mode1 = lane tracking and obstacle avoidance. mode 2 = vision, lane tracking, but guide to gps. its not primary focus. //mode3= gps mode in open field, but vision is toned down to not get distracted by random grass. //mode 4= flag tracking if(guide(currentXY, targetXY, previousXY, nextXY, robotTheta, robotWidth, 1)&& !allTargetsReached){//If target reached and and not all targets reached printf("REACHED TARGET\n"); initGuide();// reset PID control stuff. problably resets all control variables. previousXY = targetXY;//update last target if(currentTargetIndex == maxTargetIndex){ //seeing if you are done with all targets. allTargetsReached = 1; }else{//otherwise update all the target information currentTargetIndex = (currentTargetIndex + 1); nextTargetIndex = (currentTargetIndex + 1)% maxTargets; targetXY = targetListXY[currentTargetIndex]; nextXY = targetListXY[nextTargetIndex]; } } if((autoOn&&(currentTargetIndex == 0&&!approachingTarget&&!mode1TimeUp))||allTargetsReached){ //if autonomous, and on first target, and not not approaching target, and not mode 1 time up, or reached last target. mode =1;//wtf is mode distanceMultiplier = 50;//wthis is how heavily to rely on vision } else if((autoOn&¤tTargetIndex == 0&&mode1TimeUp)||(autoOn&&approachingTarget&&(currentTargetIndex<=OPEN_FIELD_INDEX||currentTargetIndex>=maxTargetIndex-END_LANE_INDEX))){ mode =2; distanceMultiplier = 50; } else if((autoOn&¤tTargetIndex!=0)){ mode =3; distanceMultiplier = 12; } flagPointDistance = D((currentXY.x-flagXY.x),(currentXY.y-flagXY.y));// basically the distance formula, but to what? what flags GPS point? if(allTargetsReached&&flagPointDistance<FLAG_DIST_THRESH){ mode =4;// what is mode } #ifdef FLAG_TESTING /*FLAG TESTING*/ mode=4; #endif //FLAG_TESTING /*Current Target Heading PID Control Adjustment*/ cvar.lookAhead = 0.00;//? cvar.kP = 0.20; cvar.kI = 0.000; cvar.kD = 0.15; turn = cvar.turn; int bestVisGpsMask = 99; int h = 0; double minVisGpsTurn = 9999; for(h=0;h<11;h++){ if(fabs((cvar.turn-turn_angle[h]))<minVisGpsTurn){ minVisGpsTurn=fabs((cvar.turn-turn_angle[h])); bestVisGpsMask = h; } } bestGpsMask = bestVisGpsMask; // printf("bvg: %d \n", bestVisGpsMask); // printf("vgt: %f cv3: %f\n", minVisGpsTurn,cvar3.turn); #ifdef USE_VISION // double visTurnBoost = 0.50; double visTurnBoost = 1.0; if(imageProc(mode) == -1) break; if(mode==1||mode==2){ turn = turn_angle[bestmask]; turn *= visTurnBoost; }else if(mode==3 && fabs(turn_angle[bestmask])>0.70){ turn = turn_angle[bestmask]; turn *= visTurnBoost; } #endif //USE_VISION #ifdef USE_LIDAR updateSick(); // findObjects(); #endif //USE_LIDAR #ifdef USE_COMBINED_BUFFER//?????????? #define WORSTTHRESH 10 #define BESTTHRESH 3 if(mode==4){ #ifdef USE_NORTH turn = (0.5*turn_angle[bestBlueMask]+0.5*turn_angle[bestRedMask]); #else turn = (0.65*turn_angle[bestBlueMask]+0.35*turn_angle[bestRedMask]); #endif turn *= 0.75; } combinedTargDist = cvar.targdist; if(((approachingTarget||inLastTarget)&¤tTargetIndex>OPEN_FIELD_INDEX &¤tTargetIndex<maxTargetIndex-END_LANE_INDEX)||(MAG(howbad[worstmask]-howbad[bestmask]))<BESTTHRESH||mode==4){ getCombinedBufferAngles(0,0);//Don't Use Vision Radar Data }else{ getCombinedBufferAngles(0,1);//Use Vision Radar Data } if(combinedBufferAngles.left != 0 || combinedBufferAngles.right !=0){ if(mode == 1 || mode==2 || mode==3 || mode==4){ // if(mode == 1 || mode==2 || mode==3){ // if(mode==2 || mode==3){ // if(mode==3){ if(fabs(combinedBufferAngles.right)==fabs(combinedBufferAngles.left)){ double revTurn; double revDistLeft, revDistRight; int revIdx; if(fabs(turn)<0.10) dir = -1.0; if(fabs(combinedBufferAngles.left)>1.25) dir = -1.0; if(dir<0){ revIdx = 540-RAD2DEG(combinedBufferAngles.left)*4; revIdx = MIN(revIdx,1080); revIdx = MAX(revIdx,0); revDistLeft = LMSdata[revIdx]; revIdx = 540-RAD2DEG(combinedBufferAngles.right)*4; revIdx = MIN(revIdx,1080); revIdx = MAX(revIdx,0); revDistRight = LMSdata[revIdx]; if(revDistLeft>=revDistRight){ revTurn = combinedBufferAngles.left; }else { revTurn = combinedBufferAngles.right; } turn = revTurn; }else{ turn = turn_angle[bestmask]; } } else if(fabs(combinedBufferAngles.right-turn)<fabs(combinedBufferAngles.left-turn)){ // } else if(turn<=0){ turn = combinedBufferAngles.right; }else { turn = combinedBufferAngles.left; } } } #endif //USE_COMBINED_BUFFER if(dir<0||revFrameCount!=0){ dir = -1.0; revFrameCount = (revFrameCount+1)%REVFRAMES; } // turn *= dir; turn = SIGN(turn) * MIN(fabs(turn), 1.0); speed = 1.0/(1.0+1.0*fabs(turn))*dir; speed = SIGN(speed) * MIN(fabs(speed), 1.0); if(!autoOn){ maxSpeed = 60; targetIndexMem = 0; }else if(dir<0){ maxSpeed = 30; }else if(mode<=2||(mode==3 && fabs(turn_angle[bestmask])>0.25)){ maxSpeed = 60 - 25*fabs(turn); // maxSpeed = 70 - 35*fabs(turn); // maxSpeed = 90 - 50*fabs(turn); // maxSpeed = 100 - 65*fabs(turn); }else if(mode==4){ maxSpeed = 45-20*fabs(turn); }else{ maxSpeed = 85 - 50*fabs(turn); // maxSpeed = 100 - 65*fabs(turn); // maxSpeed = 110 - 70*fabs(turn); // maxSpeed = 120 - 85*fabs(turn); } if(autoOn){ lSpeed = (speed + turnBoost*turn) * maxSpeed; rSpeed = (speed - turnBoost*turn) * maxSpeed; } #ifdef DEBUG_MAIN printf("s:%.4f t: %.4f m: %d vt:%f dir:%f tmr: %f\n", speed, turn, mode, turn_angle[bestmask], flagPointDistance, totalAutoTime); #endif //DEBUG_MAIN #ifdef DUMP_GPS if(dumpCount==0){ if (fp != NULL) { fprintf(fp, "%f %f %f %f %f\n",gpsvar.latitude,gpsvar.longitude, gpsvar.course, gpsvar.speed, gpsvar.time); } } dumpCount = dumpCount+1%DUMPGPSDELAY; #endif //DUMP_GPS #ifdef DEBUG_TARGET debugTarget(); #endif //DEBUG_TARGET #ifdef DEBUG_GUIDE debugGuide(); #endif //DEBUG_GUIDE #ifdef DEBUG_GPS debugGPS(); #endif //DEBUG_GPS #ifdef DEBUG_LIDAR debugSICK(); #endif //DEBUG_LIDAR #ifdef DEBUG_BUFFER debugCombinedBufferAngles(); #endif //DEBUG_BUFFE #ifdef DEBUG_VISUALIZER robotX = currentXY.x; robotY = currentXY.y; robotTheta = robotTheta;//redundant I know.... targetX = targetXY.x; targetY = targetXY.y; // should probably pass the above to the function... paintPathPlanner(robotX,robotY,robotTheta); showPlot(); #endif //VISUALIZER #ifdef USE_MAP if(mapCount==0){ // mapRobot(currentXY.x,currentXY.y,robotTheta); if(clearMapCount==0) clearMapSection(currentXY.x,currentXY.y,robotTheta); else clearMapCount = (clearMapCount+1)%CLEARMAPDELAY; mapVSICK(currentXY.x,currentXY.y,robotTheta); // mapVSICK(0,0,0); #ifdef USE_LIDAR mapSICK(currentXY.x,currentXY.y,robotTheta); #endif showMap(); // printf("MAPPING\n"); } mapCount= (mapCount+1)%MAPDELAY; #endif //USE_MAP sendSpeed(lSpeed,rSpeed); Sleep(5); } #ifdef DUMP_GPS fclose(fp); #endif return 0; }
int main(int argc, const char * argv[]) { OptParse parser; // parser.addOption("s", true); parser.addOption("js", true); if(!parser.parse(argc, argv)) { std::cout << "Required Options were not specified" << std::endl; return 1; } asio::io_service io; PacketSender sender(io); sender.connect(6142); // for(int i = 0; i < 5; ++i) // { // sender.write("P"); // std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // } JoyStick joystick(parser.getOption("js")); //AudioCapture audio("hw:1,0", "S16_LE"); //AudioCapture audio("hw:1,0", ""); //AudioCapture audio; //ImageProcessor imageProcessor; //SerialComm serial; // Define the Axis to use TimedAxisController panAxis(joystick, JoyStick::Axis::HAT_H); panAxis.setInterval(50); TimedAxisController tiltAxis(joystick, JoyStick::Axis::HAT_V); tiltAxis.setInterval(100); EventAxisController leftMotorAxis(joystick, JoyStick::Axis::LEFT_STICK_V); EventAxisController rightMotorAxis(joystick, JoyStick::Axis::RIGHT_STICK_V); CameraController cameraController(panAxis, tiltAxis, 90, 90); cameraController.setPanSpeed(2.0f); cameraController.setTiltSpeed(2.0f); MotorController motorController(leftMotorAxis, rightMotorAxis); motorController.setMaxSpeed(100.0f); // main command dispatch loop // read input from the joy stick and handle appropriate events while(true) { joystick.pollEvents(); // Check for exit if(joystick.isPressed(JoyStick::Button::BACK)) { std::cout << "Exiting" << std::endl; break; } // Attempt to sync with platform if(joystick.isPressed(JoyStick::Button::START)) { std::cout << "Requesting Sync with Platform..." << std::endl; sender.write("Z"); // ... } // When the left trigger is pressed capture image from webcam // if(joystick.isPressed(JoyStick::Button::LEFT_TRIGGER1)) // { // std::cout << "Capturing Image..." << std::endl; // imageProcessor.process(); // } // Trigger Audio Capture // if(joystick.isPressed(JoyStick::Button::RIGHT_TRIGGER1)) // { // std::cout << "Capturing Audio..." << std::endl; // audio.capture(44100, 3); // } cameraController.update(sender); motorController.update(sender); } sender.close(); return 0; }