bool Input::operator!= (const Input & rhs) const { return getDataNum() != rhs.getDataNum(); }
void Delete::Execute() { Input *pIn = pManager->GetInput(); Output *pOut = pManager->GetOutput(); //Get List of selected statements list<Statement*> SelectedStatements = pManager->GetSelectedStatements(); list<Connector*> SelectedConnectors = pManager->GetSelectedConnectors(); Point TempP; //list<Connector*>ConnList = pManager->GetConnList(); //Print Message and Wait for any click pOut->PrintMessage("Delete: Deleting Selected Statements if any, press any key to continue"); pIn->GetPointClicked(TempP); for (list<Connector*>::iterator it = SelectedConnectors.begin(); it != SelectedConnectors.end(); it++) { pManager->DeleteConnector((*it)); } list<Connector*>ConnList = pManager->GetConnList(); for (list<Statement*>::iterator it = SelectedStatements.begin(); it != SelectedStatements.end(); it++) { //Delete Input Connectors if ((*it)->GetStatementType() != 0 || ((*it)->GetStatementType() == 0 && ((StartEnd*)(*it))->GetMode() == true)) { list<Connector*> InputConnectors; for (list<Connector*>::iterator itConn = ConnList.begin(); itConn != ConnList.end(); itConn++) { if ((*itConn)->getDstStat() == (*it)) InputConnectors.push_back((*itConn)); } for (list<Connector*>::iterator itConn = InputConnectors.begin(); itConn != InputConnectors.end(); itConn++) { /* if ((*itConn)->getSrcStat()->GetpConn == (*itConn)) (*itConn)->getSrcStat()->SetpConn(NULL); else if (((Conditional*)(*itConn)->getSrcStat())->GetpConnL() == (*itConn)) ((Conditional*)(*itConn)->getSrcStat())->SetpConnL(NULL); */ if ((*itConn)->GetBranchType() == 2) ((Conditional*)(*itConn)->getSrcStat())->SetpConnL(NULL); else (*itConn)->getSrcStat()->SetpConn(NULL); pManager->DeleteConnector((*itConn)); } } //Conditional if ((*it)->GetStatementType() == 3) { //Yes if (((Conditional*)(*it))->GetpConn() != NULL) pManager->DeleteConnector(((Conditional*)(*it))->GetpConn()); //No if (((Conditional*)(*it))->GetpConnL() != NULL) pManager->DeleteConnector(((Conditional*)(*it))->GetpConnL()); } else //Not Conditional { if ((*it)->GetpConn() != NULL) pManager->DeleteConnector((*it)->GetpConn()); } pManager->DeleteStatement((*it)); } pOut->PrintMessage(""); pOut->ClearDrawArea(); pManager->UpdateInterface(); }
/* Main game event loop. * Runs at 60 Hz. * Handles inputs * Update sprites * Check collisions * Draw Screen */ void Game::eventLoop() { Graphics graphics; Input input; SDL_Event event; player_ = new Player(graphics, 400, 300); map_ = Map::createMap(graphics); bool running = true; while (running) { const int start_time_ms = SDL_GetTicks(); input.beginNewFrame(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: input.keyDownEvent(event); break; case SDL_KEYUP: input.keyUpEvent(event); break; default: break; } } /* Exit the game */ if (input.wasKeyPressed(SDLK_ESCAPE)) { running = false; } /* Player Movement */ if (input.isKeyHeld(SDLK_UP) && input.isKeyHeld(SDLK_DOWN)) { player_->stopMovingVertically(); } else if (input.isKeyHeld(SDLK_UP)) { player_->startMovingUp(); } else if (input.isKeyHeld(SDLK_DOWN)) { player_->startMovingDown(); } else { player_->stopMovingVertically(); } if (input.isKeyHeld(SDLK_LEFT) && input.isKeyHeld(SDLK_RIGHT)) { player_->stopMovingHorizontally(); } else if (input.isKeyHeld(SDLK_LEFT)) { player_->startMovingLeft(); } else if (input.isKeyHeld(SDLK_RIGHT)) { player_->startMovingRight(); } else { player_->stopMovingHorizontally(); } if (input.isKeyHeld(SDLK_RSHIFT)) { player_->setRunning(true); } else { player_->setRunning(false); } /* Update locations */ update(20); /* Draw to the screen */ draw(graphics); /* Keep the game running at max 60 fps */ const int delay = 1000 / FPS - (SDL_GetTicks() - start_time_ms); if (delay > 0) { SDL_Delay(delay); } } }
bool GeoState_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; // note, StateSet replaced GeoState April 2001. StateSet& statset = static_cast<StateSet&>(obj); statset.setRenderingHint(StateSet::OPAQUE_BIN); StateAttribute::GLModeValue mode; if (fr[0].matchWord("transparency") && StateSet_matchModeStr(fr[1].getStr(),mode)) { if (mode&StateAttribute::ON) { statset.setRenderingHint(StateSet::TRANSPARENT_BIN); } statset.setMode(GL_BLEND,mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("antialiasing") && StateSet_matchModeStr(fr[1].getStr(),mode)) { // what is the OpenGL modes for antialissing, need to look up. // statset.setMode(GeoState::ANTIALIAS,mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("face_culling") && StateSet_matchModeStr(fr[1].getStr(),mode)) { statset.setMode(GL_CULL_FACE,mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("lighting") && StateSet_matchModeStr(fr[1].getStr(),mode)) { statset.setMode(GL_LIGHTING,mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("texturing") && StateSet_matchModeStr(fr[1].getStr(),mode)) { statset.setTextureMode(0,GL_TEXTURE_2D,mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("fogging") && StateSet_matchModeStr(fr[1].getStr(),mode)) { statset.setMode(GL_FOG,mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("colortable") && StateSet_matchModeStr(fr[1].getStr(),mode)) { // what is the OpenGL modes for colortable, need to look up... // statset.setMode(GeoState::COLORTABLE,mode); fr+=2; iteratorAdvanced = true; } StateAttribute::GLModeValue texgening = StateAttribute::OFF; if (fr[0].matchWord("texgening") && StateSet_matchModeStr(fr[1].getStr(),mode)) { // leave up to a tex gen object to set modes associated with TexGen // as there are mutiple modes associated with TexGen. See below // attribute reading code. texgening = mode; fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("point_smoothing") && StateSet_matchModeStr(fr[1].getStr(),mode)) { statset.setMode(GL_POINT_SMOOTH,mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("polygon_offset") && StateSet_matchModeStr(fr[1].getStr(),mode)) { // no GL mode associated with polygon offset so commenting out. // statset.setMode(GeoState::POLYGON_OFFSET,mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("alpha_test") && StateSet_matchModeStr(fr[1].getStr(),mode)) { statset.setMode(GL_ALPHA_TEST,mode); fr+=2; iteratorAdvanced = true; } // new code using osg::Registry's list of prototypes to loaded attributes. StateAttribute* attribute = NULL; while((attribute=fr.readStateAttribute())!=NULL) { if (attribute->isTextureAttribute()) { // remap to be a texture attribute statset.setTextureAttribute(0,attribute); } else { statset.setAttribute(attribute); } if (attribute->getType()==StateAttribute::TEXGEN) statset.setAssociatedModes(attribute,texgening); iteratorAdvanced = true; } return iteratorAdvanced; }
#include "green/GreenData.hpp" #include "interface/Input.hpp" #include "solver/SolverData.hpp" #include "utils/Sphere.hpp" using pcm::Input; using pcm::utils::Sphere; /*! \class Input * \test \b InputRestartTest_Restart tests input reading on an input file parsed by * go_pcm.py */ TEST_CASE("Input reading using GetKw for an input file for a restart cavity", "[input][input_restart]") { std::string filename = "@restart.inp"; Input parsedInput = Input(filename); std::string units = "AU"; int CODATAyear = 2010; std::string cavityType = "RESTART"; std::string cavFilename = "cavity.npz"; double area = 0.3; bool scaling = true; std::string radiiSet = "BONDI"; double minimalRadius = 100.0; double diagonalScaling = 1.07; std::string mode = "IMPLICIT"; std::string solvent = "Water"; // Name in the Solvent object std::string solverType = "IEFPCM"; double correction = 0.0; bool hermitivitize = true; double probeRadius = 1.385 * angstromToBohr(); // The value for water
static void apply( const Input& in, state1& s ) { assert( in.size() == 1 ); s.c = in.begin()[ 0 ]; }
void Network::loadFromBundle(const std::string& name) { if (! StringUtils::endsWith(name, ".nta")) NTA_THROW << "loadFromBundle: bundle extension must be \".nta\""; std::string fullPath = Path::normalize(Path::makeAbsolute(name)); if (! Path::exists(fullPath)) NTA_THROW << "Path " << fullPath << " does not exist"; std::string networkStructureFilename = Path::join(fullPath, "network.yaml"); std::ifstream f(networkStructureFilename.c_str()); YAML::Parser parser(f); YAML::Node doc; bool success = parser.GetNextDocument(doc); if (!success) NTA_THROW << "Unable to find YAML document in network structure file " << networkStructureFilename; if (doc.Type() != YAML::NodeType::Map) NTA_THROW << "Invalid network structure file -- does not contain a map"; // Should contain Version, Regions, Links if (doc.size() != 3) NTA_THROW << "Invalid network structure file -- contains " << doc.size() << " elements"; // Extra version const YAML::Node *node = doc.FindValue("Version"); if (node == NULL) NTA_THROW << "Invalid network structure file -- no version"; int version; *node >> version; if (version != 2) NTA_THROW << "Invalid network structure file -- only version 2 supported"; // Regions const YAML::Node *regions = doc.FindValue("Regions"); if (regions == NULL) NTA_THROW << "Invalid network structure file -- no regions"; if (regions->Type() != YAML::NodeType::Sequence) NTA_THROW << "Invalid network structure file -- regions element is not a list"; for (YAML::Iterator region = regions->begin(); region != regions->end(); region++) { // Each region is a map -- extract the 5 values in the map if ((*region).Type() != YAML::NodeType::Map) NTA_THROW << "Invalid network structure file -- bad region (not a map)"; if ((*region).size() != 5) NTA_THROW << "Invalid network structure file -- bad region (wrong size)"; // 1. name node = (*region).FindValue("name"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region has no name"; std::string name; *node >> name; // 2. nodeType node = (*region).FindValue("nodeType"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region " << name << " has no node type"; std::string nodeType; *node >> nodeType; // 3. dimensions node = (*region).FindValue("dimensions"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region " << name << " has no dimensions"; if ((*node).Type() != YAML::NodeType::Sequence) NTA_THROW << "Invalid network structure file -- region " << name << " dimensions specified incorrectly"; Dimensions dimensions; for (YAML::Iterator valiter = (*node).begin(); valiter != (*node).end(); valiter++) { size_t val; (*valiter) >> val; dimensions.push_back(val); } // 4. phases node = (*region).FindValue("phases"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region" << name << "has no phases"; if ((*node).Type() != YAML::NodeType::Sequence) NTA_THROW << "Invalid network structure file -- region " << name << " phases specified incorrectly"; std::set<UInt32> phases; for (YAML::Iterator valiter = (*node).begin(); valiter != (*node).end(); valiter++) { UInt32 val; (*valiter) >> val; phases.insert(val); } // 5. label node = (*region).FindValue("label"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region" << name << "has no label"; std::string label; *node >> label; Region *r = addRegionFromBundle(name, nodeType, dimensions, fullPath, label); setPhases_(r, phases); } const YAML::Node *links = doc.FindValue("Links"); if (links == NULL) NTA_THROW << "Invalid network structure file -- no links"; if (links->Type() != YAML::NodeType::Sequence) NTA_THROW << "Invalid network structure file -- links element is not a list"; for (YAML::Iterator link = links->begin(); link != links->end(); link++) { // Each link is a map -- extract the 5 values in the map if ((*link).Type() != YAML::NodeType::Map) NTA_THROW << "Invalid network structure file -- bad link (not a map)"; if ((*link).size() != 6) NTA_THROW << "Invalid network structure file -- bad link (wrong size)"; // 1. type node = (*link).FindValue("type"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a type"; std::string linkType; *node >> linkType; // 2. params node = (*link).FindValue("params"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have params"; std::string params; *node >> params; // 3. srcRegion (name) node = (*link).FindValue("srcRegion"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a srcRegion"; std::string srcRegionName; *node >> srcRegionName; // 4. srcOutput node = (*link).FindValue("srcOutput"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a srcOutput"; std::string srcOutputName; *node >> srcOutputName; // 5. destRegion node = (*link).FindValue("destRegion"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a destRegion"; std::string destRegionName; *node >> destRegionName; // 6. destInput node = (*link).FindValue("destInput"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a destInput"; std::string destInputName; *node >> destInputName; if (!regions_.contains(srcRegionName)) NTA_THROW << "Invalid network structure file -- link specifies source region '" << srcRegionName << "' but no such region exists"; Region* srcRegion = regions_.getByName(srcRegionName); if (!regions_.contains(destRegionName)) NTA_THROW << "Invalid network structure file -- link specifies destination region '" << destRegionName << "' but no such region exists"; Region* destRegion = regions_.getByName(destRegionName); Output* srcOutput = srcRegion->getOutput(srcOutputName); if (srcOutput == NULL) NTA_THROW << "Invalid network structure file -- link specifies source output '" << srcOutputName << "' but no such name exists"; Input* destInput = destRegion->getInput(destInputName); if (destInput == NULL) NTA_THROW << "Invalid network structure file -- link specifies destination input '" << destInputName << "' but no such name exists"; // Create the link itself destInput->addLink(linkType, params, srcOutput); } // links }
bool Texture_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; Texture& texture = static_cast<Texture&>(obj); Texture::WrapMode wrap; if (fr[0].matchWord("wrap_s") && Texture_matchWrapStr(fr[1].getStr(),wrap)) { texture.setWrap(Texture::WRAP_S,wrap); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("wrap_t") && Texture_matchWrapStr(fr[1].getStr(),wrap)) { texture.setWrap(Texture::WRAP_T,wrap); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("wrap_r") && Texture_matchWrapStr(fr[1].getStr(),wrap)) { texture.setWrap(Texture::WRAP_R,wrap); fr+=2; iteratorAdvanced = true; } Texture::FilterMode filter; if (fr[0].matchWord("min_filter") && Texture_matchFilterStr(fr[1].getStr(),filter)) { texture.setFilter(Texture::MIN_FILTER,filter); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("mag_filter") && Texture_matchFilterStr(fr[1].getStr(),filter)) { texture.setFilter(Texture::MAG_FILTER,filter); fr+=2; iteratorAdvanced = true; } if (fr.matchSequence("maxAnisotropy %f")) { float anis=1.0f; fr[1].getFloat(anis); texture.setMaxAnisotropy(anis); fr +=2 ; iteratorAdvanced = true; } if (fr.matchSequence("borderColor %f %f %f %f")) { Vec4 color; fr[1].getFloat(color[0]); fr[2].getFloat(color[1]); fr[3].getFloat(color[2]); fr[4].getFloat(color[3]); texture.setBorderColor(color); fr +=5 ; iteratorAdvanced = true; } if (fr.matchSequence("borderWidth %i")) { int width=0; fr[1].getInt(width); texture.setBorderWidth(width); fr +=2 ; iteratorAdvanced = true; } if (fr[0].matchWord("useHardwareMipMapGeneration")) { if (fr[1].matchWord("TRUE")) { texture.setUseHardwareMipMapGeneration(true); fr +=2 ; iteratorAdvanced = true; } else if (fr[1].matchWord("FALSE")) { texture.setUseHardwareMipMapGeneration(false); fr +=2 ; iteratorAdvanced = true; } } if (fr[0].matchWord("unRefImageDataAfterApply")) { if (fr[1].matchWord("TRUE")) { texture.setUnRefImageDataAfterApply(true); fr +=2 ; iteratorAdvanced = true; } else if (fr[1].matchWord("FALSE")) { texture.setUnRefImageDataAfterApply(false); fr +=2 ; iteratorAdvanced = true; } } Texture::InternalFormatMode mode; if (fr[0].matchWord("internalFormatMode") && Texture_matchInternalFormatModeStr(fr[1].getStr(),mode)) { texture.setInternalFormatMode(mode); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("internalFormat")) { int value; if (Texture_matchInternalFormatStr(fr[1].getStr(),value) || fr[1].getInt(value)) { texture.setInternalFormat(value); fr+=2; iteratorAdvanced = true; } } if (fr[0].matchWord("sourceFormat")) { int value; if (Texture_matchInternalFormatStr(fr[1].getStr(),value) || fr[1].getInt(value)) { texture.setSourceFormat(value); fr+=2; iteratorAdvanced = true; } } if (fr[0].matchWord("sourceType")) { int value; if (Texture_matchInternalFormatStr(fr[1].getStr(),value) || fr[1].getInt(value)) { texture.setSourceType(value); fr+=2; iteratorAdvanced = true; } } if (fr[0].matchWord("resizeNonPowerOfTwo")) { if (fr[1].matchWord("TRUE")) { texture.setResizeNonPowerOfTwoHint(true); fr +=2 ; iteratorAdvanced = true; } else if (fr[1].matchWord("FALSE")) { texture.setResizeNonPowerOfTwoHint(false); fr +=2 ; iteratorAdvanced = true; } } if (fr[0].matchWord("shadowComparison")) { if (fr[1].matchWord("TRUE")) { texture.setShadowComparison(true); fr +=2 ; iteratorAdvanced = true; } else if (fr[1].matchWord("FALSE")) { texture.setShadowComparison(false); fr +=2 ; iteratorAdvanced = true; } } if (fr[0].matchWord("shadowCompareFunc")) { Texture::ShadowCompareFunc value; if (Texture_matchShadowCompareFuncStr(fr[1].getStr(),value)) { texture.setShadowCompareFunc(value); fr+=2; iteratorAdvanced = true; } } if (fr[0].matchWord("shadowTextureMode")) { Texture::ShadowTextureMode value; if (Texture_matchShadowTextureModeStr(fr[1].getStr(),value)) { texture.setShadowTextureMode(value); fr+=2; iteratorAdvanced = true; } } return iteratorAdvanced; }
bool OverlayNode_readLocalData(Object &obj, Input &fr) { bool iteratorAdvanced = false; OverlayNode &es = static_cast<OverlayNode&>(obj); if (fr.matchSequence("technique")) { if (fr[1].matchWord("OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY")) { es.setOverlayTechnique(OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY); iteratorAdvanced = true; fr += 2; } else if (fr[1].matchWord("VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY")) { es.setOverlayTechnique(OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY); iteratorAdvanced = true; fr += 2; } else if (fr[1].matchWord("VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY")) { es.setOverlayTechnique(OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY); iteratorAdvanced = true; fr += 2; } } osg::Vec4 vec4(0.0f, 0.0f, 0.0f, 1.0f); if (fr[0].matchWord("clear_color") && fr[1].getFloat(vec4[0]) && fr[2].getFloat(vec4[1]) && fr[3].getFloat(vec4[2]) && fr[4].getFloat(vec4[3])) { es.setOverlayClearColor(vec4); fr += 5; iteratorAdvanced = true; } if (fr[0].matchWord("texture_size_hint")) { if (fr[1].isUInt()) { unsigned int value = 0; fr[1].getUInt(value); es.setOverlayTextureSizeHint(value); iteratorAdvanced = true; fr += 2; } } if (fr[0].matchWord("texture_unit")) { if (fr[1].isUInt()) { unsigned int value = 0; fr[1].getUInt(value); es.setOverlayTextureUnit(value); iteratorAdvanced = true; fr += 2; } } if (fr[0].matchWord("subgraph")) { fr += 1; es.setOverlaySubgraph(fr.readNode()); iteratorAdvanced = true; } return iteratorAdvanced; }
virtual bool configure(ResourceFinder &rf) { string slash="/"; string ctrlName; string robotName; string partName; string remoteName; string localName; Time::turboBoost(); // get params from the RF ctrlName=rf.check("local",Value("fakeMobileBaseTest")).asString(); robotName=rf.check("robot",Value("fakeRobot")).asString(); partName = rf.check("part", Value("mobile_base")).asString(); bool holonomic = rf.check("holonomic"); if (holonomic) yInfo() << "Robot is holonomic"; else yInfo() << "Robot is not holonomic"; remoteName=slash+robotName+slash+partName; localName=slash+ctrlName; //reads the configuration file Property ctrl_options; ConstString configFile=rf.findFile("from"); if (configFile=="") //--from fakeMobileBaseTest.ini { yWarning("Cannot find .ini configuration file. By default I'm searching for fakeMobileBaseTest.ini"); // return false; } else { ctrl_options.fromConfigFile(configFile.c_str()); } ctrl_options.put("remote", remoteName.c_str()); ctrl_options.put("local", localName.c_str()); int rc_count =0; int rp_count =0; int rf_count =0; double start_time=yarp::os::Time::now(); bool not_yet_connected=true; //set the thread rate int period = rf.check("period",Value(20)).asInt(); yInfo("fakeMobileBaseTest thread rate: %d ms.",period); //GENERAL options yarp::os::Bottle general_options; if (ctrl_options.check("GENERAL")) { general_options = ctrl_options.findGroup("GENERAL"); } else { yError() << "Missing general_options section"; return false; } //initialize ROS bool useRos = general_options.check("use_ROS", Value(false), "enable ROS communications").asBool(); if(useRos) { if (ctrl_options.check("ROS_GENERAL")) { string rosNodeName; yarp::os::Bottle r_group = ctrl_options.findGroup("ROS_GENERAL"); if (r_group.check("node_name") == false) { yError() << "Missing node_name parameter"; return false; } rosNodeName = r_group.find("node_name").asString(); rosNode = new yarp::os::Node(rosNodeName); yarp::os::Time::delay(0.1); } else { yError() << "[ROS_GENERAL] group is missing from configuration file. ROS communication will not be initialized"; } } //creates the input input = new Input(); if (input->open(rf, ctrl_options) ==false) { yError() << "Module failed to launch"; return false; } //creates the controller control = new Controller(); if (control->init(holonomic) == false) { yError() << "Module failed to launch"; return false; } if (ctrl_options.check("ODOMETRY_ERROR")) { yarp::os::Bottle error_group = ctrl_options.findGroup("ODOMETRY_ERROR"); if (error_group.check("x_gain") == false) { yError() << "Missing x_gain parameter"; return false; } if (error_group.check("y_gain") == false) { yError() << "Missing y_gain parameter"; return false; } if (error_group.check("t_gain") == false) { yError() << "Missing t_gain parameter"; return false; } double odometry_error_x_gain = error_group.find("x_gain").asDouble(); double odometry_error_y_gain = error_group.find("y_gain").asDouble(); double odometry_error_t_gain = error_group.find("t_gain").asDouble(); control->set_odometry_error(odometry_error_x_gain,odometry_error_y_gain,odometry_error_t_gain); } //try to connect to joystickCtrl output if (rf.check("joystick_connect")) { int joystick_trials = 0; do { yarp::os::Time::delay(1.0); if (yarp::os::Network::connect("/joystickCtrl:o", localName + "/joystick:i")) { yInfo("Joystick has been automatically connected"); break; } else { yWarning("Unable to find the joystick port, retrying (%d/5)...",joystick_trials); joystick_trials++; } if (joystick_trials>=5) { yError("Unable to find the joystick port, giving up"); break; } } while (1); } rpcPort.open((localName+"/rpc").c_str()); attach(rpcPort); m_command.m_command_lin_dir = 0; m_command.m_command_lin_vel = 0; m_command.m_command_ang_vel = 0; m_command.m_command_time = 0; return true; }
void SDL_handleEvent(SDL_Event &event, bool &done) { Input *input = &Input::instance; #ifndef EMSCRIPTEN SDL_Window *wnd = SDL_GetWindowFromID(event.window.windowID); void *data = SDL_GetWindowData(wnd, "_"); spStage stage = (Stage*)data; #else spStage stage = getStage(); #endif if (!stage) stage = getStage(); Event ev(Input::event_platform); ev.userData = &event; Input::instance.dispatchEvent(&ev); switch (event.type) { case SDL_QUIT: done = true; break; case SDL_WINDOWEVENT: { /* if (event.window.event == SDL_WINDOWEVENT_ENTER) active = false; if (event.window.event == SDL_WINDOWEVENT_LEAVE) active = true; */ if (event.window.event == SDL_WINDOWEVENT_MINIMIZED) active = false; if (event.window.event == SDL_WINDOWEVENT_RESTORED) active = true; bool newFocus = focus; if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) newFocus = false; if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) newFocus = true; if (focus != newFocus) { focus = newFocus; #if HANDLE_FOCUS_LOST if (focus) focusAcquired(); log::messageln("focus: %d", (int)focus); Event ev(focus ? Stage::ACTIVATE : Stage::DEACTIVATE); if (stage) stage->dispatchEvent(&ev); if (!focus) focusLost(); #endif } //log::messageln("SDL_SYSWMEVENT %d", (int)event.window.event); break; } case SDL_MOUSEWHEEL: input->sendPointerWheelEvent(stage, event.wheel.y, &input->_pointerMouse); break; case SDL_KEYDOWN: { KeyEvent ev(KeyEvent::KEY_DOWN, &event.key); stage->dispatchEvent(&ev); } break; case SDL_KEYUP: { KeyEvent ev(KeyEvent::KEY_UP, &event.key); stage->dispatchEvent(&ev); } break; #if SDL_VIDEO_OPENGL case SDL_MOUSEMOTION: input->sendPointerMotionEvent(stage, (float)event.motion.x, (float)event.motion.y, 1.0f, &input->_pointerMouse); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { MouseButton b = MouseButton_Left; switch (event.button.button) { case 1: b = MouseButton_Left; break; case 2: b = MouseButton_Middle; break; case 3: b = MouseButton_Right; break; } input->sendPointerButtonEvent(stage, b, (float)event.button.x, (float)event.button.y, 1.0f, event.type == SDL_MOUSEBUTTONDOWN ? TouchEvent::TOUCH_DOWN : TouchEvent::TOUCH_UP, &input->_pointerMouse); } break; #else case SDL_FINGERMOTION: { //log::messageln("SDL_FINGERMOTION"); Vector2 pos = convertTouch(event); input->sendPointerMotionEvent(stage, pos.x, pos.y, event.tfinger.pressure, input->getTouchByID((int)event.tfinger.fingerId)); } break; case SDL_FINGERDOWN: case SDL_FINGERUP: { //log::messageln("SDL_FINGER"); Vector2 pos = convertTouch(event); input->sendPointerButtonEvent(stage, MouseButton_Touch, pos.x, pos.y, event.tfinger.pressure, event.type == SDL_FINGERDOWN ? TouchEvent::TOUCH_DOWN : TouchEvent::TOUCH_UP, input->getTouchByID((int)event.tfinger.fingerId)); } break; #endif } }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { Engine::Init(); Input input; input.Init(); Window window; window.Init(800, 600, "killerg2d"); ResMgr resmgr; resmgr.Init(); FrameRate framerate; framerate.Init(600); Timer timer; timer.Init(); SpiritAnimate spirit; spirit.Init("abc.txt"); int x = 100, y = 100; int model = 0; while( !input.IsKeyDown(SDLK_ESCAPE) ) { timer.Update(); input.Update(); if( input.IsKeyDown(SDLK_LEFT) ) x-=1; if( input.IsKeyDown(SDLK_RIGHT) ) x+=1; if( input.IsKeyDown(SDLK_UP) ) y-=1; if( input.IsKeyDown(SDLK_DOWN) ) y+=1; if( input.IsKeyDown(SDLK_x) ) spirit.Play(); if( input.IsKeyDown(SDLK_y) ) spirit.Stop(); spirit.Update(timer.GetIntervalF()); window.Clear(); spirit.Draw(&window, x, y); window.Flush(); framerate.WaitFrame(); } timer.Destroy(); framerate.Destroy(); resmgr.Destroy(); window.Destroy(); input.Destroy(); Engine::Destroy(); }
static pair_t peek( Input& in, const std::size_t o = 0 ) noexcept( noexcept( in.Input::peek_char( 0 ) ) ) { return { in.peek_char( o ), 1 }; }
bool Input::operator< (const Input & rhs) const { return getDataNum() < rhs.getDataNum(); }
void Game::mainLoop() { Input input; bool running = true; SDL_Event event; units::MS previous_time = SDL_GetTicks(); creation_countdown_ = 1500 + rand() % 250; while (running) { { // Collect input input.beginFrame(); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; } if (event.type == SDL_KEYDOWN && event.key.repeat == false) { input.keyDown(event.key); } else if (event.type == SDL_KEYUP) { input.keyUp(event.key); } } } { // Handle input if (input.wasKeyPressed(SDL_SCANCODE_ESCAPE)) { running = false; } const float kMoveAmount = 0.2f; if (input.isKeyHeld(SDL_SCANCODE_W)) { camera_.translateForward(kMoveAmount); } else if (input.isKeyHeld(SDL_SCANCODE_S)) { camera_.translateForward(-kMoveAmount); } if (input.isKeyHeld(SDL_SCANCODE_A)) { camera_.translateStrafe(-kMoveAmount); } else if (input.isKeyHeld(SDL_SCANCODE_D)) { camera_.translateStrafe(kMoveAmount); } const float kAngle = 5.0f; if (input.isKeyHeld(SDL_SCANCODE_LEFT)) { camera_.rotateYaw(kAngle); } else if (input.isKeyHeld(SDL_SCANCODE_RIGHT)) { camera_.rotateYaw(-kAngle); } if (input.isKeyHeld(SDL_SCANCODE_UP)) { camera_.rotatePitch(-kAngle); } else if (input.isKeyHeld(SDL_SCANCODE_DOWN)) { camera_.rotatePitch(kAngle); } if (input.wasKeyPressed(SDL_SCANCODE_P)) { std::cout << "Objects: " << game_objects_.size() << std::endl; std::cout << "Captures: " << score_ << std::endl; std::cout << "FPS: " << fps_ << std::endl; } } { const units::MS current_time = SDL_GetTicks(); const units::MS dt = current_time - previous_time; step(dt); previous_time = current_time; fps_ = 1000.0f / dt; } { draw(); engine_.swapWindow(); } SDL_Delay(5); } }
void IdenticalCodeFolding::foldIdenticalCode() { // 1. Find folding candidates. FoldingCandidates candidate_list; findCandidates(candidate_list); // 2. Initialize constant section content for (size_t i = 0; i < candidate_list.size(); ++i) { candidate_list[i].initConstantContent(m_Backend, m_KeptSections); } // 3. Find identical code until convergence bool converged = false; size_t iterations = 0; while (!converged && (iterations < m_Config.options().getICFIterations())) { converged = matchCandidates(candidate_list); ++iterations; } if (m_Config.options().printICFSections()) { debug(diag::debug_icf_iterations) << iterations; } // 4. Fold the identical code typedef std::set<Input*> FoldedObjects; FoldedObjects folded_objs; KeptSections::iterator kept, keptEnd = m_KeptSections.end(); size_t index = 0; for (kept = m_KeptSections.begin(); kept != keptEnd; ++kept, ++index) { LDSection* sect = (*kept).first; Input* obj = (*kept).second.first; size_t kept_index = (*kept).second.second; if (index != kept_index) { sect->setKind(LDFileFormat::Folded); folded_objs.insert(obj); if (m_Config.options().printICFSections()) { KeptSections::iterator it = m_KeptSections.begin() + kept_index; LDSection* kept_sect = (*it).first; Input* kept_obj = (*it).second.first; debug(diag::debug_icf_folded_section) << sect->name() << obj->name() << kept_sect->name() << kept_obj->name(); } } } // Adjust the fragment reference of the folded symbols. FoldedObjects::iterator fobj, fobjEnd = folded_objs.end(); for (fobj = folded_objs.begin(); fobj != fobjEnd; ++fobj) { LDContext::sym_iterator sym, symEnd = (*fobj)->context()->symTabEnd(); for (sym = (*fobj)->context()->symTabBegin(); sym != symEnd; ++sym) { if ((*sym)->hasFragRef() && ((*sym)->type() == ResolveInfo::Function)) { LDSymbol* out_sym = (*sym)->resolveInfo()->outSymbol(); FragmentRef* frag_ref = out_sym->fragRef(); LDSection* sect = &(frag_ref->frag()->getParent()->getSection()); if (sect->kind() == LDFileFormat::Folded) { size_t kept_index = m_KeptSections[sect].second; LDSection* kept_sect = (*(m_KeptSections.begin() + kept_index)).first; frag_ref->assign(kept_sect->getSectionData()->front(), frag_ref->offset()); } } } // for each symbol } // for each folded object }
static void apply( const Input& in, std::string& v ) { v = in.string(); }
static int do_gui(const std::vector<Widget *>& widgets, unsigned int selected) { ResourceManager& rm = ResourceManager::getInstance(); ALLEGRO_BITMAP *bg = (ALLEGRO_BITMAP *)rm.getData(RES_BACKGROUND); Input *input = (Input *)rm.getData(RES_INPUT); ALLEGRO_BITMAP *logo = (ALLEGRO_BITMAP *)rm.getData(RES_LOGO); int lw = al_get_bitmap_width(logo); int lh = al_get_bitmap_height(logo); #ifndef ALLEGRO_IPHONE ALLEGRO_FONT *myfont = (ALLEGRO_FONT *)rm.getData(RES_SMALLFONT); #endif bool redraw = true; for (;;) { /* Catch close button presses */ ALLEGRO_EVENT_QUEUE *events = ((DisplayResource *)rm.getResource(RES_DISPLAY))->getEventQueue(); while (!al_is_event_queue_empty(events)) { ALLEGRO_EVENT event; al_get_next_event(events, &event); #ifdef ALLEGRO_IPHONE if (event.type == ALLEGRO_EVENT_DISPLAY_HALT_DRAWING || event.type == ALLEGRO_EVENT_DISPLAY_SWITCH_OUT) { switch_game_out(event.type == ALLEGRO_EVENT_DISPLAY_HALT_DRAWING); } else if (event.type == ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING || event.type == ALLEGRO_EVENT_DISPLAY_SWITCH_IN) { switch_game_in(); } #else if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) exit(0); #endif } input->poll(); #if defined ALLEGRO_IPHONE float ud; if (is_joypad_connected()) { ud = input->ud(); } else { ud = input->lr(); } #else float ud = input->ud(); #endif if (ud < 0 && selected) { selected--; my_play_sample(RES_FIRELARGE); al_rest(0.200); } else if (ud > 0 && selected < (widgets.size()-1)) { selected++; my_play_sample(RES_FIRELARGE); al_rest(0.200); } if (input->b1()) { if (!widgets[selected]->activate()) return selected; } #ifndef ALLEGRO_IPHONE if (input->esc()) return -1; #endif redraw = true; #ifdef ALLEGRO_IPHONE if (switched_out) { redraw = false; } #endif al_rest(0.010); if (!redraw) { continue; } al_clear_to_color(al_map_rgb_f(0, 0, 0)); /* draw */ float h = al_get_bitmap_height(bg); float w = al_get_bitmap_width(bg); al_draw_bitmap(bg, (BB_W-w)/2, (BB_H-h)/2, 0); al_draw_bitmap(logo, (BB_W-lw)/2, (BB_H-lh)/4, 0); al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA); #ifndef ALLEGRO_IPHONE al_draw_textf(myfont, al_map_rgb(255, 255, 0), BB_W/2, BB_H/2, ALLEGRO_ALIGN_CENTRE, "z/y to start"); #endif al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA); for (unsigned int i = 0; i < widgets.size(); i++) { widgets[i]->render(i == selected); } #ifdef ALLEGRO_IPHONE input->draw(); #endif al_flip_display(); } }
[[nodiscard]] static bool match( Input& in ) noexcept { static_assert( noexcept( in.discard() ) ); in.discard(); return true; }
void do_highscores(int score) { read_scores(); ResourceManager& rm = ResourceManager::getInstance(); Input *input = (Input *)rm.getData(RES_INPUT); ALLEGRO_FONT *sm_font = (ALLEGRO_FONT *)rm.getData(RES_SMALLFONT); ALLEGRO_FONT *big_font = (ALLEGRO_FONT *)rm.getData(RES_LARGEFONT); bool is_high = score >= highScores[NUM_SCORES-1].score; bool entering = is_high; double bail_time = al_get_time() + 8; int letter_num = 0; char name[4] = " "; int character = 0; double next_input = al_get_time(); double spin_start = 0; int spin_dir = 1; for (;;) { /* Catch close button presses */ ALLEGRO_EVENT_QUEUE *events = ((DisplayResource *)rm.getResource(RES_DISPLAY))->getEventQueue(); while (!al_is_event_queue_empty(events)) { ALLEGRO_EVENT event; al_get_next_event(events, &event); #ifdef ALLEGRO_IPHONE if (event.type == ALLEGRO_EVENT_DISPLAY_HALT_DRAWING || event.type == ALLEGRO_EVENT_DISPLAY_SWITCH_OUT) { switch_game_out(event.type == ALLEGRO_EVENT_DISPLAY_HALT_DRAWING); } else if (event.type == ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING || event.type == ALLEGRO_EVENT_DISPLAY_SWITCH_IN) { switch_game_in(); } #else if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) exit(0); #endif } input->poll(); if (entering && al_get_time() > next_input) { float lr = input->lr(); if (lr != 0) { if (lr < 0) { character--; if (character < 0) character = 25; spin_dir = 1; } else if (lr > 0) { character++; if (character >= 26) character = 0; spin_dir = -1; } next_input = al_get_time()+0.2; my_play_sample(RES_FIRESMALL); spin_start = al_get_time(); } if (input->b1() && letter_num < 3) { name[letter_num] = 'A' + character; letter_num++; if (letter_num >= 3) { entering = false; bail_time = al_get_time()+8; insert_score(name, score); write_scores(); } next_input = al_get_time()+0.2; my_play_sample(RES_FIRELARGE); } } else if (!entering) { if (al_get_time() > bail_time) { return; } else if (input->b1() && al_get_time() > next_input) { al_rest(0.250); return; } } al_rest(0.010); #ifdef ALLEGRO_IPHONE if (switched_out) { continue; } #endif al_clear_to_color(al_map_rgb(0, 0, 0)); if (entering) { float a = ALLEGRO_PI*3/2; float ainc = ALLEGRO_PI*2 / 26; double elapsed = al_get_time() - spin_start; if (elapsed < 0.1) { a += (elapsed / 0.1) * ainc * spin_dir; } float scrh = BB_H / 2 - 32; float h = al_get_font_line_height(sm_font); for (int i = 0; i < 26; i++) { int c = character + i; if (c >= 26) c -= 26; char s[2]; s[1] = 0; s[0] = 'A' + c; int x = BB_W/2 + (cos(a) * scrh) - al_get_text_width(sm_font, s); int y = BB_H/2 + (sin(a) * scrh) - h/2; al_draw_textf(sm_font, i == 0 ? al_map_rgb(255, 255, 0) : al_map_rgb(200, 200, 200), x, y, 0, "%s", s); a += ainc; } char tmp[4] = { 0, }; for (int i = 0; i < 3 && name[i] != ' '; i++) { tmp[i] = name[i]; } al_draw_textf(big_font, al_map_rgb(0, 255, 0), BB_W/2, BB_H/2-20, ALLEGRO_ALIGN_CENTRE, "%s", tmp); al_draw_text(sm_font, al_map_rgb(200, 200, 200), BB_W/2, BB_H/2-20+5+al_get_font_line_height(big_font), ALLEGRO_ALIGN_CENTRE, "high score!"); } else { int yy = BB_H/2 - al_get_font_line_height(big_font)*NUM_SCORES/2; for (int i = 0; i < NUM_SCORES; i++) { al_draw_textf(big_font, al_map_rgb(255, 255, 255), BB_W/2-10, yy, ALLEGRO_ALIGN_RIGHT, "%s", highScores[i].name); al_draw_textf(big_font, al_map_rgb(255, 255, 0), BB_W/2+10, yy, ALLEGRO_ALIGN_LEFT, "%d", highScores[i].score); yy += al_get_font_line_height(big_font); } } #ifdef ALLEGRO_IPHONE input->draw(); #endif al_flip_display(); } }
int main(int argc, char *argv[]) { FILE* fp = fopen("config.txt", "r"); if (fp) { int a, b; if (fscanf(fp," cores %d", &a) == 1) plotter.n_threads = a; if (fscanf(fp," def_res %d %d", &a, &b) == 2) { gfx.screen_w_default = a; gfx.screen_h_default = b; } if (fscanf(fp," max_iter %d", &a) == 1) plotter.max_iter = a; } if (SDL_Init(SDL_INIT_EVERYTHING) == -1 || !gfx.init()) return 1; plotter.init(); plotter.resize(gfx.get_screen_w(), gfx.get_screen_h()); plotter.plot(); while (true) { frame_time = SDL_GetTicks(); input.update(); if (input.key_pressed(SDLK_ESCAPE) || input.is_quitting()) break; if (input.key_down( SDLK_LCTRL ) && input.mouse_pressed(SDL_BUTTON_LEFT)) { plotter.center(); } else if (input.mouse_pressed(SDL_BUTTON_LEFT)) { if (input.key_down(SDLK_LSHIFT)) { plotter.zoom(zoom_factor * 5); } else { plotter.zoom(zoom_factor); } } else if (input.mouse_pressed(SDL_BUTTON_RIGHT)) { if (input.key_down(SDLK_LSHIFT)) { plotter.zoom(1/(zoom_factor * 5)); } else { plotter.zoom(1/zoom_factor); } } if (input.key_pressed(SDLK_f)) { plotter.end_plotting(); gfx.toggle_fullscreen(); plotter.resize(gfx.get_screen_w(), gfx.get_screen_h()); plotter.plot(); //zoom_on(); } if (input.key_pressed(SDLK_p)) { plotter.print_pos(); } gfx.update(); int time_rem = 1000 / FPS - (SDL_GetTicks() - frame_time); if (time_rem >= 5) SDL_Delay(time_rem); } plotter.end_plotting(); SDL_Quit(); return 0; }
bool VertexProgram_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; VertexProgram& vertexProgram = static_cast<VertexProgram&>(obj); if (fr[0].matchWord("ProgramLocalParameter")) { int index; Vec4 vec; fr[1].getInt(index); fr[2].getFloat(vec[0]); fr[3].getFloat(vec[1]); fr[4].getFloat(vec[2]); fr[5].getFloat(vec[3]); fr += 6; iteratorAdvanced = true; vertexProgram.setProgramLocalParameter(index, vec); } if (fr[0].matchWord("Matrix")) { int index; fr[1].getInt(index); fr += 2; osg::Matrix matrix; if (readMatrix(matrix,fr)) { vertexProgram.setMatrix(index, matrix); } iteratorAdvanced = true; } if (fr.matchSequence("code {")) { std::string code; fr += 2; iteratorAdvanced = true; int entry = fr[0].getNoNestedBrackets(); while (!fr.eof() && fr[0].getNoNestedBrackets() >= entry) { if (fr[0].getStr()) { code.append(std::string(fr[0].getStr())); code += '\n'; } ++fr; } vertexProgram.setVertexProgram(code); } if( fr.matchSequence("file %s")) { std::string filename = fr[1].getStr(); fr+=2; iteratorAdvanced = true; osgDB::ifstream vfstream( filename.c_str() ); if( vfstream ) { ostringstream vstream; char ch; /* xxx better way to transfer a ifstream to a string?? */ while( vfstream.get(ch)) vstream.put(ch); vertexProgram.setVertexProgram( vstream.str() ); } } return iteratorAdvanced; }
bool StateSet_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; // note, StateSet replaced GeoState April 2001. StateSet& stateset = static_cast<StateSet&>(obj); // read the rendering hint value. if (fr[0].matchWord("rendering_hint")) { if (fr[1].matchWord("DEFAULT_BIN")) { stateset.setRenderingHint(StateSet::DEFAULT_BIN); fr+=2; iteratorAdvanced = true; } else if (fr[1].matchWord("OPAQUE_BIN")) { stateset.setRenderingHint(StateSet::OPAQUE_BIN); fr+=2; iteratorAdvanced = true; } else if (fr[1].matchWord("TRANSPARENT_BIN")) { stateset.setRenderingHint(StateSet::TRANSPARENT_BIN); fr+=2; iteratorAdvanced = true; } else if (fr[1].isInt()) { int value; fr[1].getInt(value); stateset.setRenderingHint(value); fr+=2; iteratorAdvanced = true; } } bool setRenderBinDetails=false; StateSet::RenderBinMode rbmode = stateset.getRenderBinMode(); if (fr[0].matchWord("renderBinMode") && StateSet_matchRenderBinModeStr(fr[1].getStr(),rbmode)) { setRenderBinDetails=true; fr+=2; iteratorAdvanced = true; } int binNumber = stateset.getBinNumber(); if (fr[0].matchWord("binNumber") && fr[1].getInt(binNumber)) { setRenderBinDetails=true; fr+=2; iteratorAdvanced = true; } std::string binName = stateset.getBinName(); if (fr[0].matchWord("binName")) { setRenderBinDetails=true; binName = fr[1].getStr(); fr+=2; iteratorAdvanced = true; } if (setRenderBinDetails) { stateset.setRenderBinDetails(binNumber,binName,rbmode); } while (fr.matchSequence("UpdateCallback {")) { // int entry = fr[0].getNoNestedBrackets(); fr += 2; StateSet::Callback* callback = fr.readObjectOfType<StateSet::Callback>(); if (callback) { stateset.setUpdateCallback(callback); } iteratorAdvanced = true; } while (fr.matchSequence("EventCallback {")) { //int entry = fr[0].getNoNestedBrackets(); fr += 2; StateSet::Callback* callback = fr.readObjectOfType<StateSet::Callback>(); if (callback) { stateset.setEventCallback(callback); } iteratorAdvanced = true; } bool readingMode = true; StateAttribute::GLModeValue value; while (readingMode) { readingMode=false; if (fr[0].isInt()) { if (StateSet_matchModeStr(fr[1].getStr(),value)) { int mode; fr[0].getInt(mode); if (s_ModesAndNames.isTextureMode(mode)) { // remap to a texture unit. stateset.setTextureMode(0,(StateAttribute::GLMode)mode,value); } else { stateset.setMode((StateAttribute::GLMode)mode,value); } fr+=2; iteratorAdvanced = true; readingMode=true; } } else if (fr[0].getStr()) { if (StateSet_matchModeStr(fr[1].getStr(),value)) { StateAttribute::GLMode mode=0; if (s_ModesAndNames.getGLModeForName(fr[0].getStr(), mode)) { if (s_ModesAndNames.isTextureMode(mode)) { // remap to a texture unit. stateset.setTextureMode(0,mode,value); } else { stateset.setMode(mode,value); } fr+=2; iteratorAdvanced = true; readingMode=true; } } } } // new code using osg::Registry's list of prototypes to loaded attributes. Uniform* uniform = NULL; while((uniform=fr.readUniform())!=NULL) { stateset.addUniform(uniform); iteratorAdvanced = true; } // new code using osg::Registry's list of prototypes to loaded attributes. StateAttribute* attribute = NULL; while((attribute=fr.readStateAttribute())!=NULL) { if (attribute->isTextureAttribute()) { // remap to be a texture attribute stateset.setTextureAttribute(0,attribute); } else { stateset.setAttribute(attribute); } iteratorAdvanced = true; } while(fr.matchSequence("textureUnit %i {")) { int entry = fr[0].getNoNestedBrackets(); unsigned int unit=0; fr[1].getUInt(unit); fr+=3; while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { bool localIteratorAdvanced = false; bool readingMode = true; StateAttribute::GLModeValue value; while (readingMode) { readingMode=false; if (fr[0].isInt()) { if (StateSet_matchModeStr(fr[1].getStr(),value)) { int mode; fr[0].getInt(mode); stateset.setTextureMode(unit,(StateAttribute::GLMode)mode,value); fr+=2; localIteratorAdvanced = true; readingMode=true; } } else if (fr[0].getStr()) { if (StateSet_matchModeStr(fr[1].getStr(),value)) { StateAttribute::GLMode mode=0; if (s_ModesAndNames.getGLModeForName(fr[0].getStr(), mode)) { stateset.setTextureMode(unit,mode,value); fr+=2; localIteratorAdvanced = true; readingMode=true; } } } } StateAttribute* attribute = NULL; while((attribute=fr.readStateAttribute())!=NULL) { stateset.setTextureAttribute(unit,attribute); localIteratorAdvanced = true; } if (!localIteratorAdvanced) fr.advanceOverCurrentFieldOrBlock(); } // skip over trailing '}' ++fr; iteratorAdvanced = true; } return iteratorAdvanced; }
static void apply( const Input& in, std::string& s ) { s.append( in.begin(), in.size() ); }
bool PagedLOD_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; PagedLOD& lod = static_cast<PagedLOD&>(obj); std::string databasePath; if (fr.read("DatabasePath",databasePath)) { lod.setDatabasePath(databasePath); } else { if (lod.getDatabasePath().empty() && fr.getOptions() && !fr.getOptions()->getDatabasePathList().empty()) { const std::string& path = fr.getOptions()->getDatabasePathList().front(); if (!path.empty()) { lod.setDatabasePath(path); } } } unsigned int num; if (fr[0].matchWord("NumChildrenThatCannotBeExpired") && fr[1].getUInt(num)) { lod.setNumChildrenThatCannotBeExpired(num); fr+=2; iteratorAdvanced = true; } bool flag; if (fr.read("DisableExternalChildrenPaging", flag)) { lod.setDisableExternalChildrenPaging(flag); iteratorAdvanced = true; } bool matchFirst; if ((matchFirst=fr.matchSequence("FileNameList {")) || fr.matchSequence("FileNameList %i {")) { // set up coordinates. int entry = fr[0].getNoNestedBrackets(); if (matchFirst) { fr += 2; } else { fr += 3; } unsigned int i=0; while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { if (fr[0].isString() || fr[0].isQuotedString()) { if (fr[0].getStr()) lod.setFileName(i,fr[0].getStr()); else lod.setFileName(i,""); ++fr; ++i; } else { ++fr; } } iteratorAdvanced = true; ++fr; } int num_children; if (fr[0].matchWord("num_children") && fr[1].getInt(num_children)) { // could allocate space for children here... fr+=2; iteratorAdvanced = true; } Node* node = NULL; while((node=fr.readNode())!=NULL) { lod.addChild(node); iteratorAdvanced = true; } return iteratorAdvanced; }
static void apply( const Input& in, std::string& s ) { assert( in.size() == 1 ); s += apply_one( in, static_cast< const T* >( nullptr ) ); }
int main ( int argc, char** argv ) { /// initialisation son & image /// initialisation FMOD FMOD_SYSTEM * system; FMOD_System_Create(&system); /// initialisation image & son initialisation(system); /// verification de la date struct tm Today; time_t maintenant; time(&maintenant); Today = *localtime(&maintenant); Today.tm_year += 1900; Today.tm_mon += 1; Today.tm_mday; /// username DWORD StrLen = 256; TCHAR SysInfoStr[256]; GetComputerName(SysInfoStr, &StrLen); std::string nameComputeur = SysInfoStr; GetUserName(SysInfoStr, &StrLen); std::string nameUser = SysInfoStr; /// déclaration et chargements des ressources /// create a new window putenv("SDL_VIDEO_WINDOW_POS=center"); /// pour centrer la fenêtre SDL_Surface* screen = SDL_SetVideoMode(LARGEUR_ECRAN, HAUTEUR_ECRAN, 32, SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_RESIZABLE|SDL_FULLSCREEN); if ( !screen ) { printf("Unable to set 640x480 video: %s\n", SDL_GetError()); return 1; } /// images SDL_Surface** images = NULL; images = (SDL_Surface **) malloc (sizeof(SDL_Surface*)*NOMBRE_IMAGE); load_images(images); /// sons FMOD_SOUND ** musiques = NULL; musiques = (FMOD_SOUND **) malloc (sizeof(FMOD_SOUND*)*NOMBRE_MUSIQUE); load_musiques(system, musiques); /// polices TTF_Font ** polices = NULL; polices = (TTF_Font **) malloc(sizeof(TTF_Font*) * NOMBRE_POLICE); load_polices(polices); /// Icone SDL_WM_SetIcon(images[0], NULL); /// titre SDL_WM_SetCaption("Julie", NULL); /// program main loop Input * in = new Input; int tempsPrecedent = 0, tempsActuel = 0; int ghost = 255; bool devient_ghost = true; int * menu = new int; *menu = -1; SDL_Rect place = {LARGEUR_ECRAN/2 - images[0]->w/2,HAUTEUR_ECRAN/2 - images[0]->h/2,0,0}; /// musiques FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, musiques[0], 0, NULL); /// affichage du logo int i = 0; while(i<256) { SDL_FillRect(SDL_GetVideoSurface(), 0, SDL_MapRGB(SDL_GetVideoSurface()->format, 0, 0, 0)); place = {LARGEUR_ECRAN/2 - images[0]->w/2,HAUTEUR_ECRAN/2 - images[0]->h/2,0,0}; SDL_SetAlpha(images[0], SDL_SRCALPHA, i); SDL_BlitSurface(images[0], NULL, SDL_GetVideoSurface(), &place); i++; SDL_Flip(SDL_GetVideoSurface()); } while(i>=0) { SDL_FillRect(SDL_GetVideoSurface(), 0, SDL_MapRGB(SDL_GetVideoSurface()->format, 0, 0, 0)); place = {LARGEUR_ECRAN/2 - images[0]->w/2,HAUTEUR_ECRAN/2 - images[0]->h/2,0,0}; SDL_SetAlpha(images[0], SDL_SRCALPHA, i); SDL_BlitSurface(images[0], NULL, SDL_GetVideoSurface(), &place); i--; SDL_Flip(SDL_GetVideoSurface()); } place = {LARGEUR_ECRAN/2 - images[1]->w/2,HAUTEUR_ECRAN/2 - images[1]->h/2,0,0}; while(!in->get_touche(SDLK_ESCAPE) && !in->get_exit()) /// boucle principale { /// mise à jour des events in->update(); /// gestion du frame fps(&tempsPrecedent, &tempsActuel, SCREEN_REFRESH); /// resize taille écran resize_screen(*in); if(*menu == 1 || in->get_touche(SDLK_1) || in->get_touche(SDLK_KP1)) /// jouer { in->set_touche(SDLK_1, 0); in->set_touche(SDLK_KP1, 0); Jeu * party = new Jeu(images); party->game(); delete party; in->set_touche(SDLK_ESCAPE, 0); } if(*menu == 2 || in->get_touche(SDLK_2) || in->get_touche(SDLK_KP2)) /// jouer { in->set_touche(SDLK_2, 0); in->set_touche(SDLK_KP2, 0); Jeu * party = new Jeu(images); party->conjugaison(); delete party; in->set_touche(SDLK_ESCAPE, 0); } if(*menu == -9) /// quitter le jeu { in->set_exit(1); } if(*menu == -1) { SDL_FillRect(SDL_GetVideoSurface(), 0, SDL_MapRGB(SDL_GetVideoSurface()->format, 0, 0, 0)); place = {LARGEUR_ECRAN/2 - images[1]->w/2,HAUTEUR_ECRAN/2 - images[1]->h/2,0,0}; SDL_BlitSurface(images[1], NULL, SDL_GetVideoSurface(), &place); /* if(devient_ghost) { ghost -= 8; } else { ghost += 8; } if(ghost >= 255 || ghost <= 88) { devient_ghost = !devient_ghost; } place = {LARGEUR_ECRAN/2 - images[2]->w/2,3*HAUTEUR_ECRAN/4 - images[2]->h/2,0,0}; SDL_SetAlpha(images[2], SDL_SRCALPHA, ghost); SDL_BlitSurface(images[2], NULL, SDL_GetVideoSurface(), &place); */ Texte menu1; Texte menu2; menu1.print("1 - Mathématiques", "arial", 60, {255,255,255}, SDL_GetVideoSurface()->w/3, 3*SDL_GetVideoSurface()->h/4); menu2.print("2 - Conjugaison", "arial", 60, {255,255,255}, SDL_GetVideoSurface()->w/3, 3*SDL_GetVideoSurface()->h/4+100); } SDL_Flip(screen); }/// end main loop /// nettoyage /// free pointeurs delete menu; delete in; /// free loaded bitmap and created surface SDL_FreeSurface(screen); free_images(images); free_polices(polices); /// libération des sons free_musiques(musiques); /// fermeture propre de ce qui est ouvert dans initialisation() fermeture(system); /// all is well ;) printf("Exited cleanly\n"); return 0; }
static void apply( const Input& in, std::string& s ) { assert( !in.empty() ); // First character MUST be present, usually 'x'. s += unhex_string< char >( in.begin() + 1, in.end() ); }
END_TEST START_TEST (test_QualExtension_create_add_and_write_L3V1V1) { const char* s1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" xmlns:qual=\"http://www.sbml.org/sbml/level3/version1/qual/version1\" level=\"3\" version=\"1\" qual:required=\"true\">\n" " <model>\n" " <listOfCompartments>\n" " <compartment id=\"c\" constant=\"true\"/>\n" " </listOfCompartments>\n" " <qual:listOfQualitativeSpecies>\n" " <qual:qualitativeSpecies metaid=\"ddd\" qual:id=\"s1\" qual:compartment=\"c\" qual:constant=\"false\" qual:name=\"sss\" qual:initialLevel=\"1\" qual:maxLevel=\"4\"/>\n" " </qual:listOfQualitativeSpecies>\n" " <qual:listOfTransitions>\n" " <qual:transition sboTerm=\"SBO:0000001\" qual:id=\"d\">\n" " <qual:listOfInputs>\n" " <qual:input qual:id=\"RD\" qual:qualitativeSpecies=\"s1\" qual:transitionEffect=\"none\" qual:name=\"aa\" qual:sign=\"negative\" qual:thresholdLevel=\"2\"/>\n" " </qual:listOfInputs>\n" " <qual:listOfOutputs>\n" " <qual:output qual:id=\"wd\" qual:qualitativeSpecies=\"s1\" qual:transitionEffect=\"production\" qual:name=\"aa\" qual:outputLevel=\"2\"/>\n" " </qual:listOfOutputs>\n" " <qual:listOfFunctionTerms>\n" " <qual:defaultTerm qual:resultLevel=\"1\"/>\n" " <qual:functionTerm qual:resultLevel=\"2\">\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <geq/>\n" " <ci> s1 </ci>\n" " <cn type=\"integer\"> 2 </cn>\n" " </apply>\n" " </math>\n" " </qual:functionTerm>\n" " </qual:listOfFunctionTerms>\n" " </qual:transition>\n" " </qual:listOfTransitions>\n" " </model>\n" "</sbml>\n" ; QualPkgNamespaces *sbmlns = new QualPkgNamespaces(3,1,1); // create the document SBMLDocument *document = new SBMLDocument(sbmlns); //// mark qual as required document->setPackageRequired("qual", true); // create the Model Model* model= new Model(sbmlns); // create the Compartment Compartment* compartment = new Compartment(sbmlns); compartment->setId("c"); compartment->setConstant(true); fail_unless(model->addCompartment(compartment) == LIBSBML_OPERATION_SUCCESS); //// create the QualitativeSpecies QualModelPlugin* mplugin = static_cast<QualModelPlugin*>(model->getPlugin("qual")); fail_unless(mplugin != NULL); QualitativeSpecies* qs = new QualitativeSpecies(sbmlns); fail_unless(qs->setId("s1") == LIBSBML_OPERATION_SUCCESS); fail_unless(qs->setCompartment("c") == LIBSBML_OPERATION_SUCCESS); fail_unless(qs->setConstant(false) == LIBSBML_OPERATION_SUCCESS); fail_unless(qs->setInitialLevel(1) == LIBSBML_OPERATION_SUCCESS); fail_unless(qs->setMaxLevel(4) == LIBSBML_OPERATION_SUCCESS); fail_unless(qs->setName("sss") == LIBSBML_OPERATION_SUCCESS); fail_unless(qs->setMetaId("ddd") == LIBSBML_OPERATION_SUCCESS); fail_unless(mplugin->addQualitativeSpecies(qs) == LIBSBML_OPERATION_SUCCESS); Transition* t = new Transition(sbmlns); fail_unless(t->setId("d") == LIBSBML_OPERATION_SUCCESS); fail_unless(t->setSBOTerm(1) == LIBSBML_OPERATION_SUCCESS); Input* i = new Input(sbmlns); fail_unless(i->setId("RD") == LIBSBML_OPERATION_SUCCESS); fail_unless(i->setQualitativeSpecies("s1") == LIBSBML_OPERATION_SUCCESS); fail_unless(i->setTransitionEffect (InputTransitionEffect_fromString("none")) == LIBSBML_OPERATION_SUCCESS); fail_unless(i->setSign(InputSign_fromString("negative")) == LIBSBML_OPERATION_SUCCESS); fail_unless(i->setThresholdLevel(2) == LIBSBML_OPERATION_SUCCESS); fail_unless(i->setName("aa") == LIBSBML_OPERATION_SUCCESS); fail_unless(t->addInput(i) == LIBSBML_OPERATION_SUCCESS); Output* o = new Output(sbmlns); fail_unless(o->setId("wd") == LIBSBML_OPERATION_SUCCESS); fail_unless(o->setQualitativeSpecies("s1") == LIBSBML_OPERATION_SUCCESS); fail_unless(o->setTransitionEffect (OutputTransitionEffect_fromString("production")) == LIBSBML_OPERATION_SUCCESS); fail_unless(o->setOutputLevel(2) == LIBSBML_OPERATION_SUCCESS); fail_unless(o->setName("aa") == LIBSBML_OPERATION_SUCCESS); fail_unless(t->addOutput(o) == LIBSBML_OPERATION_SUCCESS); FunctionTerm* ft = new FunctionTerm(sbmlns); ASTNode* math = SBML_parseL3Formula("geq(s1, 2)"); fail_unless(ft->setResultLevel(2) == LIBSBML_OPERATION_SUCCESS); fail_unless(ft->setMath(math) == LIBSBML_OPERATION_SUCCESS); fail_unless(t->addFunctionTerm(ft) == LIBSBML_OPERATION_SUCCESS); DefaultTerm* dt = new DefaultTerm(sbmlns); fail_unless(dt->setResultLevel(1) == LIBSBML_OPERATION_SUCCESS); fail_unless(t->setDefaultTerm(dt) == LIBSBML_OPERATION_SUCCESS); fail_unless(mplugin->addTransition(t) == LIBSBML_OPERATION_SUCCESS); fail_unless(document->setModel(model) == LIBSBML_OPERATION_SUCCESS); char *s2 = writeSBMLToString(document); fail_unless(strcmp(s1,s2) == 0); free(s2); delete document; }
// common run state void RunState() { #if defined(USE_SDL) // last ticks unsigned int ticks = SDL_GetTicks(); #elif defined(USE_SFML) // timer sf::Clock timer; // start timer timer.Reset(); #elif defined(USE_GLFW) double prevtime = glfwGetTime(); #endif // input logging TiXmlDocument inputlog(RECORD_CONFIG.c_str()); TiXmlElement *inputlogroot; TiXmlElement *inputlognext; if (playback) { if (!inputlog.LoadFile()) DebugPrint("error loading recording file \"%s\": %s\n", RECORD_CONFIG.c_str(), inputlog.ErrorDesc()); inputlogroot = inputlog.RootElement(); inputlognext = inputlogroot->FirstChildElement(); } else if (record) { inputlogroot = inputlog.LinkEndChild(new TiXmlElement("journal"))->ToElement(); inputlognext = NULL; } else { inputlogroot = NULL; inputlognext = NULL; } #ifdef GET_PERFORMANCE_DETAILS PerfTimer::Init(); PerfTimer control_timer; PerfTimer simulate_timer; PerfTimer collide_timer; PerfTimer update_timer; PerfTimer render_timer; PerfTimer overlay_timer; PerfTimer display_timer; PerfTimer total_timer; total_timer.Stamp(); #endif #ifdef COLLECT_DEBUG_DRAW // create a new draw list GLuint debugdraw = glGenLists(1); #endif // wait for user exit do { #ifdef GET_PERFORMANCE_DETAILS PerfTimer::Next(); control_timer.Clear(); simulate_timer.Clear(); collide_timer.Clear(); update_timer.Clear(); render_timer.Clear(); overlay_timer.Clear(); display_timer.Clear(); total_timer.Clear(); #endif // INPUT PHASE #if defined(USE_SDL) // event handler SDL_Event event; // process events while( SDL_PollEvent( &event ) ) { /* Give the console first dibs on event processing */ if (OGLCONSOLE_SDLEvent(&event)) continue; switch (event.type) { case SDL_KEYDOWN: input.OnPress( Input::TYPE_KEYBOARD, event.key.which, event.key.keysym.sym ); switch (event.key.keysym.sym) { case SDLK_F4: if (event.key.keysym.mod & KMOD_ALT) setgamestate = STATE_QUIT; break; case SDLK_RETURN: if (event.key.keysym.mod & KMOD_ALT) { CloseWindow(); SCREEN_FULLSCREEN = !SCREEN_FULLSCREEN; OpenWindow(); } break; case SDLK_ESCAPE: if (curgamestate == STATE_PLAY) { if (escape) EscapeMenuExit(); else EscapeMenuEnter(); } break; case SDLK_PAUSE: if (event.key.keysym.mod & KMOD_SHIFT) { paused = true; singlestep = true; } else { paused = !paused; } if (paused) Pause(); else Resume(); break; case SDLK_PRINT: Screenshot(); break; } break; case SDL_KEYUP: input.OnRelease( Input::TYPE_KEYBOARD, event.key.which, event.key.keysym.sym ); break; case SDL_MOUSEMOTION: input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 0, float(event.motion.x * 2 - SCREEN_WIDTH) / float(SCREEN_HEIGHT) ); input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 1, float(event.motion.y * 2 - SCREEN_HEIGHT) / float(SCREEN_HEIGHT) ); input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 2, event.motion.xrel / 32.0f ); input.OnAxis( Input::TYPE_MOUSE_AXIS, event.motion.which, 3, event.motion.yrel / 32.0f ); break; case SDL_MOUSEBUTTONDOWN: input.OnPress( Input::TYPE_MOUSE_BUTTON, event.button.which, event.button.button ); break; case SDL_MOUSEBUTTONUP: input.OnRelease( Input::TYPE_MOUSE_BUTTON, event.button.which, event.button.button ); break; case SDL_JOYAXISMOTION: input.OnAxis( Input::TYPE_JOYSTICK_AXIS, event.jaxis.which, event.jaxis.axis, event.jaxis.value / 32767.0f ); break; case SDL_JOYBUTTONDOWN: input.OnPress( Input::TYPE_JOYSTICK_BUTTON, event.jaxis.which, event.jbutton.button ); break; case SDL_JOYBUTTONUP: input.OnRelease( Input::TYPE_JOYSTICK_BUTTON, event.jbutton.which, event.jbutton.button ); break; case SDL_QUIT: setgamestate = STATE_QUIT; break; } } // get loop time in ticks unsigned int nextticks = SDL_GetTicks(); float delta = (nextticks - ticks) / 1000.0f; ticks = nextticks; #elif defined(USE_SFML) sf::Event event; while (window.GetEvent(event)) { /* Give the console first dibs on event processing */ if (OGLCONSOLE_SFMLEvent(&event)) continue; // Some code for stopping application on close or when escape is pressed... switch (event.Type) { case sf::Event::Resized: glViewport(0, 0, event.Size.Width, event.Size.Height); break; case sf::Event::KeyPressed: input.OnPress( Input::TYPE_KEYBOARD, 0, event.Key.Code ); switch(event.Key.Code) { case sf::Key::F4: if (event.Key.Alt) setgamestate = STATE_QUIT; break; case sf::Key::Return: if (event.Key.Alt) { CloseWindow(); SCREEN_FULLSCREEN = !SCREEN_FULLSCREEN; OpenWindow(); } break; case sf::Key::Escape: if (curgamestate == STATE_PLAY) { if (escape) EscapeMenuExit(); else EscapeMenuEnter(); } break; case sf::Key::Pause: if (event.Key.Shift) { paused = true; singlestep = true; } else { paused = !paused; } if (paused) Pause(); else Resume(); break; } break; case sf::Event::KeyReleased: input.OnRelease( Input::TYPE_KEYBOARD, 0, event.Key.Code ); break; case sf::Event::MouseMoved: input.OnAxis( Input::TYPE_MOUSE_AXIS, 0, 0, float(int(event.MouseMove.X) * 2 - SCREEN_WIDTH) / float(SCREEN_HEIGHT) ); input.OnAxis( Input::TYPE_MOUSE_AXIS, 0, 1, float(int(event.MouseMove.Y) * 2 - SCREEN_HEIGHT) / float(SCREEN_HEIGHT) ); break; case sf::Event::MouseButtonPressed: input.OnPress( Input::TYPE_MOUSE_BUTTON, 0, event.MouseButton.Button ); break; case sf::Event::MouseButtonReleased: input.OnRelease( Input::TYPE_MOUSE_BUTTON, 0, event.MouseButton.Button ); break; case sf::Event::JoyMoved: input.OnAxis( Input::TYPE_JOYSTICK_AXIS, event.JoyMove.JoystickId, event.JoyMove.Axis, event.JoyMove.Position / 100.0f ); break; case sf::Event::JoyButtonPressed: input.OnPress( Input::TYPE_JOYSTICK_BUTTON, event.JoyButton.JoystickId, event.JoyButton.Button ); break; case sf::Event::JoyButtonReleased: input.OnRelease( Input::TYPE_JOYSTICK_BUTTON, event.JoyButton.JoystickId, event.JoyButton.Button ); break; case sf::Event::Closed: setgamestate = STATE_QUIT; break; } } // get loop time in ticks float delta = timer.GetElapsedTime(); timer.Reset(); //ticks += delta; #elif defined(USE_GLFW) if (glfwGetJoystickParam(0, GLFW_PRESENT)) { // get joystick axis positions int axiscount = glfwGetJoystickParam(0, GLFW_AXES); float *axis = static_cast<float *>(_alloca(axiscount * sizeof(float))); axiscount = glfwGetJoystickPos(0, axis, axiscount); for (int i = 0; i < axiscount; ++i) input.OnAxis(Input::TYPE_JOYSTICK_AXIS, 0, i, axis[i]); // get joystick button states int buttoncount = glfwGetJoystickParam(0, GLFW_BUTTONS); unsigned char *button = static_cast<unsigned char *>(_alloca(buttoncount * sizeof(unsigned char))); buttoncount = glfwGetJoystickButtons(0, button, buttoncount); for (int i = 0; i < buttoncount; ++i) input.OnAxis(Input::TYPE_JOYSTICK_BUTTON, 0, i, button[i]); } double nexttime = glfwGetTime(); float delta = float(nexttime - prevtime); prevtime = nexttime; #endif // clamp ticks to something sensible // (while debugging, for example) if (delta > 0.1f) delta = 0.1f; // frame time and turns if (singlestep) { // advance 1/60th of a second frame_time = TIME_SCALE / 60.0f; frame_turns = frame_time * sim_rate; } else if (paused || escape) { // freeze time frame_time = 0.0f; frame_turns = 0.0f; } else if (FIXED_STEP) { // advance one simulation step frame_time = TIME_SCALE * sim_step; frame_turns = TIME_SCALE; } else { // advance by frame time frame_time = delta * TIME_SCALE; frame_turns = frame_time * sim_rate; } // turns per motion-blur step float step_turns = std::min(TIME_SCALE * MOTIONBLUR_TIME * sim_rate, 1.0f) / MOTIONBLUR_STEPS; // advance to beginning of motion blur steps sim_fraction += frame_turns; sim_fraction -= MOTIONBLUR_STEPS * step_turns; // for each motion-blur step for (int blur = 0; blur < MOTIONBLUR_STEPS; ++blur) { // clear the screen glClear( GL_COLOR_BUFFER_BIT #ifdef ENABLE_DEPTH_TEST | GL_DEPTH_BUFFER_BIT #endif ); // set projection glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glFrustum( -0.5*VIEW_SIZE*SCREEN_WIDTH/SCREEN_HEIGHT, 0.5*VIEW_SIZE*SCREEN_WIDTH/SCREEN_HEIGHT, 0.5f*VIEW_SIZE, -0.5f*VIEW_SIZE, 256.0f*1.0f, 256.0f*5.0f ); // set base modelview matrix glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslatef( 0.0f, 0.0f, -256.0f ); glScalef( -1.0f, -1.0f, -1.0f ); // advance the sim timer sim_fraction += step_turns; if (escape) { input.Update(); input.Step(); } // while simulation turns to run... else while ((singlestep || !paused) && sim_fraction >= 1.0f) { // deduct a turn sim_fraction -= 1.0f; // advance the turn counter ++sim_turn; // save original fraction float save_fraction = sim_fraction; // switch fraction to simulation mode sim_fraction = 0.0f; #ifdef COLLECT_DEBUG_DRAW // collect any debug draw glNewList(debugdraw, GL_COMPILE); #endif // seed the random number generator Random::Seed(0x92D68CA2 ^ sim_turn); (void)Random::Int(); // update database Database::Update(); if (curgamestate == STATE_PLAY) { if (playback) { // quit if out of turns if (!inputlognext) { setgamestate = STATE_SHELL; break; } // get the next turn value int turn = -1; inputlognext->QueryIntAttribute("turn", &turn); // if the turn matches the simulation turn... if ((unsigned int)turn == sim_turn) { // update the control values input.Playback(inputlognext); // go to the next entry inputlognext = inputlognext->NextSiblingElement(); } } else if (record) { // save original input values float prev[Input::NUM_LOGICAL]; memcpy(prev, input.output, sizeof(prev)); // update input values input.Update(); // if any controls have changed... bool changed = false; for (int i = 0; i < Input::NUM_LOGICAL; ++i) { if (input.output[i] != prev[i]) { changed = true; break; } } if (changed) { // create an input turn entry TiXmlElement item( "input" ); item.SetAttribute( "turn", sim_turn ); // add changed control values input.Record(&item, prev); // add the new input entry inputlogroot->InsertEndChild(item); } } else { // update input values input.Update(); } } // do any pending turn actions DoTurn(); // CONTROL PHASE #ifdef GET_PERFORMANCE_DETAILS control_timer.Start(); #endif // control all entities Controller::ControlAll(sim_step); #ifdef GET_PERFORMANCE_DETAILS control_timer.Stop(); simulate_timer.Start(); #endif // SIMULATION PHASE // (generate forces) Simulatable::SimulateAll(sim_step); #ifdef GET_PERFORMANCE_DETAILS simulate_timer.Stop(); collide_timer.Start(); #endif // COLLISION PHASE // (apply forces and update positions) Collidable::CollideAll(sim_step); #ifdef GET_PERFORMANCE_DETAILS collide_timer.Stop(); update_timer.Start(); #endif // UPDATE PHASE // (use updated positions) Updatable::UpdateAll(sim_step); #ifdef GET_PERFORMANCE_DETAILS update_timer.Stop(); #endif // step inputs for next turn input.Step(); #ifdef COLLECT_DEBUG_DRAW // finish the draw list glEndList(); #endif // restore original fraction sim_fraction = save_fraction; } // clear single-step singlestep = false; // seed the random number generator FloatInt floatint; floatint.f = sim_fraction; Random::Seed(0x92D68CA2 ^ sim_turn ^ floatint.u); (void)Random::Int(); #ifdef PRINT_SIMULATION_TIMER DebugPrint("delta=%f ticks=%d sim_t=%f\n", delta, ticks, sim_fraction); #endif #ifdef GET_PERFORMANCE_DETAILS render_timer.Start(); #endif // RENDERING PHASE // push camera transform glPushMatrix(); // get interpolated track position Vector2 viewpos(Lerp(camerapos[0], camerapos[1], sim_fraction)); // set view position glTranslatef( -viewpos.x, -viewpos.y, 0 ); // calculate view area AlignedBox2 view; view.min.x = viewpos.x - VIEW_SIZE * 0.5f * SCREEN_WIDTH / SCREEN_HEIGHT; view.max.x = viewpos.x + VIEW_SIZE * 0.5f * SCREEN_WIDTH / SCREEN_HEIGHT; view.min.y = viewpos.y - VIEW_SIZE * 0.5f; view.max.y = viewpos.y + VIEW_SIZE * 0.5f; // render all entities // (send interpolation ratio and offset from simulation time) Renderable::RenderAll(view); // reset camera transform glPopMatrix(); // if performing motion blur... if (MOTIONBLUR_STEPS > 1) { // accumulate the image glAccum(blur ? GL_ACCUM : GL_LOAD, 1.0f / float(MOTIONBLUR_STEPS)); } #ifdef GET_PERFORMANCE_DETAILS render_timer.Stop(); #endif } #ifdef GET_PERFORMANCE_DETAILS render_timer.Start(); #endif // if performing motion blur... if (MOTIONBLUR_STEPS > 1) { // return the accumulated image glAccum(GL_RETURN, 1); } // switch blend mode glPushAttrib(GL_COLOR_BUFFER_BIT | GL_TEXTURE_BIT); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); #ifdef GET_PERFORMANCE_DETAILS render_timer.Stop(); overlay_timer.Start(); #endif #ifdef COLLECT_DEBUG_DRAW if (DEBUG_DRAW) { // push camera transform glPushMatrix(); // get interpolated track position Vector2 viewpos(Lerp(camerapos[0], camerapos[1], sim_fraction)); // set camera to track position glTranslatef( -viewpos.x, -viewpos.y, 0 ); // debug draw glCallList(debugdraw); // pop camera transform glPopMatrix(); } #endif // push projection transform glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 640, 480, 0, -1, 1); // use 640x480 screen coordinates glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // render all overlays Overlay::RenderAll(); #ifdef GET_PERFORMANCE_DETAILS overlay_timer.Stop(); if (!OPENGL_SWAPCONTROL) { display_timer.Start(); // wait for rendering to finish glFinish(); display_timer.Stop(); } #ifdef DRAW_PERFORMANCE_DETAILS if (PROFILER_OUTPUTSCREEN) { struct BandInfo { const LONGLONG * time; float r; float g; float b; float a; }; static BandInfo band_info[] = { { control_timer.mHistory, 1.0f, 0.0f, 0.0f, 0.5f }, { simulate_timer.mHistory, 1.0f, 1.0f, 0.0f, 0.5f }, { collide_timer.mHistory, 0.0f, 1.0f, 0.0f, 0.5f }, { update_timer.mHistory, 0.0f, 0.5f, 1.0f, 0.5f }, { render_timer.mHistory, 1.0f, 0.0f, 1.0f, 0.5f }, { overlay_timer.mHistory, 1.0f, 0.5f, 0.0f, 0.5f }, { display_timer.mHistory, 0.5f, 0.5f, 0.5f, 0.5f }, }; // generate y samples float sample_y[SDL_arraysize(band_info)+1][PerfTimer::NUM_SAMPLES]; int index = PerfTimer::mIndex; for (int i = 0; i < PerfTimer::NUM_SAMPLES; ++i) { float y = 480.0f; sample_y[0][i] = y; for (int band = 0; band < SDL_arraysize(band_info); ++band) { y -= 60.0f * 480.0f * band_info[band].time[index] / PerfTimer::mFrequency; sample_y[band+1][i] = y; } if (++index >= PerfTimer::NUM_SAMPLES) index = 0; } glBegin(GL_QUADS); for (int band = 0; band < SDL_arraysize(band_info); ++band) { glColor4fv(&band_info[band].r); float x = 0; float dx = 640.0f / PerfTimer::NUM_SAMPLES; for (int i = 0; i < PerfTimer::NUM_SAMPLES; i++) { glVertex3f(x, sample_y[band][i], 0); glVertex3f(x+dx, sample_y[band][i], 0); glVertex3f(x+dx, sample_y[band+1][i], 0); glVertex3f(x, sample_y[band+1][i], 0); x += dx; } } glEnd(); } #endif #ifdef PRINT_PERFORMANCE_DETAILS if (PROFILER_OUTPUTPRINT) { DebugPrint("C=%d S=%d P=%d U=%d R=%d O=%d D=%d\n", control_timer.Microseconds(), simulate_timer.Microseconds(), collide_timer.Microseconds(), update_timer.Microseconds(), render_timer.Microseconds(), overlay_timer.Microseconds(), display_timer.Microseconds()); } #endif // update frame timer total_timer.Stamp(); #if defined(PRINT_PERFORMANCE_FRAMERATE) || defined(DRAW_PERFORMANCE_FRAMERATE) if (FRAMERATE_OUTPUTSCREEN || FRAMERATE_OUTPUTPRINT) { // compute minimum, maximum, and average frame times over the past second LONGLONG total_min = LLONG_MAX; LONGLONG total_max = LLONG_MIN; LONGLONG total_sum = 0; LONGLONG total_samples = 0; int i = PerfTimer::mIndex; do { total_min = std::min(total_min, total_timer.mHistory[i]); total_max = std::max(total_max, total_timer.mHistory[i]); total_sum += total_timer.mHistory[i]; ++total_samples; i = (i > 0) ? i - 1 : PerfTimer::NUM_SAMPLES - 1; } while (total_sum <= PerfTimer::mFrequency && i != PerfTimer::mIndex && total_samples != PerfTimer::mCount); total_sum /= total_samples; // compute frame rates double rate_max = (double)PerfTimer::mFrequency / total_min; double rate_avg = (double)PerfTimer::mFrequency / total_sum; double rate_min = (double)PerfTimer::mFrequency / total_max; #if defined(DRAW_PERFORMANCE_FRAMERATE) if (FRAMERATE_OUTPUTSCREEN) { // draw frame rate indicator glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, OGLCONSOLE_glFontHandle); glBegin(GL_QUADS); char fps[16]; sprintf(fps, "%.2f max", rate_max); glColor4f(0.5f, 0.5f, 0.5f, 1.0f); OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 16, 8, -8, 0); sprintf(fps, "%.2f avg", rate_avg); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 24, 8, -8, 0); sprintf(fps, "%.2f min", rate_min); glColor4f(0.5f, 0.5f, 0.5f, 1.0f); OGLCONSOLE_DrawString(fps, 640 - 16 - 8 * strlen(fps), 32, 8, -8, 0); glEnd(); glDisable(GL_TEXTURE_2D); } #endif #if defined(PRINT_PERFORMANCE_FRAMERATE) if (FRAMERATE_OUTPUTPRINT) { DebugPrint("%.2f<%.2f<%.2f\n", rate_min, rate_avg, rate_max); } #endif } #endif #endif // reset camera transform glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); // restore blend mode glPopAttrib(); /* Render our console */ OGLCONSOLE_Draw(); // show the back buffer Platform::Present(); #if 0 #ifdef GET_PERFORMANCE_DETAILS if (OPENGL_SWAPCONTROL) #endif // wait for rendering to finish glFinish(); #endif // clear device reset flag wasreset = false; } while( setgamestate == curgamestate ); if (record) { // save input log inputlog.SaveFile(); } }