void Core_NotifyShutdown() { for (auto it = shutdownFuncs.begin(); it != shutdownFuncs.end(); ++it) { (*it)(); } }
void UdpServerListenHandler::HandleReadBlock(const ErrorCode & error_code, const boost::shared_ptr<BlockData> & block, const RID & resource_id, boost::uint32_t transaction_id, boost::uint16_t block_index, const std::set<boost::uint16_t> & subpiece_indexs, boost::uint16_t dest_protocol_version, const boost::asio::ip::udp::endpoint & end_point) { if (!server_) { return; } if (error_code == ErrorCodes::Success) { for(std::set<boost::uint16_t>::const_iterator iter = subpiece_indexs.begin(); iter != subpiece_indexs.end(); ++iter) { protocol::SubPieceInfo sub_piece_info = RequestParser::ParseFromSNToPeer(block_index, *iter); boost::uint16_t subpiece_index = *iter; if (subpiece_index < block->GetSubPieceNumber()) { statistics_->OnSubPieceResponseSent(); boost::shared_ptr<ResponseTask> subpiece_response( new SubPieceResponseTask( end_point, block, subpiece_index, transaction_id, resource_id, guid_, sub_piece_info, dest_protocol_version)); AddResponseTask(subpiece_response); } else { statistics_->OnError(ErrorCodes::ResourceNotFound); boost::shared_ptr<ResponseTask> error_response( new ErrorResponseTask( end_point, transaction_id, resource_id, guid_, protocol::ErrorPacket::PPV_SUBPIECE_NO_RESOURCEID, dest_protocol_version)); AddResponseTask(error_response); } } } else { statistics_->OnError(error_code); boost::shared_ptr<ResponseTask> error_response( new ErrorResponseTask( end_point, transaction_id, resource_id, guid_, protocol::ErrorPacket::PPV_SUBPIECE_NO_RESOURCEID, dest_protocol_version)); AddResponseTask(error_response); } }
void CProjectileDrawer::DrawProjectilesSetShadow(std::set<CProjectile*>& projectiles) { for (std::set<CProjectile*>::iterator setIt = projectiles.begin(); setIt != projectiles.end(); ++setIt) { DrawProjectileShadow(*setIt); } }
/// Records hexes that were cleared of fog via WML. void add_fog_override(const std::set<map_location> &hexes) { fog_clearer_.insert(hexes.begin(), hexes.end()); }
inline BOSTREAM2(const std::set<T, C, A> &a) { return itwrite(out, a.size(), a.begin()); }
int main(void){ int i,cur = 0,steps; char c; std::set<int>::iterator it1; points.insert(0); scanf("%d %d",&N,&K); //store moves in the form start-end for(i = 0;i < N; i++){ scanf("\n%d %c",&steps,&c); if(c == 'R'){ moves[i].start = cur; cur += steps; moves[i].end = cur; }else { moves[i].end = cur; cur -= steps; moves[i].start = cur; } points.insert(cur); } P = points.size(); //compress coordinates for(it1 = points.begin(),i = 0; it1 != points.end(); ++it1,i++){ cc[*it1] = i; original[i] = *it1; } //replace original with compressed values for(i = 0;i < N; i++){ moves[i].start = cc[moves[i].start]; moves[i].end = cc[moves[i].end]; } //mark visited for(i = 0;i < N; i++){ visited[moves[i].start+1] += 1; visited[moves[i].end+1] += -1; } int vis = 0; for(i = 0;i < P; i++){ vis += visited[i]; visited[i] = vis; } //count visited more than K times int count = 0; for(i = 1;i < P; i++){ if(visited[i] >= K){ count += original[i] - original[i-1]; } } printf("%d\n",count); return 0; }
// prints the values in the set void printTopN(std::set<tfidfPair>& set) { std::for_each(set.begin(), set.end(), [](tfidfPair a) { std::cout << a.word << ": " << a.value << std::endl; }); }
void game_board::check_victory(bool & continue_level, bool & found_player, bool & found_network_player, bool & cleared_villages, std::set<unsigned> & not_defeated, bool remove_from_carryover_on_defeat) { continue_level = true; found_player = false; found_network_player = false; cleared_villages = false; not_defeated = std::set<unsigned>(); for (const unit & i : units()) { DBG_EE << "Found a unit: " << i.id() << " on side " << i.side() << std::endl; const team& tm = teams()[i.side()-1]; DBG_EE << "That team's defeat condition is: " << tm.defeat_condition() << std::endl; if (i.can_recruit() && tm.defeat_condition() == team::DEFEAT_CONDITION::NO_LEADER) { not_defeated.insert(i.side()); } else if (tm.defeat_condition() == team::DEFEAT_CONDITION::NO_UNITS) { not_defeated.insert(i.side()); } } for (team& tm : teams_) { if(tm.defeat_condition() == team::DEFEAT_CONDITION::NEVER) { not_defeated.insert(tm.side()); } // Clear villages for teams that have no leader and // mark side as lost if it should be removed from carryover. if (not_defeated.find(tm.side()) == not_defeated.end()) { tm.clear_villages(); // invalidate_all() is overkill and expensive but this code is // run rarely so do it the expensive way. cleared_villages = true; if (remove_from_carryover_on_defeat) { tm.set_lost(true); } } else if(remove_from_carryover_on_defeat) { tm.set_lost(false); } } for (std::set<unsigned>::iterator n = not_defeated.begin(); n != not_defeated.end(); ++n) { size_t side = *n - 1; DBG_EE << "Side " << (side+1) << " is a not-defeated team" << std::endl; std::set<unsigned>::iterator m(n); for (++m; m != not_defeated.end(); ++m) { if (teams()[side].is_enemy(*m)) { return; } DBG_EE << "Side " << (side+1) << " and " << *m << " are not enemies." << std::endl; } if (teams()[side].is_local_human()) { found_player = true; } if (teams()[side].is_network_human()) { found_network_player = true; } } continue_level = false; }
void InfiLEmptyStencilModeCache() { auto iter = cache.begin(); for ( ;iter!=cache.end();++iter ) delete *iter; cache.clear(); }
bool set_subset(const std::set<K,C,A>& x, const std::set<K,C,A>& y) { return std::includes(x.begin(), x.end(), y.begin(), y.end()); }
double highOrderTools::smooth_metric_(std::vector<MElement*> & v, GFace *gf, dofManager<double> &myAssembler, std::set<MVertex*> &verticesToMove, elasticityTerm &El) { std::set<MVertex*>::iterator it; double dx = 0.0; if (myAssembler.sizeOfR()){ // while convergence for (unsigned int i = 0; i < v.size(); i++){ MElement *e = v[i]; int nbNodes = e->getNumVertices(); const int n2 = 2 * nbNodes; const int n3 = 3 * nbNodes; fullMatrix<double> K33(n3, n3); fullMatrix<double> K22(n2, n2); fullMatrix<double> J32(n3, n2); fullMatrix<double> J23(n2, n3); fullVector<double> D3(n3); fullVector<double> R2(n2); fullMatrix<double> J23K33(n2, n3); K33.setAll(0.0); SElement se(e); El.elementMatrix(&se, K33); computeMetricInfo(gf, e, J32, J23, D3); J23K33.gemm(J23, K33, 1, 0); K22.gemm(J23K33, J32, 1, 0); J23K33.mult(D3, R2); for (int j = 0; j < n2; j++){ Dof RDOF = El.getLocalDofR(&se, j); myAssembler.assemble(RDOF, -R2(j)); for (int k = 0; k < n2; k++){ Dof CDOF = El.getLocalDofC(&se, k); myAssembler.assemble(RDOF, CDOF, K22(j, k)); } } } myAssembler.systemSolve(); // for all element, compute detJ at integration points --> material law end // while convergence for (it = verticesToMove.begin(); it != verticesToMove.end(); ++it){ if ((*it)->onWhat()->dim() == 2){ SPoint2 param; reparamMeshVertexOnFace((*it), gf, param); SPoint2 dparam; myAssembler.getDofValue((*it), 0, _tag, dparam[0]); myAssembler.getDofValue((*it), 1, _tag, dparam[1]); SPoint2 newp = param+dparam; dx += newp.x() * newp.x() + newp.y() * newp.y(); (*it)->setParameter(0, newp.x()); (*it)->setParameter(1, newp.y()); } } myAssembler.systemClear(); } return dx; }
// Atom::AddExclusionList() void Atom::AddExclusionList(std::set<int> const& elist) { excluded_.clear(); for (std::set<int>::const_iterator ei = elist.begin(); ei != elist.end(); ei++) excluded_.push_back( *ei ); }
void Context::arrayVars(const std::set<Value*> &arrayValues){ for(std::set<Value*>::iterator it = arrayValues.begin(); it != arrayValues.end();it++){ ExprPtr expr = Expression::mkIntToIntVar((*it) -> getName()); this->val2expr[*it] = expr; } }
Mesh::Mesh(const std::map<MElement*,GEntity*> &element2entity, const std::set<MElement*> &els, std::set<MVertex*> &toFix, bool fixBndNodes, bool fastJacEval) : _fastJacEval(fastJacEval) { _dim = (*els.begin())->getDim(); // Initialize elements, vertices, free vertices and element->vertices // connectivity const int nElements = els.size(); _nPC = 0; _el.resize(nElements); _el2FV.resize(nElements); _el2V.resize(nElements); _nBezEl.resize(nElements); _nNodEl.resize(nElements); _indPCEl.resize(nElements); int iEl = 0; bool nonGeoMove = false; for(std::set<MElement*>::const_iterator it = els.begin(); it != els.end(); ++it, ++iEl) { _el[iEl] = *it; const JacobianBasis *jac = _el[iEl]->getJacobianFuncSpace(); _nBezEl[iEl] = _fastJacEval ? jac->getNumJacNodesFast() : jac->getNumJacNodes(); _nNodEl[iEl] = jac->getNumMapNodes(); for (int iVEl = 0; iVEl < jac->getNumMapNodes(); iVEl++) { MVertex *vert = _el[iEl]->getVertex(iVEl); GEntity *ge = vert->onWhat(); const int vDim = ge->dim(); const bool hasParam = ge->haveParametrization(); int iV = addVert(vert); _el2V[iEl].push_back(iV); if ((vDim > 0) && (toFix.find(vert) == toFix.end()) && (!fixBndNodes || vDim == _dim)) { // Free vertex? ParamCoord *param; if (vDim == 3) param = new ParamCoordPhys3D(); else if (hasParam) param = new ParamCoordParent(vert); else { if (vDim == 2) param = new ParamCoordLocalSurf(vert); else param = new ParamCoordLocalLine(vert); nonGeoMove = true; } int iFV = addFreeVert(vert,iV,vDim,param,toFix); _el2FV[iEl].push_back(iFV); for (int i=_startPCFV[iFV]; i<_startPCFV[iFV]+vDim; i++) _indPCEl[iEl].push_back(i); } else _el2FV[iEl].push_back(-1); } } if (nonGeoMove) Msg::Info("WARNING: Some vertices will be moved along local lines " "or planes, they may not remain on the exact geometry"); // Initial coordinates _ixyz.resize(nVert()); for (int iV = 0; iV < nVert(); iV++) _ixyz[iV] = _vert[iV]->point(); _iuvw.resize(nFV()); for (int iFV = 0; iFV < nFV(); iFV++) _iuvw[iFV] = _paramFV[iFV]->getUvw(_freeVert[iFV]); // Set current coordinates _xyz = _ixyz; _uvw = _iuvw; // Set normals to 2D elements (with magnitude of inverse Jacobian) or initial // Jacobians of 3D elements if (_dim == 2) { _scaledNormEl.resize(nEl()); for (int iEl = 0; iEl < nEl(); iEl++) calcScaledNormalEl2D(element2entity,iEl); } else { _invStraightJac.resize(nEl(),1.); double dumJac[3][3]; for (int iEl = 0; iEl < nEl(); iEl++) _invStraightJac[iEl] = 1. / fabs(_el[iEl]->getPrimaryJacobian(0.,0.,0.,dumJac)); } }
void UpdateData::AddOutOfRangeGUID(std::set<uint64>& guids) { m_outOfRangeGUIDs.insert(guids.begin(), guids.end()); }
void editor_action_area::extend(const editor_map& /*map*/, const std::set<map_location>& locs) { area_.insert(locs.begin(), locs.end()); }
void CFileItemHandler::HandleFileItem(const char *ID, bool allowFile, const char *resultname, CFileItemPtr item, const CVariant ¶meterObject, const std::set<std::string> &validFields, CVariant &result, bool append /* = true */, CThumbLoader *thumbLoader /* = NULL */) { CVariant object; std::set<std::string> fields(validFields.begin(), validFields.end()); if (item.get()) { std::set<std::string>::const_iterator fileField = fields.find("file"); if (fileField != fields.end()) { if (allowFile) { if (item->HasVideoInfoTag() && !item->GetVideoInfoTag()->GetPath().IsEmpty()) object["file"] = item->GetVideoInfoTag()->GetPath().c_str(); if (item->HasMusicInfoTag() && !item->GetMusicInfoTag()->GetURL().IsEmpty()) object["file"] = item->GetMusicInfoTag()->GetURL().c_str(); if (!object.isMember("file")) object["file"] = item->GetPath().c_str(); } fields.erase(fileField); } if (ID) { if (item->HasPVRChannelInfoTag() && item->GetPVRChannelInfoTag()->ChannelID() > 0) object[ID] = item->GetPVRChannelInfoTag()->ChannelID(); else if (item->HasMusicInfoTag() && item->GetMusicInfoTag()->GetDatabaseId() > 0) object[ID] = (int)item->GetMusicInfoTag()->GetDatabaseId(); else if (item->HasVideoInfoTag() && item->GetVideoInfoTag()->m_iDbId > 0) object[ID] = item->GetVideoInfoTag()->m_iDbId; if (stricmp(ID, "id") == 0) { if (item->HasPVRChannelInfoTag()) object["type"] = "channel"; else if (item->HasMusicInfoTag()) { if (item->m_bIsFolder && item->IsAlbum()) object["type"] = "album"; else object["type"] = "song"; } else if (item->HasVideoInfoTag() && !item->GetVideoInfoTag()->m_type.empty()) { std::string type = item->GetVideoInfoTag()->m_type; if (type == "movie" || type == "tvshow" || type == "episode" || type == "musicvideo") object["type"] = type; } else if (item->HasPictureInfoTag()) object["type"] = "picture"; if (!object.isMember("type")) object["type"] = "unknown"; } } bool deleteThumbloader = false; if (thumbLoader == NULL) { if (item->HasVideoInfoTag()) thumbLoader = new CVideoThumbLoader(); else if (item->HasMusicInfoTag()) thumbLoader = new CMusicThumbLoader(); if (thumbLoader != NULL) { deleteThumbloader = true; thumbLoader->Initialize(); } } if (item->HasPVRChannelInfoTag()) FillDetails(item->GetPVRChannelInfoTag(), item, fields, object, thumbLoader); if (item->HasVideoInfoTag()) FillDetails(item->GetVideoInfoTag(), item, fields, object, thumbLoader); if (item->HasMusicInfoTag()) FillDetails(item->GetMusicInfoTag(), item, fields, object, thumbLoader); if (item->HasPictureInfoTag()) FillDetails(item->GetPictureInfoTag(), item, fields, object, thumbLoader); FillDetails(item.get(), item, fields, object, thumbLoader); if (deleteThumbloader) delete thumbLoader; object["label"] = item->GetLabel().c_str(); } else object = CVariant(CVariant::VariantTypeNull); if (resultname) { if (append) result[resultname].append(object); else result[resultname] = object; } }
void chooser::create_device (const std::set<scanner::info>& devices, const std::string& udi) { std::set<scanner::info>::const_iterator it = devices.begin (); while (devices.end () != it && udi != it->udi ()) { ++it; } if (devices.end () != it) { Glib::RefPtr< Gdk::Window > window = get_window (); if (window) { window->set_cursor (Gdk::Cursor (Gdk::WATCH)); Gdk::flush (); } scanner::ptr ptr; std::string why; try { // FIXME This is a bit clunky but both calls may be time // consuming and cannot be put in a separate thread if // the connexion and/or the scanner objects are run via // process separation. The child process would exit at // the end of the thread. while (Gtk::Main::events_pending ()) Gtk::Main::iteration (); connexion::ptr cnx (connexion::create (it->connexion (), it->path ())); while (Gtk::Main::events_pending ()) Gtk::Main::iteration (); ptr = scanner::create (cnx, *it); } catch (const std::exception& e) { why = e.what (); } catch (...) { // FIXME set a why we failed to create a device } if (window) { window->set_cursor (); } if (ptr) { cache_ = get_active (); set_tooltip_text (it->udi ()); signal_device_changed_.emit (ptr); } else { const std::string& name = get_active ()->get_value (cols_->name); const std::string& udi = get_active ()->get_value (cols_->udi); inhibit_callback_ = true; if (cache_) set_active (cache_); inhibit_callback_ = false; BOOST_THROW_EXCEPTION (std::runtime_error ((format (_("Cannot access %1%\n(%2%)\n%3%")) % name % udi % _(why) ).str ())); } } }
void IOComponent::processAll(uint64_t clock, size_t data_size, uint8_t *mask, uint8_t *data, std::set<IOComponent *> &updated_machines) { io_clock = clock; // receive process data updates and mask to yield updated components current_time = microsecs(); assert(data != io_process_data); #if VERBOSE_DEBUG for (size_t ii=0; ii<data_size; ++ii) if (mask[ii]) { std::cout << "IOComponent::processAll()\n"; std::cout << "size: " << data_size << "\n"; std::cout << "pdta: "; display( io_process_data, data_size); std::cout << "\n"; std::cout << "pmsk: "; display( io_process_mask, data_size); std::cout << "\n"; std::cout << "data: "; display( data, data_size); std::cout << "\n"; std::cout << "mask: "; display( mask, data_size); std::cout << "\n"; break; } #endif assert(data_size == process_data_size); if (hardware_state == s_hardware_preinit) { // the initial process data has arrived from EtherCAT. keep the previous data as the defaults // so they can be applied asap memcpy(io_process_data, data, process_data_size); //setHardwareState(s_hardware_init); return; } // step through the incoming mask and update bits in process data uint8_t *p = data; uint8_t *m = mask; uint8_t *q = io_process_data; IOComponent *just_added = 0; for (unsigned int i=0; i<process_data_size; ++i) { if (!last_process_data) { if (*m) notifyComponentsAt(i); } // if (*m && *p==*q) { // std::cout<<"warning: incoming_data == process_data but mask indicates a change at byte " // << (int)(m-mask) << std::setw(2) << std::hex << " value: 0x" << (int)(*m) << std::dec << "\n"; // } if (*p != *q && *m) { // copy masked bits if any uint8_t bitmask = 0x01; int j = 0; // check each bit against the mask and if the mask if // set, check if the bit has changed. If the bit has // changed, notify components that use this bit and // update the bit while (bitmask) { if ( *m & bitmask) { //std::cout << "looking up " << i << ":" << j << "\n"; IOComponent *ioc = (*indexed_components)[ i*8+j ]; if (ioc && ioc != just_added) { just_added = ioc; //if (!ioc) std::cout << "no component at " << i << ":" << j << " found\n"; //else std::cout << "found " << ioc->io_name << "\n"; #if 0 if (ioc && ioc->last_event != e_none) { // pending locally sourced change on this io std::cout << " adding " << ioc->io_name << " due to event " << ioc->last_event << "\n"; updatedComponentsIn.insert(ioc); } #endif if ( (*p & bitmask) != (*q & bitmask) ) { // remotely source change on this io if (ioc) { //std::cout << " adding " << ioc->io_name << " due to bit change\n"; boost::recursive_mutex::scoped_lock lock(processing_queue_mutex); updatedComponentsIn.insert(ioc); } if (*p & bitmask) *q |= bitmask; else *q &= (uint8_t)(0xff - bitmask); } //else { // std::cout << "no change " << (unsigned int)*p << " vs " << // (unsigned int)*q << "\n";} } else { if (!ioc) std::cout << "IOComponent::processAll(): no io component at " << i <<":" <<j <<" but mask bit is set\n"; if ( (*p & bitmask) != (*q & bitmask) ) { if (*p & bitmask) *q |= bitmask; else *q &= (uint8_t)(0xff - bitmask); } } } bitmask = bitmask << 1; ++j; } } ++p; ++q; ++m; } if (hardware_state == s_operational) { // save the domain data for the next check if (!last_process_data) { last_process_data = new uint8_t[process_data_size]; } memcpy(last_process_data, io_process_data, process_data_size); } { boost::recursive_mutex::scoped_lock lock(processing_queue_mutex); if (!updatedComponentsIn.size()) return; // std::cout << updatedComponentsIn.size() << " component updates from hardware\n"; #ifdef USE_EXPERIMENTAL_IDLE_LOOP // look at the components that changed and remove them from the outgoing queue as long as the // outputs have been sent to the hardware std::set<IOComponent*>::iterator iter = updatedComponentsIn.begin(); while (iter != updatedComponentsIn.end()) { IOComponent *ioc = *iter++; ioc->read_time = io_clock; //std::cerr << "processing " << ioc->io_name << " time: " << ioc->read_time << "\n"; updatedComponentsIn.erase(ioc); if (updates_sent && updatedComponentsOut.count(ioc)) { //std::cout << "output request for " << ioc->io_name << " resolved\n"; updatedComponentsOut.erase(ioc); } //else std::cout << "still waiting for " << ioc->io_name << " event: " << ioc->last_event << "\n"; updated_machines.insert(ioc); } // for machines with updates to send, if these machines already have the same value // as the hardware (and updates have been sent) we also remove them from the // outgoing queue if (updates_sent) { iter = updatedComponentsOut.begin(); while (iter != updatedComponentsOut.end()) { IOComponent *ioc = *iter++; if (ioc->pending_value == (uint32_t)ioc->address.value) { //std::cout << "output request for " << ioc->io_name << " cleared as hardware value matches\n"; updatedComponentsOut.erase(ioc); } } } #else std::list<IOComponent *>::iterator iter = processing_queue.begin(); while (iter != processing_queue.end()) { IOComponent *ioc = *iter++; ioc->read_time = io_clock; ioc->idle(); } #endif } outputs_waiting = updatedComponentsOut.size(); }
PLAYER_UPDATE_STATE Player::Update(float delta_, Goal* goal_, std::vector<Bullet> bullets_, std::set<TerrainTile*> monitoredTiles_) { playerWaitTimer += delta_; animationTimer += delta_; //set animation if (animationTimer > 0.6f) { animationTimer = 0.0f; animSwitch++; if (animSwitch % 2 == 0) { playerTexture = textures[0]; } else { playerTexture = textures[1]; } } if (spotted && behaviour != FLEE) { cout << "behaviour == FLEE" << endl; behaviour = FLEE; navigationList.clear(); spotted = false; } //update player on normal path //while the navigationList is not empty. if (navigationList.empty() && behaviour == SEEK) { // //convert click location to tile TerrainTile* dstTile = terrain->TileAtMouseCoords(goal_->Pos()); //convert player location to tile TerrainTile* playerTile = terrain->TileAtMouseCoords(static_cast<int>(pos.x), static_cast<int>(pos.y)); // //get the vector of tiles to nav to navigationList = terrain->ShortestPath(playerTile, dstTile, monitoredTiles_); } if (navigationList.empty() && behaviour == FLEE) { TerrainTile* playerTile = terrain->TileAtMouseCoords(static_cast<int>(pos.x), static_cast<int>(pos.y)); //get a new path from terrain to get away from enemy navigationList = terrain->ClosestUnmonitoredTile(playerTile, monitoredTiles_); //is current tile monitored? if (std::find(monitoredTiles_.begin(), monitoredTiles_.end(), playerTile) == monitoredTiles_.end()) { behaviour = SEEK; } } ////wait for x seconds //if (navigationList.empty() && behaviour == FLEE) //{ // cout << "behaviour == WAIT" << endl; // behaviour = WAIT; //} //if (behaviour == WAIT) //{ // // if (playerWaitTimer > 0.1f) // { // playerWaitTimer = 0.0f; // cout << "behaviour == SEEK" << endl; // behaviour = SEEK; // } //} if (!navigationList.empty()) { //if ( behaviour != WAIT ) //{ //get the next node and move towards it TerrainTile* nextNode = navigationList[navigationList.size() - 1]; Vector2 nextNodePos = nextNode->Pos(); //if reached pop it off the top if ((pos - nextNode->Pos()).GetMagnitude() < 1.0f) { pos = nextNode->Pos(); navigationList.erase(navigationList.end() - 1); navigationList.clear(); } else { int currentTerrainCost = 1; if ((pos - nextNode->Pos()).GetMagnitude() < TILE_SIZE * 0.5f) { currentTerrainCost = nextNode->Cost(); } //TODO FIX - .GetNormal does not work on vector with Magnitude of 0 Vector2 direction = (nextNodePos - pos).GetNormal(); Vector2 velocity = (direction * 75) * delta_; velocity *= 1.f / (float)currentTerrainCost; pos += velocity; //rotate animation if (direction.x > 0.6) //heading right { RotateSprite(playerTexture, 0); } else if (direction.x < -0.6) //heading left { RotateSprite(playerTexture, PI); } else if (direction.y > 0.6) //heading down { RotateSprite(playerTexture, PI / 2); } else if (direction.y < -0.6) //heading up { RotateSprite(playerTexture, -(PI / 2)); } } //if ( playerWaitTimer > 2.0f ) //{ // navigationList.clear(); // playerWaitTimer = 0.0f; //} //} } //update player rect rect.centre = pos; //check if bullet collided with player for (auto& bullet : bullets_) { if (Collision::RectCollision(bullet.GetRect(), rect)) { cout << "bullet struck player" << endl; return PUS_DIED; } } if (terrain->TileAtMouseCoords(pos) == terrain->TileAtMouseCoords(goal_->Pos())) { return PUS_WON; } // if (IsKeyDown(SDLK_UP) || IsKeyDown(SDLK_w)) // { // pos.y -= 100 * delta_; // } // if (IsKeyDown(SDLK_DOWN) || IsKeyDown(SDLK_s)) // { // pos.y += 100 * delta_; // } // if (IsKeyDown(SDLK_RIGHT) || IsKeyDown(SDLK_d)) // { // pos.x += 100 * delta_; // } // if (IsKeyDown(SDLK_LEFT) || IsKeyDown(SDLK_a)) // { // pos.x -= 100 * delta_; // } return PUS_NORMAL; }
// Look up multiple symbols in the symbol table and return a set of // Modules that define those symbols. bool Archive::findModulesDefiningSymbols(std::set<std::string>& symbols, SmallVectorImpl<Module*>& result, std::string* error) { if (!mapfile || !base) { if (error) *error = "Empty archive invalid for finding modules defining symbols"; return false; } if (symTab.empty()) { // We don't have a symbol table, so we must build it now but lets also // make sure that we populate the modules table as we do this to ensure // that we don't load them twice when findModuleDefiningSymbol is called // below. // Get a pointer to the first file const char* At = base + firstFileOffset; const char* End = mapfile->getBufferEnd(); while ( At < End) { // Compute the offset to be put in the symbol table unsigned offset = At - base - firstFileOffset; // Parse the file's header ArchiveMember* mbr = parseMemberHeader(At, End, error); if (!mbr) return false; // If it contains symbols if (mbr->isBitcode()) { // Get the symbols std::vector<std::string> symbols; std::string FullMemberName = archPath.str() + "(" + mbr->getPath().str() + ")"; Module* M = GetBitcodeSymbols(At, mbr->getSize(), FullMemberName, Context, symbols, error); if (M) { // Insert the module's symbols into the symbol table for (std::vector<std::string>::iterator I = symbols.begin(), E=symbols.end(); I != E; ++I ) { symTab.insert(std::make_pair(*I, offset)); } // Insert the Module and the ArchiveMember into the table of // modules. modules.insert(std::make_pair(offset, std::make_pair(M, mbr))); } else { if (error) *error = "Can't parse bitcode member: " + mbr->getPath().str() + ": " + *error; delete mbr; return false; } } // Go to the next file location At += mbr->getSize(); if ((intptr_t(At) & 1) == 1) At++; } } // At this point we have a valid symbol table (one way or another) so we // just use it to quickly find the symbols requested. SmallPtrSet<Module*, 16> Added; for (std::set<std::string>::iterator I=symbols.begin(), Next = I, E=symbols.end(); I != E; I = Next) { // Increment Next before we invalidate it. ++Next; // See if this symbol exists Module* m = findModuleDefiningSymbol(*I,error); if (!m) continue; bool NewMember = Added.insert(m); if (!NewMember) continue; // The symbol exists, insert the Module into our result. result.push_back(m); // Remove the symbol now that its been resolved. symbols.erase(I); } return true; }
void iterate_hull_points( const std::vector<t_point2i>& data_points, std::vector<t_point2i>& hull_points, const std::set<unsigned int>& edge_bin_indices ) { t_point2i seed_point = data_points[get_seed_point_index(data_points)]; t_point2i curr_point = seed_point; t_point2i next_point; t_point2f curr_axis = t_point2f(1.0f, 0.0f); hull_points.push_back(seed_point); fprintf(HULL_POINTS_FILE, "%d\t%d\n", seed_point.x(), seed_point.y()); do { float min_point_angle = M_PI * 2.0f; // find next point on hull #if 0 { unsigned int min_point_index = 0; for (unsigned int n = 0; n < data_points.size(); n++) { const t_point2i& p = data_points[n]; if (p == curr_point) continue; const t_point2f v = t_point2f(p.x() - curr_point.x(), p.y() - curr_point.y()); const t_point2f w = v / v.radius(); const float angle = std::acos(std::max(-1.0f, std::min(1.0f, w.dot(curr_axis)))); if (angle < min_point_angle) { min_point_angle = angle; min_point_index = n; } } curr_axis = t_point2f(data_points[min_point_index].x() - curr_point.x(), data_points[min_point_index].y() - curr_point.y()); curr_axis = curr_axis / curr_axis.radius(); curr_point = data_points[min_point_index]; } #else { for (auto it = edge_bin_indices.begin(); it != edge_bin_indices.end(); ++it) { const t_point_bin& bin = POINT_BIN_GRID.get_bin(*it); for (unsigned int n = 0; n < bin.get_size(); n++) { const t_point2i& p = bin.get_point(n); if (p == curr_point) continue; const t_point2f v = t_point2f(p.x() - curr_point.x(), p.y() - curr_point.y()); const t_point2f w = v / v.radius(); const float angle = std::acos(std::max(-1.0f, std::min(1.0f, w.dot(curr_axis)))); if (angle < min_point_angle) { min_point_angle = angle; // TODO: bins should store pair<point, index> instances // min_point_index = n; next_point = p; } } } curr_axis = t_point2f(next_point.x() - curr_point.x(), next_point.y() - curr_point.y()); curr_axis = curr_axis / curr_axis.radius(); curr_point = next_point; } #endif hull_points.push_back(curr_point); fprintf(HULL_POINTS_FILE, "%d\t%d\n", curr_point.x(), curr_point.y()); } while (curr_point != seed_point); }
void NBRampsComputer::buildOffRamp(NBNode* cur, NBNodeCont& nc, NBEdgeCont& ec, NBDistrictCont& dc, SUMOReal rampLength, bool dontSplit, std::set<NBEdge*>& incremented) { NBEdge* potHighway, *potRamp, *prev; getOffRampEdges(cur, &potHighway, &potRamp, &prev); // compute the number of lanes to append const unsigned int firstLaneNumber = potHighway->getNumLanes(); int toAdd = (potRamp->getNumLanes() + firstLaneNumber) - prev->getNumLanes(); NBEdge* first = prev; NBEdge* last = prev; NBEdge* curr = prev; if (toAdd > 0 && find(incremented.begin(), incremented.end(), prev) == incremented.end()) { SUMOReal currLength = 0; while (curr != 0 && currLength + curr->getGeometry().length() - POSITION_EPS < rampLength) { if (find(incremented.begin(), incremented.end(), curr) == incremented.end()) { curr->incLaneNo(toAdd); curr->invalidateConnections(true); incremented.insert(curr); moveRampRight(curr, toAdd); currLength += curr->getLength(); // !!! loaded length? last = curr; } NBNode* prevN = curr->getFromNode(); if (prevN->getIncomingEdges().size() == 1) { curr = prevN->getIncomingEdges()[0]; if (curr->getNumLanes() != firstLaneNumber) { // the number of lanes changes along the computation; we'll stop... curr = 0; } } else { // ambigous; and, in fact, what should it be? ...stop curr = 0; } } // check whether a further split is necessary if (curr != 0 && !dontSplit && currLength - POSITION_EPS < rampLength && curr->getNumLanes() == firstLaneNumber && find(incremented.begin(), incremented.end(), curr) == incremented.end()) { // there is enough place to build a ramp; do it bool wasFirst = first == curr; Position pos = curr->getGeometry().positionAtLengthPosition(curr->getGeometry().length() - (rampLength - currLength)); NBNode* rn = new NBNode(curr->getID() + "-AddedOffRampNode", pos); if (!nc.insert(rn)) { throw ProcessError("Ups - could not build on-ramp for edge '" + curr->getID() + "' (node could not be build)!"); } std::string name = curr->getID(); bool ok = ec.splitAt(dc, curr, rn, curr->getID(), curr->getID() + "-AddedOffRampEdge", curr->getNumLanes(), curr->getNumLanes() + toAdd); if (!ok) { WRITE_ERROR("Ups - could not build on-ramp for edge '" + curr->getID() + "'!"); return; } curr = ec.retrieve(name + "-AddedOffRampEdge"); curr->invalidateConnections(true); incremented.insert(curr); last = curr; moveRampRight(curr, toAdd); if (wasFirst) { first = curr; } } } // set connections from added ramp to ramp/highway if (!first->addLane2LaneConnections(potRamp->getNumLanes(), potHighway, 0, MIN2(first->getNumLanes() - 1, potHighway->getNumLanes()), NBEdge::L2L_VALIDATED, true)) { throw ProcessError("Could not set connection!"); } if (!first->addLane2LaneConnections(0, potRamp, 0, potRamp->getNumLanes(), NBEdge::L2L_VALIDATED, false)) { throw ProcessError("Could not set connection!"); } // patch ramp geometry PositionVector p = potRamp->getGeometry(); p.pop_front(); p.push_front(first->getLaneShape(0)[-1]); potRamp->setGeometry(p); // set connections from previous highway to added ramp NBNode* prevN = last->getFromNode(); if (prevN->getIncomingEdges().size() == 1) { NBEdge* prev = prevN->getIncomingEdges()[0];//const EdgeVector& o1 = cont->getToNode()->getOutgoingEdges(); if (prev->getNumLanes() < last->getNumLanes()) { last->addLane2LaneConnections(last->getNumLanes() - prev->getNumLanes(), last, 0, prev->getNumLanes(), NBEdge::L2L_VALIDATED); } } }
void CFileItemHandler::HandleFileItem(const char *ID, bool allowFile, const char *resultname, CFileItemPtr item, const CVariant ¶meterObject, const std::set<std::string> &validFields, CVariant &result, bool append /* = true */, CThumbLoader *thumbLoader /* = NULL */) { CVariant object; std::set<std::string> fields(validFields.begin(), validFields.end()); if (item.get()) { std::set<std::string>::const_iterator fileField = fields.find("file"); if (fileField != fields.end()) { if (allowFile) { if (item->HasVideoInfoTag() && !item->GetVideoInfoTag()->GetPath().empty()) object["file"] = item->GetVideoInfoTag()->GetPath().c_str(); if (item->HasMusicInfoTag() && !item->GetMusicInfoTag()->GetURL().empty()) object["file"] = item->GetMusicInfoTag()->GetURL().c_str(); if (item->HasPVRRecordingInfoTag() && !item->GetPVRRecordingInfoTag()->GetPath().empty()) object["file"] = item->GetPVRRecordingInfoTag()->GetPath().c_str(); if (item->HasPVRTimerInfoTag() && !item->GetPVRTimerInfoTag()->m_strFileNameAndPath.empty()) object["file"] = item->GetPVRTimerInfoTag()->m_strFileNameAndPath.c_str(); if (!object.isMember("file")) object["file"] = item->GetPath().c_str(); } fields.erase(fileField); } if (ID) { if (item->HasPVRChannelInfoTag() && item->GetPVRChannelInfoTag()->ChannelID() > 0) object[ID] = item->GetPVRChannelInfoTag()->ChannelID(); else if (item->HasEPGInfoTag() && item->GetEPGInfoTag()->UniqueBroadcastID() > 0) object[ID] = item->GetEPGInfoTag()->UniqueBroadcastID(); else if (item->HasPVRRecordingInfoTag() && item->GetPVRRecordingInfoTag()->m_iRecordingId > 0) object[ID] = item->GetPVRRecordingInfoTag()->m_iRecordingId; else if (item->HasPVRTimerInfoTag() && item->GetPVRTimerInfoTag()->m_iTimerId > 0) object[ID] = item->GetPVRTimerInfoTag()->m_iTimerId; else if (item->HasMusicInfoTag() && item->GetMusicInfoTag()->GetDatabaseId() > 0) object[ID] = (int)item->GetMusicInfoTag()->GetDatabaseId(); else if (item->HasVideoInfoTag() && item->GetVideoInfoTag()->m_iDbId > 0) object[ID] = item->GetVideoInfoTag()->m_iDbId; if (stricmp(ID, "id") == 0) { if (item->HasPVRChannelInfoTag()) object["type"] = "channel"; else if (item->HasMusicInfoTag()) { std::string type = item->GetMusicInfoTag()->GetType(); if (type == MediaTypeAlbum || type == MediaTypeSong || type == MediaTypeArtist) object["type"] = type; else if (!item->m_bIsFolder) object["type"] = MediaTypeSong; } else if (item->HasVideoInfoTag() && !item->GetVideoInfoTag()->m_type.empty()) { std::string type = item->GetVideoInfoTag()->m_type; if (type == MediaTypeMovie || type == MediaTypeTvShow || type == MediaTypeEpisode || type == MediaTypeMusicVideo) object["type"] = type; } else if (item->HasPictureInfoTag()) object["type"] = "picture"; if (!object.isMember("type")) object["type"] = "unknown"; if (fields.find("filetype") != fields.end()) { if (item->m_bIsFolder) object["filetype"] = "directory"; else object["filetype"] = "file"; } } } bool deleteThumbloader = false; if (thumbLoader == NULL) { if (item->HasVideoInfoTag()) thumbLoader = new CVideoThumbLoader(); else if (item->HasMusicInfoTag()) thumbLoader = new CMusicThumbLoader(); if (thumbLoader != NULL) { deleteThumbloader = true; thumbLoader->OnLoaderStart(); } } if (item->HasPVRChannelInfoTag()) FillDetails(item->GetPVRChannelInfoTag().get(), item, fields, object, thumbLoader); if (item->HasEPGInfoTag()) FillDetails(item->GetEPGInfoTag().get(), item, fields, object, thumbLoader); if (item->HasPVRRecordingInfoTag()) FillDetails(item->GetPVRRecordingInfoTag().get(), item, fields, object, thumbLoader); if (item->HasPVRTimerInfoTag()) FillDetails(item->GetPVRTimerInfoTag().get(), item, fields, object, thumbLoader); if (item->HasVideoInfoTag()) FillDetails(item->GetVideoInfoTag(), item, fields, object, thumbLoader); if (item->HasMusicInfoTag()) FillDetails(item->GetMusicInfoTag(), item, fields, object, thumbLoader); if (item->HasPictureInfoTag()) FillDetails(item->GetPictureInfoTag(), item, fields, object, thumbLoader); FillDetails(item.get(), item, fields, object, thumbLoader); if (deleteThumbloader) delete thumbLoader; object["label"] = item->GetLabel().c_str(); } else object = CVariant(CVariant::VariantTypeNull); if (resultname) { if (append) result[resultname].append(object); else result[resultname] = object; } }
void LLEmbeddedItems::bindEmbeddedChars( LLFontGL* font ) const { if( sEntries.empty() ) { return; } for (std::set<llwchar>::const_iterator iter1 = mEmbeddedUsedChars.begin(); iter1 != mEmbeddedUsedChars.end(); ++iter1) { llwchar wch = *iter1; item_map_t::iterator iter2 = sEntries.find(wch); if (iter2 == sEntries.end()) { continue; } LLInventoryItem* item = iter2->second.mItem; if (!item) { continue; } const char* img_name; switch( item->getType() ) { case LLAssetType::AT_TEXTURE: if(item->getInventoryType() == LLInventoryType::IT_SNAPSHOT) { img_name = "inv_item_snapshot.tga"; } else { img_name = "inv_item_texture.tga"; } break; case LLAssetType::AT_SOUND: img_name = "inv_item_sound.tga"; break; case LLAssetType::AT_LANDMARK: if (item->getFlags() & LLInventoryItem::II_FLAGS_LANDMARK_VISITED) { img_name = "inv_item_landmark_visited.tga"; } else { img_name = "inv_item_landmark.tga"; } break; case LLAssetType::AT_CLOTHING: img_name = "inv_item_clothing.tga"; break; case LLAssetType::AT_OBJECT: if (item->getFlags() & LLInventoryItem::II_FLAGS_OBJECT_HAS_MULTIPLE_ITEMS) { img_name = "inv_item_object_multi.tga"; } else { img_name = "inv_item_object.tga"; } break; case LLAssetType::AT_NOTECARD: img_name = "inv_item_notecard.tga"; break; case LLAssetType::AT_LSL_TEXT: img_name = "inv_item_script.tga"; break; case LLAssetType::AT_BODYPART: img_name = "inv_item_skin.tga"; break; case LLAssetType::AT_ANIMATION: img_name = "inv_item_animation.tga";break; case LLAssetType::AT_GESTURE: img_name = "inv_item_gesture.tga"; break; default: llassert(0); continue; } LLUIImagePtr image = LLUI::getUIImage(img_name); font->addEmbeddedChar( wch, image->getImage(), item->getName() ); } }
void RoseBin_ControlFlowAnalysis::printGraph(std::string fileName, std::set<std::string>& filter) { #if 1 ASSERT_not_reachable("no longer supported"); #else std::set<std::string>::const_iterator it = filter.begin(); for (;it!=filter.end();++it) { std::cerr << "CFG -- contains filter: ." << *it << "." << endl; } // typedef rose_hash::unordered_map <std::string, SgGraphNode*> nodeType; // typedef rose_hash::unordered_map <string, SgGraphNode*,hash_stringptr> nodeType; rose_graph_integer_node_hash_map result; //rose_graph_hash_multimap& nodes = vizzGraph->get_node_index_to_node_map(); rose_graph_integer_node_hash_map nodes = vizzGraph->get_node_index_to_node_map(); rose_graph_integer_node_hash_map::iterator itn2 = nodes.begin(); for (; itn2 != nodes.end();++itn2) { // string hex_address = itn2->first; SgGraphNode* node = itn2->second; string hex_address = node->get_name(); //string hex_addr_tmp = node->get_name(); //ROSE_ASSERT(hex_address==hex_addr_tmp); SgNode* internal = node->get_SgNode(); SgAsmFunction* func = isSgAsmFunction(internal); if (func) { std::cerr << "ControlFlowAnalysis:: found function: ." << hex_address << "." <<endl; std::set<std::string>::const_iterator it = filter.find(hex_address); if (it!=filter.end()) { //std::cerr << " ******************* match ********************* " << std::endl; set<SgGraphNode*> gns; set<std::string> names; getCFGNodesForFunction(gns,names,node,hex_address); if (debug) cerr << " nodes in function: " << gns.size() << " " << names.size() <<endl; ROSE_ASSERT(gns.size()==names.size()); set<SgGraphNode*>::const_iterator it2 = gns.begin(); set<std::string>::const_iterator it3 = names.begin(); for (;it2!=gns.end();++it2, ++it3) { std::string name = *it3; SgGraphNode* n = *it2; if (debug) cerr << " adding to result ."<<name<<"."<<endl; result.insert(make_pair(itn2->first,n)); } } } } rose_graph_integer_node_hash_map nodesResult = nodes; rose_graph_integer_node_hash_map::iterator itn23 = nodes.begin(); for (; itn23!=nodes.end();++itn23) { //string hex_address = isSgGraphNode(itn23->second)->get_name(); int pos = itn23->first; // rose_graph_integer_node_hash_map::iterator it = result.find(hex_address); rose_graph_integer_node_hash_map::iterator it = result.find(pos); if (it==result.end()) { // not found in result, i.e. delete //nodesResult.erase(hex_address); nodesResult.erase(pos); } } // vizzGraph->nodes=nodesResult; #if 0 // vizzGraph->nodes=result; // create file bool forward_analysis=true; bool multiedge=false; std::ofstream myfile; myfile.open(fileName.c_str()); string name = "ROSE Graph"; vizzGraph->printProlog(myfile, name); string functionName=""; vizzGraph->setGrouping(true); vizzGraph->printNodes(true, this, forward_analysis, myfile,functionName); nrNodes=vizzGraph->nodes.size(); vizzGraph->printEdges(this,myfile, multiedge); nrEdges=vizzGraph->get_node_index_to_edge_multimap_edgesOut().size(); vizzGraph->printEpilog(myfile); myfile.close(); #endif #if 1 RoseBin_Graph* gr = new RoseBin_DotGraph(); gr->graph = new SgIncidenceDirectedGraph("test");//SgDirectedGraph("test","test"); gr->get_node_index_to_node_map()=nodesResult; //typedef SB_DirectedGraph::edgeType edgeType; rose_graph_integer_edge_hash_multimap edges = vizzGraph->get_node_index_to_edge_multimap_edgesOut(); rose_graph_integer_edge_hash_multimap resultEdges; rose_graph_integer_edge_hash_multimap::iterator itEdg = edges.begin(); for (; itEdg!=edges.end();++itEdg) { int index = itEdg->first; SgGraphNode* node = NULL; rose_graph_integer_node_hash_map::iterator nIT = vizzGraph->get_node_index_to_node_map().find(index); if (nIT!=vizzGraph->get_node_index_to_node_map().end()) node=nIT->second; ROSE_ASSERT(node); SgDirectedGraphEdge* edge = isSgDirectedGraphEdge(itEdg->second); SgGraphNode* target = isSgGraphNode(edge->get_to()); rose_graph_integer_node_hash_map::iterator itn2 = nodesResult.begin(); bool foundS=false; if (node) foundS=true; bool foundT=false; for (; itn2!=nodesResult.end();++itn2) { SgGraphNode* n = itn2->second; //if (n==source) foundS=true; if (n==target) foundT=true; } if (foundS==false || foundT==false) { } else resultEdges.insert(make_pair(node->get_index(),edge)); } gr->get_node_index_to_edge_multimap_edgesOut()=resultEdges; // create file bool forward_analysis=true; bool multiedge=false; std::ofstream myfile; myfile.open(fileName.c_str()); string name = "ROSE Graph"; gr->printProlog(myfile, name); string functionName=""; gr->setGrouping(true); gr->printNodes(true, this, forward_analysis, myfile,functionName); nrNodes=gr->get_node_index_to_node_map().size(); ROSE_ASSERT(g_algo->info); gr->printEdges(g_algo->info, this,myfile, multiedge); nrEdges=gr->get_node_index_to_edge_multimap_edgesOut().size(); gr->printEpilog(myfile); myfile.close(); #endif #endif }
/* Lights neighbors of from_nodes, collects all them and then goes on recursively. */ void VoxelManipulator::spreadLight(enum LightBank bank, std::set<v3s16> & from_nodes, INodeDefManager *nodemgr) { const v3s16 dirs[6] = { v3s16(0,0,1), // back v3s16(0,1,0), // top v3s16(1,0,0), // right v3s16(0,0,-1), // front v3s16(0,-1,0), // bottom v3s16(-1,0,0), // left }; if(from_nodes.size() == 0) return; std::set<v3s16> lighted_nodes; for(std::set<v3s16>::iterator j = from_nodes.begin(); j != from_nodes.end(); ++j) { v3s16 pos = *j; emerge(VoxelArea(pos - v3s16(1,1,1), pos + v3s16(1,1,1))); u32 i = m_area.index(pos); if(m_flags[i] & VOXELFLAG_INEXISTENT) continue; MapNode &n = m_data[i]; u8 oldlight = n.getLight(bank, nodemgr); u8 newlight = diminish_light(oldlight); // Loop through 6 neighbors for(u16 i=0; i<6; i++) { // Get the position of the neighbor node v3s16 n2pos = pos + dirs[i]; try { u32 n2i = m_area.index(n2pos); if(m_flags[n2i] & VOXELFLAG_INEXISTENT) continue; MapNode &n2 = m_data[n2i]; u8 light2 = n2.getLight(bank, nodemgr); /* If the neighbor is brighter than the current node, add to list (it will light up this node on its turn) */ if(light2 > undiminish_light(oldlight)) { lighted_nodes.insert(n2pos); } /* If the neighbor is dimmer than how much light this node would spread on it, add to list */ if(light2 < newlight) { if(nodemgr->get(n2).light_propagates) { n2.setLight(bank, newlight, nodemgr); lighted_nodes.insert(n2pos); } } } catch(InvalidPositionException &e) { continue; } } } /*dstream<<"spreadLight(): Changed block " <<blockchangecount<<" times" <<" for "<<from_nodes.size()<<" nodes" <<std::endl;*/ if(lighted_nodes.size() > 0) spreadLight(bank, lighted_nodes, nodemgr); }
bool ConsoleAdapter::consoleInputBox_KeyUp(const CEGUI::EventArgs& args) { const CEGUI::KeyEventArgs& keyargs = static_cast<const CEGUI::KeyEventArgs&>(args); if(keyargs.scancode != CEGUI::Key::Tab) { mTabPressed = false; } switch(keyargs.scancode) { case CEGUI::Key::ArrowUp: { if(mBackend->getHistory().getHistoryPosition() == 0) { mCommandLine = mInputBox->getText().c_str(); } else { // we are not at the command line but in the history // => write back the editing mBackend->getHistory().changeHistory(mBackend->getHistory().getHistoryPosition(), mInputBox->getText().c_str()); } mBackend->getHistory().moveBackwards(); if(mBackend->getHistory().getHistoryPosition() != 0) { mInputBox->setText(mBackend->getHistory().getHistoryString()); } return true; } case CEGUI::Key::ArrowDown: { if(mBackend->getHistory().getHistoryPosition() > 0) { mBackend->getHistory().changeHistory(mBackend->getHistory().getHistoryPosition(), mInputBox->getText().c_str()); mBackend->getHistory().moveForwards(); if(mBackend->getHistory().getHistoryPosition() == 0) { mInputBox->setText(mCommandLine); } else { mInputBox->setText(mBackend->getHistory().getHistoryString()); } } return true; } case CEGUI::Key::Tab: { std::string sCommand(mInputBox->getText().c_str()); // only process commands if(sCommand[0] != '/') { return true; } sCommand = sCommand.substr(1, mInputBox->getCaretIndex() - 1); if(mTabPressed == true) { const std::set< std::string > commands(mBackend->getPrefixes(sCommand)); if(commands.size() > 0) { std::set< std::string >::const_iterator iCommand(commands.begin()); std::string sMessage(""); mSelected = (mSelected + 1) % commands.size(); int select(0); while(iCommand != commands.end()) { if(select == mSelected) { std::string sCommandLine(mInputBox->getText().c_str()); // compose the new command line: old text before the caret + selected command mInputBox->setText(sCommandLine.substr(0, mInputBox->getCaretIndex()) + iCommand->substr(mInputBox->getCaretIndex() - 1)); mInputBox->setSelection(mInputBox->getCaretIndex(), 0xFFFFFFFF); } sMessage += *iCommand + ' '; ++iCommand; ++select; } mBackend->pushMessage(sMessage); } } else { mTabPressed = true; mSelected = 0; const std::set< std::string > commands(mBackend->getPrefixes(sCommand)); if(commands.size() == 0) { // TODO: Error reporting? } else { // if any command starts with the current prefix if(commands.size() == 1) { mInputBox->setText(std::string("/") + *(commands.begin()) + ' '); // this will be at the end of the text mInputBox->setCaretIndex(0xFFFFFFFF); } else { //If there are multiple matches we need to find the lowest common denominator. We'll do this by iterating through all characters and then checking with all the possible commands if they match that prefix, until we get a false. std::set< std::string >::const_iterator iSelected(commands.begin()); std::set< std::string >::const_iterator iCommand(commands.begin()); std::string sCommonPrefix(*iCommand); int select = 1; ++iCommand; while(iCommand != commands.end()) { if(select == mSelected) { iSelected = iCommand; } std::string::size_type i(0); while((i < sCommonPrefix.length()) && (i < (*iCommand).length())) { if(sCommonPrefix[i] != (*iCommand)[i]) { break; } ++i; } if(i < sCommonPrefix.length()) { sCommonPrefix = sCommonPrefix.substr(0, i); } ++select; ++iCommand; } mInputBox->setText(std::string("/") + sCommonPrefix + iSelected->substr(sCommonPrefix.length())); mInputBox->setCaretIndex(sCommonPrefix.length() + 1); mInputBox->setSelection(sCommonPrefix.length() + 1, 0xFFFFFFFF); } } } return true; } case CEGUI::Key::Return: case CEGUI::Key::NumpadEnter: { if (mReturnKeyDown) { mReturnKeyDown = false; if(mInputBox->getSelectionLength() > 0) { unsigned long ulSelectionEnd(mInputBox->getSelectionEndIndex()); mInputBox->setText(mInputBox->getText() + ' '); mInputBox->setCaretIndex(ulSelectionEnd + 1); mInputBox->setSelection(mInputBox->getCaretIndex(), mInputBox->getCaretIndex()); } else { const CEGUI::String consoleText(mInputBox->getText()); mInputBox->setText(CEGUI::String("")); mBackend->pushMessage(("> " + consoleText).c_str()); // run the command mBackend->runCommand(consoleText.c_str()); EventCommandExecuted.emit(consoleText.c_str()); } } return true; } default: { break; } } return false; }
void CProjectileDrawer::DrawProjectilesSet(std::set<CProjectile*>& projectiles, bool drawReflection, bool drawRefraction) { for (std::set<CProjectile*>::iterator setIt = projectiles.begin(); setIt != projectiles.end(); ++setIt) { DrawProjectile(*setIt, drawReflection, drawRefraction); } }
int main() { { typedef int V; V ar[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8 }; std::set<int> m(ar, ar+sizeof(ar)/sizeof(ar[0])); assert(std::distance(m.begin(), m.end()) == m.size()); assert(std::distance(m.rbegin(), m.rend()) == m.size()); std::set<int>::iterator i; i = m.begin(); std::set<int>::const_iterator k = i; assert(i == k); for (int j = 1; j <= m.size(); ++j, ++i) assert(*i == j); } { typedef int V; V ar[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8 }; const std::set<int> m(ar, ar+sizeof(ar)/sizeof(ar[0])); assert(std::distance(m.begin(), m.end()) == m.size()); assert(std::distance(m.cbegin(), m.cend()) == m.size()); assert(std::distance(m.rbegin(), m.rend()) == m.size()); assert(std::distance(m.crbegin(), m.crend()) == m.size()); std::set<int>::const_iterator i; i = m.begin(); for (int j = 1; j <= m.size(); ++j, ++i) assert(*i == j); } #if __cplusplus >= 201103L || defined(_LIBCPP_MSVC) { typedef int V; V ar[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8 }; std::set<int, std::less<int>, min_allocator<int>> m(ar, ar+sizeof(ar)/sizeof(ar[0])); assert(std::distance(m.begin(), m.end()) == m.size()); assert(std::distance(m.rbegin(), m.rend()) == m.size()); std::set<int, std::less<int>, min_allocator<int>>::iterator i; i = m.begin(); std::set<int, std::less<int>, min_allocator<int>>::const_iterator k = i; assert(i == k); for (int j = 1; j <= m.size(); ++j, ++i) assert(*i == j); } { typedef int V; V ar[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8 }; const std::set<int, std::less<int>, min_allocator<int>> m(ar, ar+sizeof(ar)/sizeof(ar[0])); assert(std::distance(m.begin(), m.end()) == m.size()); assert(std::distance(m.cbegin(), m.cend()) == m.size()); assert(std::distance(m.rbegin(), m.rend()) == m.size()); assert(std::distance(m.crbegin(), m.crend()) == m.size()); std::set<int, std::less<int>, min_allocator<int>>::const_iterator i; i = m.begin(); for (int j = 1; j <= m.size(); ++j, ++i) assert(*i == j); } #endif #if _LIBCPP_STD_VER > 11 { // N3644 testing typedef std::set<int> C; C::iterator ii1{}, ii2{}; C::iterator ii4 = ii1; C::const_iterator cii{}; assert ( ii1 == ii2 ); assert ( ii1 == ii4 ); assert (!(ii1 != ii2 )); assert ( (ii1 == cii )); assert ( (cii == ii1 )); assert (!(ii1 != cii )); assert (!(cii != ii1 )); } #endif }