text
stringlengths
54
60.6k
<commit_before>#include "networking/servernetworker.h" #include "global_constants.h" ServerNetworker::ServerNetworker() : Networker(true) { ENetAddress address; address.host = ENET_HOST_ANY; address.port = 3224; // 3223-3230 host = enet_host_create(&address, PLAYER_LIMIT, 1, 0, 0); if (host == NULL) { fprintf(stderr, "Fatal Error while attempting to create server host!"); throw -1; } } ServerNetworker::~ServerNetworker() { //dtor } void ServerNetworker::receive(Gamestate *state) { ENetEvent event; while (enet_host_service(host, &event, 0)) { if (event.type == ENET_EVENT_TYPE_CONNECT) { EntityPtr player = state->addplayer(); event.peer->data = std::malloc(sizeof(int)); reinterpret_cast<int*>(event.peer->data)[0] = state->playerlist[state->playerlist.size()-1]; enet_peer_timeout(event.peer, 0, 2000, 3000); // Send full update WriteBuffer frame = WriteBuffer(); frame.write<uint8_t>(SERVER_FULLUPDATE); state->serializefull(&frame); ENetPacket *eventpacket = enet_packet_create(frame.getdata(), frame.length(), ENET_PACKET_FLAG_RELIABLE); enet_peer_send(event.peer, 0, eventpacket); // Set the spawn timer for the new player so that they will spawn at next opportunity state->get<Player>(player)->spawntimer.timer = state->get<Player>(player)->spawntimer.duration; state->get<Player>(player)->spawntimer.active = true; // Tell everyone except the new player that a new player joined WriteBuffer tmpbuffer; tmpbuffer.write<uint8_t>(PLAYER_JOINED); eventpacket = enet_packet_create(tmpbuffer.getdata(), tmpbuffer.length(), ENET_PACKET_FLAG_RELIABLE); for (unsigned int i=0; i<host->connectedPeers; ++i) { if (&(host->peers[i]) != event.peer) { enet_peer_send(&(host->peers[i]), 0, eventpacket); } } enet_host_flush(host); } else if (event.type == ENET_EVENT_TYPE_DISCONNECT) { int i = state->findplayerid(reinterpret_cast<int*>(event.peer->data)[0]); state->removeplayer(i); std::free(event.peer->data); // Send disconnect event of that player sendbuffer.write<uint8_t>(PLAYER_LEFT); sendbuffer.write<uint8_t>(i); } else if (event.type == ENET_EVENT_TYPE_RECEIVE) { ReadBuffer data = ReadBuffer(event.packet->data, event.packet->dataLength); while (data.length() > 0) { int eventtype = data.read<uint8_t>(); if (eventtype == CLIENT_INPUT) { Player *p = state->get<Player>(reinterpret_cast<int*>(event.peer->data)[0]); if (p->character != 0) { InputContainer pressedkeys, heldkeys; heldkeys.deserialize(&data); double mouse_x = data.read<int16_t>(); double mouse_y = data.read<int16_t>(); p->getcharacter(state)->setinput(state, heldkeys, mouse_x, mouse_y); } } else { fprintf(stderr, "Invalid packet received on server: %i!", eventtype); } } enet_packet_destroy(event.packet); } } } void ServerNetworker::sendeventdata(Gamestate *state) { if (sendbuffer.length() > 0) { ENetPacket *eventpacket = enet_packet_create(sendbuffer.getdata(), sendbuffer.length(), ENET_PACKET_FLAG_RELIABLE); enet_host_broadcast(host, 0, eventpacket); enet_host_flush(host); sendbuffer.reset(); } } void ServerNetworker::sendframedata(Gamestate *state) { WriteBuffer frame = WriteBuffer(); frame.write<uint8_t>(SERVER_SNAPSHOTUPDATE); state->serializesnapshot(&frame); ENetPacket *framepacket = enet_packet_create(frame.getdata(), frame.length(), 0); enet_host_broadcast(host, 0, framepacket); enet_host_flush(host); } <commit_msg>Removed useless variable that was creating warnings.<commit_after>#include "networking/servernetworker.h" #include "global_constants.h" ServerNetworker::ServerNetworker() : Networker(true) { ENetAddress address; address.host = ENET_HOST_ANY; address.port = 3224; // 3223-3230 host = enet_host_create(&address, PLAYER_LIMIT, 1, 0, 0); if (host == NULL) { fprintf(stderr, "Fatal Error while attempting to create server host!"); throw -1; } } ServerNetworker::~ServerNetworker() { //dtor } void ServerNetworker::receive(Gamestate *state) { ENetEvent event; while (enet_host_service(host, &event, 0)) { if (event.type == ENET_EVENT_TYPE_CONNECT) { EntityPtr player = state->addplayer(); event.peer->data = std::malloc(sizeof(int)); reinterpret_cast<int*>(event.peer->data)[0] = state->playerlist[state->playerlist.size()-1]; enet_peer_timeout(event.peer, 0, 2000, 3000); // Send full update WriteBuffer frame = WriteBuffer(); frame.write<uint8_t>(SERVER_FULLUPDATE); state->serializefull(&frame); ENetPacket *eventpacket = enet_packet_create(frame.getdata(), frame.length(), ENET_PACKET_FLAG_RELIABLE); enet_peer_send(event.peer, 0, eventpacket); // Set the spawn timer for the new player so that they will spawn at next opportunity state->get<Player>(player)->spawntimer.timer = state->get<Player>(player)->spawntimer.duration; state->get<Player>(player)->spawntimer.active = true; // Tell everyone except the new player that a new player joined WriteBuffer tmpbuffer; tmpbuffer.write<uint8_t>(PLAYER_JOINED); eventpacket = enet_packet_create(tmpbuffer.getdata(), tmpbuffer.length(), ENET_PACKET_FLAG_RELIABLE); for (unsigned int i=0; i<host->connectedPeers; ++i) { if (&(host->peers[i]) != event.peer) { enet_peer_send(&(host->peers[i]), 0, eventpacket); } } enet_host_flush(host); } else if (event.type == ENET_EVENT_TYPE_DISCONNECT) { int i = state->findplayerid(reinterpret_cast<int*>(event.peer->data)[0]); state->removeplayer(i); std::free(event.peer->data); // Send disconnect event of that player sendbuffer.write<uint8_t>(PLAYER_LEFT); sendbuffer.write<uint8_t>(i); } else if (event.type == ENET_EVENT_TYPE_RECEIVE) { ReadBuffer data = ReadBuffer(event.packet->data, event.packet->dataLength); while (data.length() > 0) { int eventtype = data.read<uint8_t>(); if (eventtype == CLIENT_INPUT) { Player *p = state->get<Player>(reinterpret_cast<int*>(event.peer->data)[0]); if (p->character != 0) { InputContainer heldkeys; heldkeys.deserialize(&data); double mouse_x = data.read<int16_t>(); double mouse_y = data.read<int16_t>(); p->getcharacter(state)->setinput(state, heldkeys, mouse_x, mouse_y); } } else { fprintf(stderr, "Invalid packet received on server: %i!", eventtype); } } enet_packet_destroy(event.packet); } } } void ServerNetworker::sendeventdata(Gamestate *state) { if (sendbuffer.length() > 0) { ENetPacket *eventpacket = enet_packet_create(sendbuffer.getdata(), sendbuffer.length(), ENET_PACKET_FLAG_RELIABLE); enet_host_broadcast(host, 0, eventpacket); enet_host_flush(host); sendbuffer.reset(); } } void ServerNetworker::sendframedata(Gamestate *state) { WriteBuffer frame = WriteBuffer(); frame.write<uint8_t>(SERVER_SNAPSHOTUPDATE); state->serializesnapshot(&frame); ENetPacket *framepacket = enet_packet_create(frame.getdata(), frame.length(), 0); enet_host_broadcast(host, 0, framepacket); enet_host_flush(host); } <|endoftext|>
<commit_before>#include <mtp/metadata/Library.h> #include <mtp/ptp/Session.h> #include <mtp/ptp/ObjectPropertyListParser.h> #include <mtp/log.h> #include <unordered_map> namespace mtp { namespace { const std::string UknownArtist ("UknownArtist"); const std::string UknownAlbum ("UknownAlbum"); const std::string VariousArtists ("VariousArtists"); } Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId) { NameToObjectIdMap list; ByteArray data = _session->GetObjectPropertyList(parentId, ObjectFormat::Association, ObjectProperty::ObjectFilename, 0, 1); ObjectPropertyListParser<std::string> parser; parser.Parse(data, [&](ObjectId id, ObjectProperty property, const std::string &name) { list.insert(std::make_pair(name, id)); }); return list; } ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name) { auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId); for (auto id : objects.ObjectHandles) { auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename); if (name == oname) return id; } return _session->CreateDirectory(name, parentId, _storage).ObjectId; } Library::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session) { auto storages = _session->GetStorageIDs(); if (storages.StorageIDs.empty()) throw std::runtime_error("no storages found"); u64 progress = 0, total = 0; if (reporter) reporter(State::Initialising, progress, total); _artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist); debug("device supports ObjectFormat::Artist: ", _artistSupported? "yes": "no"); { auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum); _albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end(); } _storage = storages.StorageIDs[0]; //picking up first storage. //zune fails to create artist/album without storage id { ByteArray data = _session->GetObjectPropertyList(Session::Root, ObjectFormat::Association, ObjectProperty::ObjectFilename, 0, 1); ObjectPropertyListParser<std::string> parser; parser.Parse(data, [&](ObjectId id, ObjectProperty property, const std::string &name) { if (name == "Artists") _artistsFolder = id; else if (name == "Albums") _albumsFolder = id; else if (name == "Music") _musicFolder = id; }); } if (_artistSupported && _artistsFolder == ObjectId()) _artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId; if (_albumsFolder == ObjectId()) _albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId; if (_musicFolder == ObjectId()) _musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId; debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0); debug("albums folder: ", _albumsFolder.Id); debug("music folder: ", _musicFolder.Id); auto musicFolders = ListAssociations(_musicFolder); using namespace mtp; msg::ObjectHandles artists, albums; if (_artistSupported) { debug("getting artists..."); if (reporter) reporter(State::QueryingArtists, progress, total); artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device); total += artists.ObjectHandles.size(); } { debug("getting albums..."); if (reporter) reporter(State::QueryingAlbums, progress, total); albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device); total += albums.ObjectHandles.size(); } if (_artistSupported) { if (reporter) reporter(State::LoadingArtists, progress, total); for (auto id : artists.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name); debug("artist: ", name, "\t", id.Id); auto artist = std::make_shared<Artist>(); artist->Id = id; artist->Name = name; auto it = musicFolders.find(name); if (it != musicFolders.end()) artist->MusicFolderId = it->second; else artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId; _artists.insert(std::make_pair(name, artist)); if (reporter) reporter(State::LoadingArtists, ++progress, total); } } if (reporter) reporter(State::LoadingAlbums, progress, total); std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders; for (auto id : albums.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name); auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist); std::string albumDate; if (_albumDateAuthoredSupported) albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored); auto artist = GetArtist(artistName); if (!artist) artist = CreateArtist(artistName); debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate); auto album = std::make_shared<Album>(); album->Name = name; album->Artist = artist; album->Id = id; album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0; if (albumFolders.find(artist) == albumFolders.end()) { albumFolders[artist] = ListAssociations(artist->MusicFolderId); } auto it = albumFolders.find(artist); if (it == albumFolders.end()) throw std::runtime_error("no iterator after insert, internal error"); const auto & albums = it->second; auto alit = albums.find(name); if (alit != albums.end()) album->MusicFolderId = alit->second; else album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId; _albums.insert(std::make_pair(std::make_pair(artist, name), album)); if (reporter) reporter(State::LoadingAlbums, ++progress, total); } if (reporter) reporter(State::Loaded, progress, total); } Library::~Library() { } Library::ArtistPtr Library::GetArtist(std::string name) { if (name.empty()) name = UknownArtist; auto it = _artists.find(name); return it != _artists.end()? it->second: ArtistPtr(); } Library::ArtistPtr Library::CreateArtist(std::string name) { if (name.empty()) name = UknownArtist; auto artist = std::make_shared<Artist>(); artist->Name = name; artist->MusicFolderId = GetOrCreate(_musicFolder, name); if (_artistSupported) { ByteArray propList; OutputStream os(propList); os.Write32(2); //number of props os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name + ".art"); auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList); artist->Id = response.ObjectId; } _artists.insert(std::make_pair(name, artist)); return artist; } Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name) { if (name.empty()) name = UknownAlbum; auto it = _albums.find(std::make_pair(artist, name)); return it != _albums.end()? it->second: AlbumPtr(); } Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year) { if (!artist) throw std::runtime_error("artists is required"); if (name.empty()) name = UknownAlbum; ByteArray propList; OutputStream os(propList); bool sendYear = year != 0 && _albumDateAuthoredSupported; os.Write32(3 + (sendYear? 1: 0)); //number of props if (_artistSupported) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ArtistId)); os.Write16(static_cast<u16>(DataTypeCode::Uint32)); os.Write32(artist->Id.Id); } else { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Artist)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name + "--" + name + ".alb"); if (sendYear) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::DateAuthored)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(ConvertYear(year)); } auto album = std::make_shared<Album>(); album->Artist = artist; album->Name = name; album->Year = year; album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name); auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList); album->Id = response.ObjectId; _albums.insert(std::make_pair(std::make_pair(artist, name), album)); return album; } bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex) { if (!album) return false; LoadRefs(album); auto & tracks = album->Tracks; auto range = tracks.equal_range(name); for(auto i = range.first; i != range.second; ++i) { if (i->second == trackIndex) return true; } return false; } Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist, const AlbumPtr & album, ObjectFormat type, std::string name, const std::string & genre, int trackIndex, const std::string &filename, size_t size) { ByteArray propList; OutputStream os(propList); os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props if (_artistSupported) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ArtistId)); os.Write16(static_cast<u16>(DataTypeCode::Uint32)); os.Write32(artist->Id.Id); } else { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Artist)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); if (trackIndex) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Track)); os.Write16(static_cast<u16>(DataTypeCode::Uint16)); os.Write16(trackIndex); } if (!genre.empty()) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Genre)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(genre); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(filename); auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList); NewTrackInfo ti; ti.Id = response.ObjectId; ti.Name = name; ti.Index = trackIndex; return ti; } void Library::LoadRefs(AlbumPtr album) { if (!album || album->RefsLoaded) return; auto refs = _session->GetObjectReferences(album->Id).ObjectHandles; std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin())); for(auto trackId : refs) { auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name); auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track); debug("[", index, "]: ", name); album->Tracks.insert(std::make_pair(name, index)); } album->RefsLoaded = true; } void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti) { if (!album) return; LoadRefs(album); auto & refs = album->Refs; auto & tracks = album->Tracks; msg::ObjectHandles handles; std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles)); handles.ObjectHandles.push_back(ti.Id); _session->SetObjectReferences(album->Id, handles); refs.insert(ti.Id); tracks.insert(std::make_pair(ti.Name, ti.Index)); } bool Library::Supported(const mtp::SessionPtr & session) { auto & gdi = session->GetDeviceInfo(); return gdi.Supports(OperationCode::GetObjectPropList) && gdi.Supports(OperationCode::SendObjectPropList) && gdi.Supports(OperationCode::SetObjectReferences) && gdi.Supports(ObjectFormat::AbstractAudioAlbum); ; } } <commit_msg>use GetObjectPropList to get album/artist list<commit_after>#include <mtp/metadata/Library.h> #include <mtp/ptp/Session.h> #include <mtp/ptp/ObjectPropertyListParser.h> #include <mtp/log.h> #include <unordered_map> namespace mtp { namespace { const std::string UknownArtist ("UknownArtist"); const std::string UknownAlbum ("UknownAlbum"); const std::string VariousArtists ("VariousArtists"); } Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId) { NameToObjectIdMap list; ByteArray data = _session->GetObjectPropertyList(parentId, ObjectFormat::Association, ObjectProperty::ObjectFilename, 0, 1); ObjectPropertyListParser<std::string> parser; parser.Parse(data, [&](ObjectId id, ObjectProperty property, const std::string &name) { list.insert(std::make_pair(name, id)); }); return list; } ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name) { auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId); for (auto id : objects.ObjectHandles) { auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename); if (name == oname) return id; } return _session->CreateDirectory(name, parentId, _storage).ObjectId; } Library::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session) { auto storages = _session->GetStorageIDs(); if (storages.StorageIDs.empty()) throw std::runtime_error("no storages found"); u64 progress = 0, total = 0; if (reporter) reporter(State::Initialising, progress, total); _artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist); debug("device supports ObjectFormat::Artist: ", _artistSupported? "yes": "no"); { auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum); _albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end(); } _storage = storages.StorageIDs[0]; //picking up first storage. //zune fails to create artist/album without storage id { ByteArray data = _session->GetObjectPropertyList(Session::Root, ObjectFormat::Association, ObjectProperty::ObjectFilename, 0, 1); ObjectStringPropertyListParser::Parse(data, [&](ObjectId id, ObjectProperty property, const std::string &name) { if (name == "Artists") _artistsFolder = id; else if (name == "Albums") _albumsFolder = id; else if (name == "Music") _musicFolder = id; }); } if (_artistSupported && _artistsFolder == ObjectId()) _artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId; if (_albumsFolder == ObjectId()) _albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId; if (_musicFolder == ObjectId()) _musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId; debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0); debug("albums folder: ", _albumsFolder.Id); debug("music folder: ", _musicFolder.Id); auto musicFolders = ListAssociations(_musicFolder); using namespace mtp; ByteArray artists, albums; if (_artistSupported) { debug("getting artists..."); if (reporter) reporter(State::QueryingArtists, progress, total); artists = _session->GetObjectPropertyList(Session::Root, mtp::ObjectFormat::Artist, mtp::ObjectProperty::Name, 0, 1); HexDump("artists", artists); total += ObjectStringPropertyListParser::GetSize(artists); } { debug("getting albums..."); if (reporter) reporter(State::QueryingAlbums, progress, total); albums = _session->GetObjectPropertyList(Session::Root, mtp::ObjectFormat::AbstractAudioAlbum, mtp::ObjectProperty::Name, 0, 1); HexDump("albums", artists); total += ObjectStringPropertyListParser::GetSize(albums); } if (_artistSupported) { if (reporter) reporter(State::LoadingArtists, progress, total); ObjectStringPropertyListParser::Parse(artists, [&](ObjectId id, ObjectProperty property, const std::string &name) { debug("artist: ", name, "\t", id.Id); auto artist = std::make_shared<Artist>(); artist->Id = id; artist->Name = name; auto it = musicFolders.find(name); if (it != musicFolders.end()) artist->MusicFolderId = it->second; else artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId; _artists.insert(std::make_pair(name, artist)); if (reporter) reporter(State::LoadingArtists, ++progress, total); }); } if (reporter) reporter(State::LoadingAlbums, progress, total); std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders; ObjectStringPropertyListParser::Parse(albums, [&](ObjectId id, ObjectProperty property, const std::string &name) { auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist); std::string albumDate; if (_albumDateAuthoredSupported) albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored); auto artist = GetArtist(artistName); if (!artist) artist = CreateArtist(artistName); debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate); auto album = std::make_shared<Album>(); album->Name = name; album->Artist = artist; album->Id = id; album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0; if (albumFolders.find(artist) == albumFolders.end()) { albumFolders[artist] = ListAssociations(artist->MusicFolderId); } auto it = albumFolders.find(artist); if (it == albumFolders.end()) throw std::runtime_error("no iterator after insert, internal error"); const auto & albums = it->second; auto alit = albums.find(name); if (alit != albums.end()) album->MusicFolderId = alit->second; else album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId; _albums.insert(std::make_pair(std::make_pair(artist, name), album)); if (reporter) reporter(State::LoadingAlbums, ++progress, total); }); if (reporter) reporter(State::Loaded, progress, total); } Library::~Library() { } Library::ArtistPtr Library::GetArtist(std::string name) { if (name.empty()) name = UknownArtist; auto it = _artists.find(name); return it != _artists.end()? it->second: ArtistPtr(); } Library::ArtistPtr Library::CreateArtist(std::string name) { if (name.empty()) name = UknownArtist; auto artist = std::make_shared<Artist>(); artist->Name = name; artist->MusicFolderId = GetOrCreate(_musicFolder, name); if (_artistSupported) { ByteArray propList; OutputStream os(propList); os.Write32(2); //number of props os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name + ".art"); auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList); artist->Id = response.ObjectId; } _artists.insert(std::make_pair(name, artist)); return artist; } Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name) { if (name.empty()) name = UknownAlbum; auto it = _albums.find(std::make_pair(artist, name)); return it != _albums.end()? it->second: AlbumPtr(); } Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year) { if (!artist) throw std::runtime_error("artists is required"); if (name.empty()) name = UknownAlbum; ByteArray propList; OutputStream os(propList); bool sendYear = year != 0 && _albumDateAuthoredSupported; os.Write32(3 + (sendYear? 1: 0)); //number of props if (_artistSupported) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ArtistId)); os.Write16(static_cast<u16>(DataTypeCode::Uint32)); os.Write32(artist->Id.Id); } else { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Artist)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name + "--" + name + ".alb"); if (sendYear) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::DateAuthored)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(ConvertYear(year)); } auto album = std::make_shared<Album>(); album->Artist = artist; album->Name = name; album->Year = year; album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name); auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList); album->Id = response.ObjectId; _albums.insert(std::make_pair(std::make_pair(artist, name), album)); return album; } bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex) { if (!album) return false; LoadRefs(album); auto & tracks = album->Tracks; auto range = tracks.equal_range(name); for(auto i = range.first; i != range.second; ++i) { if (i->second == trackIndex) return true; } return false; } Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist, const AlbumPtr & album, ObjectFormat type, std::string name, const std::string & genre, int trackIndex, const std::string &filename, size_t size) { ByteArray propList; OutputStream os(propList); os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props if (_artistSupported) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ArtistId)); os.Write16(static_cast<u16>(DataTypeCode::Uint32)); os.Write32(artist->Id.Id); } else { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Artist)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); if (trackIndex) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Track)); os.Write16(static_cast<u16>(DataTypeCode::Uint16)); os.Write16(trackIndex); } if (!genre.empty()) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Genre)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(genre); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(filename); auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList); NewTrackInfo ti; ti.Id = response.ObjectId; ti.Name = name; ti.Index = trackIndex; return ti; } void Library::LoadRefs(AlbumPtr album) { if (!album || album->RefsLoaded) return; auto refs = _session->GetObjectReferences(album->Id).ObjectHandles; std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin())); for(auto trackId : refs) { auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name); auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track); debug("[", index, "]: ", name); album->Tracks.insert(std::make_pair(name, index)); } album->RefsLoaded = true; } void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti) { if (!album) return; LoadRefs(album); auto & refs = album->Refs; auto & tracks = album->Tracks; msg::ObjectHandles handles; std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles)); handles.ObjectHandles.push_back(ti.Id); _session->SetObjectReferences(album->Id, handles); refs.insert(ti.Id); tracks.insert(std::make_pair(ti.Name, ti.Index)); } bool Library::Supported(const mtp::SessionPtr & session) { auto & gdi = session->GetDeviceInfo(); return gdi.Supports(OperationCode::GetObjectPropList) && gdi.Supports(OperationCode::SendObjectPropList) && gdi.Supports(OperationCode::SetObjectReferences) && gdi.Supports(ObjectFormat::AbstractAudioAlbum); ; } } <|endoftext|>
<commit_before>#include <algorithm> #include <vector> #include <endian.h> #define LOGLEVEL VERBOSE #include "utils/logging.h" #include "nmranet/GlobalEventHandler.hxx" #include "nmranet/NMRAnetEventRegistry.hxx" #include "if/nmranet_if.h" #include "core/nmranet_event.h" #include "nmranet/EventHandlerTemplates.hxx" #include "nmranet/EventManager.hxx" /*static*/ GlobalEventFlow* GlobalEventFlow::instance = nullptr; struct GlobalEventFlow::Impl { Impl(int max_event_slots) : pending_sem_(max_event_slots) {} // This is the queue of events that are coming from the read thread to the // handler thread. Every "released" event is a new incoming event message. TypedAllocator<GlobalEventMessage> event_queue_; // This is the queue of global identify events. TypedAllocator<GlobalEventMessage> global_event_queue_; // Incoming event message, as it got off the event_queue. GlobalEventMessage* message_; // Statically allocated structure for calling the event handlers from the // main event queue. EventReport main_event_report_; // Each allocated GlobalEventMessage holds one value in this semaphore. OSSem pending_sem_; // The implementation of the iterators. std::unique_ptr<NMRAnetEventHandler> handler_; }; GlobalEventFlow::GlobalEventFlow(Executor* executor, int max_event_slots) : ControlFlow(executor, CrashNotifiable::DefaultInstance()), impl_(new Impl(max_event_slots)) { impl_->handler_.reset(new VectorEventHandlers(executor)); StartFlowAt(ST(WaitForEvent)); } GlobalEventFlow::~GlobalEventFlow() {} ControlFlow::ControlFlowAction GlobalEventFlow::WaitForEvent() { LOG(VERBOSE, "GlobalFlow::WaitForEvent"); return Allocate(&impl_->event_queue_, ST(HandleEventArrived)); } ControlFlow::ControlFlowAction GlobalEventFlow::HandleEventArrived() { LOG(VERBOSE, "GlobalFlow::EventArrived"); GetAllocationResult(&impl_->message_); return Allocate(&event_handler_mutex, ST(HandleEvent)); } void DecodeRange(EventReport* r) { uint64_t e = r->event; if (e & 1) { r->mask = (e ^ (e + 1)) >> 1; } else { r->mask = (e ^ (e - 1)) >> 1; } r->event &= ~r->mask; } ControlFlow::ControlFlowAction GlobalEventFlow::HandleEvent() { LOG(VERBOSE, "GlobalFlow::HandleEvent"); EventReport* rep = &impl_->main_event_report_; rep->src_node = impl_->message_->src_node; rep->dst_node = impl_->message_->dst_node; rep->event = impl_->message_->event; rep->mask = EVENT_EXACT_MASK; EventHandlerFunction fn; switch (impl_->message_->mti) { case MTI_EVENT_REPORT: fn = &NMRAnetEventHandler::HandleEventReport; break; case MTI_CONSUMER_IDENTIFY: fn = &NMRAnetEventHandler::HandleIdentifyConsumer; break; case MTI_CONSUMER_IDENTIFIED_RANGE: DecodeRange(rep); fn = &NMRAnetEventHandler::HandleConsumerRangeIdentified; break; case MTI_CONSUMER_IDENTIFIED_UNKNOWN: rep->state = UNKNOWN; fn = &NMRAnetEventHandler::HandleConsumerIdentified; break; case MTI_CONSUMER_IDENTIFIED_VALID: rep->state = VALID; fn = &NMRAnetEventHandler::HandleConsumerIdentified; break; case MTI_CONSUMER_IDENTIFIED_INVALID: rep->state = INVALID; fn = &NMRAnetEventHandler::HandleConsumerIdentified; break; case MTI_CONSUMER_IDENTIFIED_RESERVED: rep->state = RESERVED; fn = &NMRAnetEventHandler::HandleConsumerIdentified; break; case MTI_PRODUCER_IDENTIFY: fn = &NMRAnetEventHandler::HandleIdentifyProducer; break; case MTI_PRODUCER_IDENTIFIED_RANGE: DecodeRange(rep); fn = &NMRAnetEventHandler::HandleProducerRangeIdentified; break; case MTI_PRODUCER_IDENTIFIED_UNKNOWN: rep->state = UNKNOWN; fn = &NMRAnetEventHandler::HandleProducerIdentified; break; case MTI_PRODUCER_IDENTIFIED_VALID: rep->state = VALID; fn = &NMRAnetEventHandler::HandleProducerIdentified; break; case MTI_PRODUCER_IDENTIFIED_INVALID: rep->state = INVALID; fn = &NMRAnetEventHandler::HandleProducerIdentified; break; case MTI_PRODUCER_IDENTIFIED_RESERVED: rep->state = RESERVED; fn = &NMRAnetEventHandler::HandleProducerIdentified; break; case MTI_EVENTS_IDENTIFY_ADDRESSED: case MTI_EVENTS_IDENTIFY_GLOBAL: fn = &NMRAnetEventHandler::HandleIdentifyGlobal; break; default: DIE("Unexpected message arrived at the global event handler."); } // case FreeMessage(impl_->message_); (impl_->handler_.get()->*fn)(rep, this); // We insert an intermediate state to consume any pending notifications. return WaitAndCall(ST(HandlerFinished)); } ControlFlow::ControlFlowAction GlobalEventFlow::WaitForHandler() { return WaitAndCall(ST(HandlerFinished)); } ControlFlow::ControlFlowAction GlobalEventFlow::HandlerFinished() { LOG(VERBOSE, "GlobalFlow::HandlerFinished"); // @TODO(balazs.racz): When there is a new event in the main event queue, we // shouldn't release the mutex but go straight to the acquisition. event_handler_mutex.Unlock(); return CallImmediately(ST(WaitForEvent)); } GlobalEventMessage* GlobalEventFlow::AllocateMessage() { impl_->pending_sem_.wait(); return new GlobalEventMessage(); } void GlobalEventFlow::PostEvent(GlobalEventMessage* message) { impl_->event_queue_.TypedReleaseBack(message); } void GlobalEventFlow::FreeMessage(GlobalEventMessage* m) { delete m; impl_->pending_sem_.post(); } #ifdef CPP_EVENT_HANDLER /** Process an event packet. * @param mti Message Type Indicator * @param node node that the packet is addressed to * @param data NMRAnet packet data */ extern "C" { void nmranet_event_packet_addressed(uint16_t mti, node_handle_t src, node_t node, const void* data) { /*struct id_node* id_node = node; if (id_node->priv->state == NODE_UNINITIALIZED) { return; }*/ GlobalEventMessage* m = GlobalEventFlow::instance->AllocateMessage(); m->mti = mti; m->dst_node = node; m->src_node = src; m->event = 0; if (data) { memcpy(&m->event, data, sizeof(uint64_t)); m->event = be64toh(m->event); } GlobalEventFlow::instance->PostEvent(m); /* switch (mti) { default: break; case MTI_CONSUMER_IDENTIFY: // nmranet_identify_consumers(node, event, EVENT_EXACT_MASK); break; case MTI_CONSUMER_IDENTIFIED_RANGE: // nmranet_identify_consumers(node, event, identify_range_mask(event)); break; case MTI_CONSUMER_IDENTIFIED_UNKNOWN: // fall through case MTI_CONSUMER_IDENTIFIED_VALID: // fall through case MTI_CONSUMER_IDENTIFIED_INVALID: // fall through case MTI_CONSUMER_IDENTIFIED_RESERVED: break; case MTI_PRODUCER_IDENTIFY: // nmranet_identify_producers(node, event, EVENT_EXACT_MASK); break; case MTI_PRODUCER_IDENTIFIED_RANGE: // nmranet_identify_producers(node, event, identify_range_mask(event)); break; case MTI_PRODUCER_IDENTIFIED_UNKNOWN: // fall through case MTI_PRODUCER_IDENTIFIED_VALID: // fall through case MTI_PRODUCER_IDENTIFIED_INVALID: // fall through case MTI_PRODUCER_IDENTIFIED_RESERVED: break; case MTI_EVENTS_IDENTIFY_ADDRESSED: // fall through case MTI_EVENTS_IDENTIFY_GLOBAL: // nmranet_identify_consumers(node, 0, EVENT_ALL_MASK); // nmranet_identify_producers(node, 0, EVENT_ALL_MASK); break; }*/ } /** Process an event packet. * @param mti Message Type Indicator * @param src source Node ID * @param data NMRAnet packet data */ void nmranet_event_packet_global(uint16_t mti, node_handle_t src, const void* data) { GlobalEventMessage* m = GlobalEventFlow::instance->AllocateMessage(); m->mti = mti; m->dst_node = nullptr; m->src_node = src; m->event = 0; if (data) { memcpy(&m->event, data, sizeof(uint64_t)); m->event = be64toh(m->event); } GlobalEventFlow::instance->PostEvent(m); /* switch (mti) { default: break; case MTI_EVENT_REPORT: { // to save processing time in instantiations that include a large // number of nodes, consumers are sorted at the event level and // not at the node level. struct event_node* event_node; struct event_node event_lookup; uint64_t event; memcpy(&event, data, sizeof(uint64_t)); event = be64toh(event); event_lookup.event = event; event_node = RB_FIND(event_tree, &eventHead, &event_lookup); if (event_node) { for (EventPriv* current = event_node->priv; current != NULL; current = current->next) { event_post(current->node, src, event); } } break; } case MTI_CONSUMER_IDENTIFY: // fall through case MTI_CONSUMER_IDENTIFIED_RANGE: // fall through case MTI_CONSUMER_IDENTIFIED_UNKNOWN: // fall through case MTI_CONSUMER_IDENTIFIED_VALID: // fall through case MTI_CONSUMER_IDENTIFIED_INVALID: // fall through case MTI_CONSUMER_IDENTIFIED_RESERVED: // fall through case MTI_PRODUCER_IDENTIFY: // fall through case MTI_PRODUCER_IDENTIFIED_RANGE: // fall through case MTI_PRODUCER_IDENTIFIED_UNKNOWN: // fall through case MTI_PRODUCER_IDENTIFIED_VALID: // fall through case MTI_PRODUCER_IDENTIFIED_INVALID: // fall through case MTI_PRODUCER_IDENTIFIED_RESERVED: // fall through case MTI_EVENTS_IDENTIFY_GLOBAL: // os_mutex_lock(&nodeMutex); // global message, deliver all, non-subscribe for (node_t node = nmranet_node_next(NULL); node != NULL; node = nmranet_node_next(node)) { nmranet_event_packet_addressed(mti, node, data); } os_mutex_unlock(&nodeMutex); break; } */ } // This is a trick we play on the linker to pull in these symbols. Otherwise we // won't be able to link the binary, since there are back-references to these // symbols from lower-level libraries. void (*unused_f)(node_t, uint64_t, uint64_t)=&nmranet_identify_consumers; void (*unused_g)(node_t, uint64_t, uint64_t)=&nmranet_identify_producers; } // extern C #endif // CPP_EVENT_HANDLER <commit_msg>Fixes bug when the mask was interpreted inverted compared to the implementation.<commit_after>#include <algorithm> #include <vector> #include <endian.h> #define LOGLEVEL VERBOSE #include "utils/logging.h" #include "nmranet/GlobalEventHandler.hxx" #include "nmranet/NMRAnetEventRegistry.hxx" #include "if/nmranet_if.h" #include "core/nmranet_event.h" #include "nmranet/EventHandlerTemplates.hxx" #include "nmranet/EventManager.hxx" /*static*/ GlobalEventFlow* GlobalEventFlow::instance = nullptr; struct GlobalEventFlow::Impl { Impl(int max_event_slots) : pending_sem_(max_event_slots) {} // This is the queue of events that are coming from the read thread to the // handler thread. Every "released" event is a new incoming event message. TypedAllocator<GlobalEventMessage> event_queue_; // This is the queue of global identify events. TypedAllocator<GlobalEventMessage> global_event_queue_; // Incoming event message, as it got off the event_queue. GlobalEventMessage* message_; // Statically allocated structure for calling the event handlers from the // main event queue. EventReport main_event_report_; // Each allocated GlobalEventMessage holds one value in this semaphore. OSSem pending_sem_; // The implementation of the iterators. std::unique_ptr<NMRAnetEventHandler> handler_; }; GlobalEventFlow::GlobalEventFlow(Executor* executor, int max_event_slots) : ControlFlow(executor, CrashNotifiable::DefaultInstance()), impl_(new Impl(max_event_slots)) { impl_->handler_.reset(new VectorEventHandlers(executor)); StartFlowAt(ST(WaitForEvent)); } GlobalEventFlow::~GlobalEventFlow() {} ControlFlow::ControlFlowAction GlobalEventFlow::WaitForEvent() { LOG(VERBOSE, "GlobalFlow::WaitForEvent"); return Allocate(&impl_->event_queue_, ST(HandleEventArrived)); } ControlFlow::ControlFlowAction GlobalEventFlow::HandleEventArrived() { LOG(VERBOSE, "GlobalFlow::EventArrived"); GetAllocationResult(&impl_->message_); return Allocate(&event_handler_mutex, ST(HandleEvent)); } void DecodeRange(EventReport* r) { uint64_t e = r->event; if (e & 1) { r->mask = (e ^ (e + 1)) >> 1; } else { r->mask = (e ^ (e - 1)) >> 1; } r->event &= ~r->mask; } ControlFlow::ControlFlowAction GlobalEventFlow::HandleEvent() { LOG(VERBOSE, "GlobalFlow::HandleEvent"); EventReport* rep = &impl_->main_event_report_; rep->src_node = impl_->message_->src_node; rep->dst_node = impl_->message_->dst_node; rep->event = impl_->message_->event; rep->mask = 1; EventHandlerFunction fn; switch (impl_->message_->mti) { case MTI_EVENT_REPORT: fn = &NMRAnetEventHandler::HandleEventReport; break; case MTI_CONSUMER_IDENTIFY: fn = &NMRAnetEventHandler::HandleIdentifyConsumer; break; case MTI_CONSUMER_IDENTIFIED_RANGE: DecodeRange(rep); fn = &NMRAnetEventHandler::HandleConsumerRangeIdentified; break; case MTI_CONSUMER_IDENTIFIED_UNKNOWN: rep->state = UNKNOWN; fn = &NMRAnetEventHandler::HandleConsumerIdentified; break; case MTI_CONSUMER_IDENTIFIED_VALID: rep->state = VALID; fn = &NMRAnetEventHandler::HandleConsumerIdentified; break; case MTI_CONSUMER_IDENTIFIED_INVALID: rep->state = INVALID; fn = &NMRAnetEventHandler::HandleConsumerIdentified; break; case MTI_CONSUMER_IDENTIFIED_RESERVED: rep->state = RESERVED; fn = &NMRAnetEventHandler::HandleConsumerIdentified; break; case MTI_PRODUCER_IDENTIFY: fn = &NMRAnetEventHandler::HandleIdentifyProducer; break; case MTI_PRODUCER_IDENTIFIED_RANGE: DecodeRange(rep); fn = &NMRAnetEventHandler::HandleProducerRangeIdentified; break; case MTI_PRODUCER_IDENTIFIED_UNKNOWN: rep->state = UNKNOWN; fn = &NMRAnetEventHandler::HandleProducerIdentified; break; case MTI_PRODUCER_IDENTIFIED_VALID: rep->state = VALID; fn = &NMRAnetEventHandler::HandleProducerIdentified; break; case MTI_PRODUCER_IDENTIFIED_INVALID: rep->state = INVALID; fn = &NMRAnetEventHandler::HandleProducerIdentified; break; case MTI_PRODUCER_IDENTIFIED_RESERVED: rep->state = RESERVED; fn = &NMRAnetEventHandler::HandleProducerIdentified; break; case MTI_EVENTS_IDENTIFY_ADDRESSED: case MTI_EVENTS_IDENTIFY_GLOBAL: fn = &NMRAnetEventHandler::HandleIdentifyGlobal; break; default: DIE("Unexpected message arrived at the global event handler."); } // case FreeMessage(impl_->message_); (impl_->handler_.get()->*fn)(rep, this); // We insert an intermediate state to consume any pending notifications. return WaitAndCall(ST(HandlerFinished)); } ControlFlow::ControlFlowAction GlobalEventFlow::WaitForHandler() { return WaitAndCall(ST(HandlerFinished)); } ControlFlow::ControlFlowAction GlobalEventFlow::HandlerFinished() { LOG(VERBOSE, "GlobalFlow::HandlerFinished"); // @TODO(balazs.racz): When there is a new event in the main event queue, we // shouldn't release the mutex but go straight to the acquisition. event_handler_mutex.Unlock(); return CallImmediately(ST(WaitForEvent)); } GlobalEventMessage* GlobalEventFlow::AllocateMessage() { impl_->pending_sem_.wait(); return new GlobalEventMessage(); } void GlobalEventFlow::PostEvent(GlobalEventMessage* message) { impl_->event_queue_.TypedReleaseBack(message); } void GlobalEventFlow::FreeMessage(GlobalEventMessage* m) { delete m; impl_->pending_sem_.post(); } #ifdef CPP_EVENT_HANDLER /** Process an event packet. * @param mti Message Type Indicator * @param node node that the packet is addressed to * @param data NMRAnet packet data */ extern "C" { void nmranet_event_packet_addressed(uint16_t mti, node_handle_t src, node_t node, const void* data) { /*struct id_node* id_node = node; if (id_node->priv->state == NODE_UNINITIALIZED) { return; }*/ GlobalEventMessage* m = GlobalEventFlow::instance->AllocateMessage(); m->mti = mti; m->dst_node = node; m->src_node = src; m->event = 0; if (data) { memcpy(&m->event, data, sizeof(uint64_t)); m->event = be64toh(m->event); } GlobalEventFlow::instance->PostEvent(m); /* switch (mti) { default: break; case MTI_CONSUMER_IDENTIFY: // nmranet_identify_consumers(node, event, EVENT_EXACT_MASK); break; case MTI_CONSUMER_IDENTIFIED_RANGE: // nmranet_identify_consumers(node, event, identify_range_mask(event)); break; case MTI_CONSUMER_IDENTIFIED_UNKNOWN: // fall through case MTI_CONSUMER_IDENTIFIED_VALID: // fall through case MTI_CONSUMER_IDENTIFIED_INVALID: // fall through case MTI_CONSUMER_IDENTIFIED_RESERVED: break; case MTI_PRODUCER_IDENTIFY: // nmranet_identify_producers(node, event, EVENT_EXACT_MASK); break; case MTI_PRODUCER_IDENTIFIED_RANGE: // nmranet_identify_producers(node, event, identify_range_mask(event)); break; case MTI_PRODUCER_IDENTIFIED_UNKNOWN: // fall through case MTI_PRODUCER_IDENTIFIED_VALID: // fall through case MTI_PRODUCER_IDENTIFIED_INVALID: // fall through case MTI_PRODUCER_IDENTIFIED_RESERVED: break; case MTI_EVENTS_IDENTIFY_ADDRESSED: // fall through case MTI_EVENTS_IDENTIFY_GLOBAL: // nmranet_identify_consumers(node, 0, EVENT_ALL_MASK); // nmranet_identify_producers(node, 0, EVENT_ALL_MASK); break; }*/ } /** Process an event packet. * @param mti Message Type Indicator * @param src source Node ID * @param data NMRAnet packet data */ void nmranet_event_packet_global(uint16_t mti, node_handle_t src, const void* data) { GlobalEventMessage* m = GlobalEventFlow::instance->AllocateMessage(); m->mti = mti; m->dst_node = nullptr; m->src_node = src; m->event = 0; if (data) { memcpy(&m->event, data, sizeof(uint64_t)); m->event = be64toh(m->event); } GlobalEventFlow::instance->PostEvent(m); /* switch (mti) { default: break; case MTI_EVENT_REPORT: { // to save processing time in instantiations that include a large // number of nodes, consumers are sorted at the event level and // not at the node level. struct event_node* event_node; struct event_node event_lookup; uint64_t event; memcpy(&event, data, sizeof(uint64_t)); event = be64toh(event); event_lookup.event = event; event_node = RB_FIND(event_tree, &eventHead, &event_lookup); if (event_node) { for (EventPriv* current = event_node->priv; current != NULL; current = current->next) { event_post(current->node, src, event); } } break; } case MTI_CONSUMER_IDENTIFY: // fall through case MTI_CONSUMER_IDENTIFIED_RANGE: // fall through case MTI_CONSUMER_IDENTIFIED_UNKNOWN: // fall through case MTI_CONSUMER_IDENTIFIED_VALID: // fall through case MTI_CONSUMER_IDENTIFIED_INVALID: // fall through case MTI_CONSUMER_IDENTIFIED_RESERVED: // fall through case MTI_PRODUCER_IDENTIFY: // fall through case MTI_PRODUCER_IDENTIFIED_RANGE: // fall through case MTI_PRODUCER_IDENTIFIED_UNKNOWN: // fall through case MTI_PRODUCER_IDENTIFIED_VALID: // fall through case MTI_PRODUCER_IDENTIFIED_INVALID: // fall through case MTI_PRODUCER_IDENTIFIED_RESERVED: // fall through case MTI_EVENTS_IDENTIFY_GLOBAL: // os_mutex_lock(&nodeMutex); // global message, deliver all, non-subscribe for (node_t node = nmranet_node_next(NULL); node != NULL; node = nmranet_node_next(node)) { nmranet_event_packet_addressed(mti, node, data); } os_mutex_unlock(&nodeMutex); break; } */ } // This is a trick we play on the linker to pull in these symbols. Otherwise we // won't be able to link the binary, since there are back-references to these // symbols from lower-level libraries. void (*unused_f)(node_t, uint64_t, uint64_t)=&nmranet_identify_consumers; void (*unused_g)(node_t, uint64_t, uint64_t)=&nmranet_identify_producers; } // extern C #endif // CPP_EVENT_HANDLER <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of meegotouch-controlpanelapplets. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "offlinebrief.h" #include <DcpWidgetTypes> #include <MApplication> #include <MBanner> #include <MMessageBox> #include <MLabel> #define DEBUG #include "../debug.h" #ifdef HAVE_QMSYSTEM OfflineBrief::OfflineBrief () : m_DevMode (new QmDeviceMode()), m_infoBanner (0) { connect (m_DevMode, SIGNAL (deviceModeChanged (MeeGo::QmDeviceMode::DeviceMode)), SLOT (devModeChanged (MeeGo::QmDeviceMode::DeviceMode))); m_LastMode = m_DevMode->getMode(); } #else OfflineBrief::OfflineBrief (), m_infoBanner (0) { /* * FIXME: To install a version that works without the help of the QmSystem * library. */ } #endif OfflineBrief::~OfflineBrief() { #ifdef HAVE_QMSYSTEM delete m_DevMode; #endif } #ifdef HAVE_QMSYSTEM void OfflineBrief::devModeChanged ( MeeGo::QmDeviceMode::DeviceMode mode) { SYS_DEBUG("newmode %d", mode); m_LastMode = mode; emit valuesChanged(); } #endif QString OfflineBrief::titleText () const { //% "Flight mode" return qtTrId ("qtn_sett_main_flightmode"); } QString OfflineBrief::valueText() const { #if 0 return currentText(); #endif return ""; } QString OfflineBrief::currentText() const { #ifdef HAVE_QMSYSTEM switch (m_LastMode) { case QmDeviceMode::Flight: //% "Deactivate offline mode" return qtTrId("qtn_offl_deactivate"); case QmDeviceMode::Normal: default: //% "Activate offline mode" return qtTrId("qtn_offl_activate"); } #endif return QString("No QmSystem"); } bool OfflineBrief::toggle () const { return (m_LastMode == QmDeviceMode::Flight); } void OfflineBrief::setToggle ( bool toggle) { SYS_DEBUG ("toggle = %s", SYS_BOOL (toggle)); /* * Don't do anything if we already in the desired mode */ if (toggle && m_LastMode == QmDeviceMode::Flight) return; else if ((! toggle) && m_LastMode == QmDeviceMode::Normal) return; #ifdef HAVE_QMSYSTEM if (! toggle) { //% "Exit offline mode?" MMessageBox* dialog = new MMessageBox ("", qtTrId("qtn_offl_exiting"), M::YesButton | M::NoButton); /* * This will set the 'Normal' mode if dialog accepted */ connect (dialog, SIGNAL (accepted ()), SLOT (processDialogResult ())); /* * This will switch back the button for the proper state */ connect (dialog, SIGNAL (rejected ()), this, SIGNAL (valuesChanged ())); dialog->appear (MApplication::activeWindow (), MSceneWindow::DestroyWhenDone); } else { bool success = m_DevMode->setMode (QmDeviceMode::Flight); SYS_DEBUG ("m_DevMode->setMode (Flight) success: %s", SYS_BOOL (success)); if (success) { if (! m_infoBanner) { m_infoBanner = new MBanner; m_infoBanner->setStyleName ("InformationBanner"); m_infoBanner->setObjectName ("InfoBanner"); } //% "Closing all connections. Switching to offline mode." m_infoBanner->setTitle (qtTrId ("qtn_offl_entering")); m_infoBanner->appear (MApplication::activeWindow ()); } } #endif } /* * FIXME: This slot is only called when the dialog is accepted... * Re-name this at once... */ void OfflineBrief::processDialogResult () { #ifdef HAVE_QMSYSTEM bool success = m_DevMode->setMode (QmDeviceMode::Normal); SYS_DEBUG ("m_DevMode->setMode (Normal) success: %s", SYS_BOOL (success)); emit valuesChanged(); #endif } int OfflineBrief::widgetTypeID () const { return DcpWidgetType::Toggle; } <commit_msg>Changes: possible crash fix2<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of meegotouch-controlpanelapplets. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "offlinebrief.h" #include <DcpWidgetTypes> #include <MApplication> #include <MBanner> #include <MMessageBox> #include <MLabel> #define DEBUG #include "../debug.h" #ifdef HAVE_QMSYSTEM OfflineBrief::OfflineBrief () : m_DevMode (new QmDeviceMode()), m_infoBanner (0) { connect (m_DevMode, SIGNAL (deviceModeChanged (MeeGo::QmDeviceMode::DeviceMode)), SLOT (devModeChanged (MeeGo::QmDeviceMode::DeviceMode))); m_LastMode = m_DevMode->getMode(); } #else OfflineBrief::OfflineBrief (), m_infoBanner (0) { /* * FIXME: To install a version that works without the help of the QmSystem * library. */ } #endif OfflineBrief::~OfflineBrief() { #ifdef HAVE_QMSYSTEM delete m_DevMode; #endif } #ifdef HAVE_QMSYSTEM void OfflineBrief::devModeChanged ( MeeGo::QmDeviceMode::DeviceMode mode) { SYS_DEBUG("newmode %d", mode); m_LastMode = mode; emit valuesChanged(); } #endif QString OfflineBrief::titleText () const { //% "Flight mode" return qtTrId ("qtn_sett_main_flightmode"); } QString OfflineBrief::valueText() const { #if 0 return currentText(); #endif return ""; } QString OfflineBrief::currentText() const { #ifdef HAVE_QMSYSTEM switch (m_LastMode) { case QmDeviceMode::Flight: //% "Deactivate offline mode" return qtTrId("qtn_offl_deactivate"); case QmDeviceMode::Normal: default: //% "Activate offline mode" return qtTrId("qtn_offl_activate"); } #endif return QString("No QmSystem"); } bool OfflineBrief::toggle () const { return (m_LastMode == QmDeviceMode::Flight); } void OfflineBrief::setToggle ( bool toggle) { SYS_DEBUG ("toggle = %s", SYS_BOOL (toggle)); /* * Don't do anything if we already in the desired mode */ if (toggle && m_LastMode == QmDeviceMode::Flight) return; else if ((! toggle) && m_LastMode == QmDeviceMode::Normal) return; #ifdef HAVE_QMSYSTEM if (! toggle) { //% "Exit offline mode?" MMessageBox* dialog = new MMessageBox ("", qtTrId("qtn_offl_exiting"), M::YesButton | M::NoButton); /* * This will set the 'Normal' mode if dialog accepted */ connect (dialog, SIGNAL (accepted ()), SLOT (processDialogResult ())); /* * This will switch back the button for the proper state */ connect (dialog, SIGNAL (rejected ()), this, SIGNAL (valuesChanged ())); dialog->appear (MApplication::activeWindow (), MSceneWindow::DestroyWhenDone); } else { bool success = m_DevMode->setMode (QmDeviceMode::Flight); SYS_DEBUG ("m_DevMode->setMode (Flight) success: %s", SYS_BOOL (success)); if (success) { m_infoBanner = new MBanner; m_infoBanner->setStyleName ("InformationBanner"); m_infoBanner->setObjectName ("InfoBanner"); //% "Closing all connections. Switching to offline mode." m_infoBanner->setTitle (qtTrId ("qtn_offl_entering")); m_infoBanner->appear ( MApplication::activeWindow (), MSceneWindow::DestroyWhenDone); // Set to NULL, as will destroy itself m_infoBanner = 0; } } #endif } /* * FIXME: This slot is only called when the dialog is accepted... * Re-name this at once... */ void OfflineBrief::processDialogResult () { #ifdef HAVE_QMSYSTEM bool success = m_DevMode->setMode (QmDeviceMode::Normal); SYS_DEBUG ("m_DevMode->setMode (Normal) success: %s", SYS_BOOL (success)); emit valuesChanged(); #endif } int OfflineBrief::widgetTypeID () const { return DcpWidgetType::Toggle; } <|endoftext|>
<commit_before>// This program compares the performance of appending many short strings // using different facilities. #include <cstdlib> #include <cstdio> #include <vector> #include <string> #include <sstream> #include <iostream> #include <clue/timing.hpp> using namespace std; using namespace clue; class WithStringStream { private: stringstream sstr_; public: const char *repr() const { return "with-stringstream"; } void reset() { sstr_.str(""); } string str() const { return sstr_.str(); } void append(const string& s) { sstr_.write(s.c_str(), s.size()); sstr_.put(' '); } }; class WithStringBuf { private: stringbuf sbuf_; public: const char *repr() const { return "with-stringbuf"; } void reset() { sbuf_.str(""); } string str() const { return sbuf_.str(); } void append(const string& s) { sbuf_.sputn(s.c_str(), s.size()); sbuf_.sputc(' '); } }; class WithString { private: string str_; public: const char *repr() const { return "with-string"; } void reset() { str_.clear(); } string str() const { return str_; } void append(const string& s) { str_.append(s); str_.append(1, ' '); } }; class WithVectorChar { private: vector<char> vec_; public: const char *repr() const { return "with-vectorchar"; } void reset() { vec_.clear(); } string str() const { return string(vec_.data(), vec_.size()); } void append(const string& s) { vec_.insert(vec_.end(), s.data(), s.data() + s.size()); vec_.push_back(' '); } }; class WithManualBuffer { private: size_t cap_; size_t len_; char *buf_; public: WithManualBuffer() : cap_(4), len_(0), buf_((char*)malloc(sizeof(char) * cap_)) { } ~WithManualBuffer() { free(buf_); } WithManualBuffer(const WithManualBuffer&) = delete; WithManualBuffer& operator = (const WithManualBuffer&) = delete; const char *repr() const { return "with-manualbuf"; } void reset() { len_ = 0; } string str() const { return string(buf_, len_); } void append(const string& s) { _append(s.c_str(), s.size()); _append(" ", 1); } private: void _append(const char *s, size_t n) { size_t newlen = len_ + n; if (cap_ < newlen) { size_t newcap = cap_ * 2; while (newcap < newlen) newcap *= 2; buf_ = (char*)realloc(buf_, sizeof(char) * newcap); cap_ = newcap; } memcpy(buf_ + len_, s, n * sizeof(char)); len_ += n; } }; template<class S> void verify_correctness(S&& s, const vector<string>& tokens, const string& expect_str) { s.reset(); cout << " verifying " << s.repr() << endl;; for (const string& tk: tokens) { s.append(tk); } string result = s.str(); if (result != expect_str) { cout << " verification failed:" << endl; cout << " EXPECT: \"" << expect_str << "\"" << endl; cout << " ACTUAL: \"" << s.str() << "\"" << endl; exit(1); } } inline char randchar() { return 'a' + (rand() % 26); } inline const char* randstr(char *buf, size_t slen) { // actual length of buf must be at least slen + 1 for (size_t i = 0; i < slen; ++i) { buf[i] = randchar(); } buf[slen] = '\0'; return buf; } template<class S> void measure_performance(S &&s, const vector<string>& tokens) { auto f = [&]() { s.reset(); for (const string& tk: tokens) s.append(tk); }; auto r = calibrated_time(f); std::printf(" %-25s: %.6f secs/run\n", s.repr(), r.elapsed_secs / r.count_runs); } int main() { // competitors WithStringStream with_strstream; WithStringBuf with_strbuf; WithString with_string; WithVectorChar with_vecchar; WithManualBuffer with_manbuf; // verify the correctness vector<string> tokens0 { string("abc"), string("ef"), string("xyz") }; string expect_str("abc ef xyz "); cout << "Verifying correctness ..." << endl; verify_correctness(with_strstream, tokens0, expect_str); verify_correctness(with_strbuf, tokens0, expect_str); verify_correctness(with_string, tokens0, expect_str); verify_correctness(with_vecchar, tokens0, expect_str); verify_correctness(with_manbuf, tokens0, expect_str); // prepare data for performance measurement cout << "Preparing data ..." << endl; const size_t N = 1000000; const size_t slen = 4; char tkbuf[slen + 1]; vector<string> tokens; tokens.reserve(N); for (size_t i = 0; i < N; ++i) { tokens.emplace_back(randstr(tkbuf, slen)); } // measure performance cout << "Measuring performance ..." << endl; measure_performance(with_strstream, tokens); measure_performance(with_strbuf, tokens); measure_performance(with_string, tokens); measure_performance(with_vecchar, tokens); measure_performance(with_manbuf, tokens); return 0; } <commit_msg>fix memcpy missing problem<commit_after>// This program compares the performance of appending many short strings // using different facilities. #include <cstdlib> #include <cstdio> #include <cstring> #include <vector> #include <string> #include <sstream> #include <iostream> #include <clue/timing.hpp> using namespace std; using namespace clue; class WithStringStream { private: stringstream sstr_; public: const char *repr() const { return "with-stringstream"; } void reset() { sstr_.str(""); } string str() const { return sstr_.str(); } void append(const string& s) { sstr_.write(s.c_str(), s.size()); sstr_.put(' '); } }; class WithStringBuf { private: stringbuf sbuf_; public: const char *repr() const { return "with-stringbuf"; } void reset() { sbuf_.str(""); } string str() const { return sbuf_.str(); } void append(const string& s) { sbuf_.sputn(s.c_str(), s.size()); sbuf_.sputc(' '); } }; class WithString { private: string str_; public: const char *repr() const { return "with-string"; } void reset() { str_.clear(); } string str() const { return str_; } void append(const string& s) { str_.append(s); str_.append(1, ' '); } }; class WithVectorChar { private: vector<char> vec_; public: const char *repr() const { return "with-vectorchar"; } void reset() { vec_.clear(); } string str() const { return string(vec_.data(), vec_.size()); } void append(const string& s) { vec_.insert(vec_.end(), s.data(), s.data() + s.size()); vec_.push_back(' '); } }; class WithManualBuffer { private: size_t cap_; size_t len_; char *buf_; public: WithManualBuffer() : cap_(4), len_(0), buf_((char*)malloc(sizeof(char) * cap_)) { } ~WithManualBuffer() { free(buf_); } WithManualBuffer(const WithManualBuffer&) = delete; WithManualBuffer& operator = (const WithManualBuffer&) = delete; const char *repr() const { return "with-manualbuf"; } void reset() { len_ = 0; } string str() const { return string(buf_, len_); } void append(const string& s) { _append(s.c_str(), s.size()); _append(" ", 1); } private: void _append(const char *s, size_t n) { size_t newlen = len_ + n; if (cap_ < newlen) { size_t newcap = cap_ * 2; while (newcap < newlen) newcap *= 2; buf_ = (char*)realloc(buf_, sizeof(char) * newcap); cap_ = newcap; } std::memcpy(buf_ + len_, s, n * sizeof(char)); len_ += n; } }; template<class S> void verify_correctness(S&& s, const vector<string>& tokens, const string& expect_str) { s.reset(); cout << " verifying " << s.repr() << endl;; for (const string& tk: tokens) { s.append(tk); } string result = s.str(); if (result != expect_str) { cout << " verification failed:" << endl; cout << " EXPECT: \"" << expect_str << "\"" << endl; cout << " ACTUAL: \"" << s.str() << "\"" << endl; exit(1); } } inline char randchar() { return 'a' + (rand() % 26); } inline const char* randstr(char *buf, size_t slen) { // actual length of buf must be at least slen + 1 for (size_t i = 0; i < slen; ++i) { buf[i] = randchar(); } buf[slen] = '\0'; return buf; } template<class S> void measure_performance(S &&s, const vector<string>& tokens) { auto f = [&]() { s.reset(); for (const string& tk: tokens) s.append(tk); }; auto r = calibrated_time(f); std::printf(" %-25s: %.6f secs/run\n", s.repr(), r.elapsed_secs / r.count_runs); } int main() { // competitors WithStringStream with_strstream; WithStringBuf with_strbuf; WithString with_string; WithVectorChar with_vecchar; WithManualBuffer with_manbuf; // verify the correctness vector<string> tokens0 { string("abc"), string("ef"), string("xyz") }; string expect_str("abc ef xyz "); cout << "Verifying correctness ..." << endl; verify_correctness(with_strstream, tokens0, expect_str); verify_correctness(with_strbuf, tokens0, expect_str); verify_correctness(with_string, tokens0, expect_str); verify_correctness(with_vecchar, tokens0, expect_str); verify_correctness(with_manbuf, tokens0, expect_str); // prepare data for performance measurement cout << "Preparing data ..." << endl; const size_t N = 1000000; const size_t slen = 4; char tkbuf[slen + 1]; vector<string> tokens; tokens.reserve(N); for (size_t i = 0; i < N; ++i) { tokens.emplace_back(randstr(tkbuf, slen)); } // measure performance cout << "Measuring performance ..." << endl; measure_performance(with_strstream, tokens); measure_performance(with_strbuf, tokens); measure_performance(with_string, tokens); measure_performance(with_vecchar, tokens); measure_performance(with_manbuf, tokens); return 0; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "common/logger.h" namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { if (parse_tree.get() == nullptr) return NULL; std::shared_ptr<planner::AbstractPlan> plan_tree; //std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch(parse_item_node_type){ case PARSE_NODE_TYPE_SCAN: child_plan = new planner::SeqScanPlan(); break; } // if (child_plan != nullptr) { // if (plan_tree != nullptr) // plan_tree->AddChild(child_plan); // else // plan_tree = child_plan; // } return plan_tree; } } // namespace optimizer } // namespace peloton <commit_msg>Fix Simple Mistake<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "common/logger.h" namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { if (parse_tree.get() == nullptr) return NULL; std::shared_ptr<planner::AbstractPlan> plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch(parse_item_node_type){ case PARSE_NODE_TYPE_SCAN: child_plan = new planner::SeqScanPlan(); break; } // if (child_plan != nullptr) { // if (plan_tree != nullptr) // plan_tree->AddChild(child_plan); // else // plan_tree = child_plan; // } return plan_tree; } } // namespace optimizer } // namespace peloton <|endoftext|>
<commit_before>/* Copyright (C) 1998-2004 by Jorrit Tyberghein (C) 2003 by Philip Aumayr (C) 2004-2007 by Frank Richter This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgfx/imagememory.h" #include "csgfx/packrgb.h" #include "csgfx/rgbpixel.h" #include "csutil/blockallocator.h" #include "gl_render3d.h" #include "gl_txtmgr_basictex.h" #include "gl_txtmgr_lightmap.h" CS_PLUGIN_NAMESPACE_BEGIN(gl3d) { CS_LEAKGUARD_IMPLEMENT(csGLRendererLightmap); CS_LEAKGUARD_IMPLEMENT(csGLSuperLightmap); class csRLMAlloc : public csBlockAllocator<csGLRendererLightmap> { public: csRLMAlloc () : csBlockAllocator<csGLRendererLightmap> (512) { } }; CS_IMPLEMENT_STATIC_VAR (GetRLMAlloc, csRLMAlloc, ()) //--------------------------------------------------------------------------- void csGLRendererLightmap::DecRef () { csRefTrackerAccess::TrackDecRef (GetSCFObject(), scfRefCount); scfRefCount--; if (scfRefCount == 0) { CS_ASSERT (slm != 0); slm->FreeRLM (this); return; } } csGLRendererLightmap::csGLRendererLightmap () : scfImplementationType (this) { } csGLRendererLightmap::~csGLRendererLightmap () { #ifdef CS_DEBUG if (slm->texHandle != (GLuint)~0) { csRGBcolor* pat = new csRGBcolor[rect.Width () * rect.Height ()]; int x, y; csRGBcolor* p = pat; for (y = 0; y < rect.Height (); y++) { for (x = 0; x < rect.Width (); x++) { p->red = ((x ^ y) & 1) * 0xff; p++; } } csGLGraphics3D::statecache->SetTexture ( GL_TEXTURE_2D, slm->texHandle); glTexSubImage2D (GL_TEXTURE_2D, 0, rect.xmin, rect.ymin, rect.Width (), rect.Height (), GL_RGB, GL_UNSIGNED_BYTE, pat); delete[] pat; } #endif } void csGLRendererLightmap::GetSLMCoords (int& left, int& top, int& width, int& height) { left = rect.xmin; top = rect.ymin; width = rect.Width (); height = rect.Height (); } void csGLRendererLightmap::SetData (csRGBcolor* data) { slm->CreateTexture (); csGLGraphics3D::statecache->SetTexture ( GL_TEXTURE_2D, slm->texHandle); const uint8* packed = csPackRGB::PackRGBcolorToRGB (data, rect.Width () * rect.Height ()); glTexSubImage2D (GL_TEXTURE_2D, 0, rect.xmin, rect.ymin, rect.Width (), rect.Height (), GL_RGB, GL_UNSIGNED_BYTE, packed); csPackRGB::DiscardPackedRGB (packed); } void csGLRendererLightmap::SetLightCellSize (int size) { (void)size; } //--------------------------------------------------------------------------- void csGLSuperLightmap::DecRef () { csRefTrackerAccess::TrackDecRef (GetSCFObject(), scfRefCount); scfRefCount--; if (scfRefCount == 0) { if (txtmgr != 0) txtmgr->superLMs.Delete (this); delete this; return; } } csGLSuperLightmap::csGLSuperLightmap (csGLTextureManager* txtmgr, int width, int height) : scfImplementationType (this) { w = width; h = height; texHandle = (GLuint)~0; numRLMs = 0; csGLSuperLightmap::txtmgr = txtmgr; } csGLSuperLightmap::~csGLSuperLightmap () { DeleteTexture (); } void csGLSuperLightmap::CreateTexture () { if (texHandle == (GLuint)~0) { glGenTextures (1, &texHandle); csGLGraphics3D::statecache->SetTexture ( GL_TEXTURE_2D, texHandle); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); csRGBcolor* data = new csRGBcolor [w * h]; #ifdef CS_DEBUG // Fill the background for debugging purposes (to quickly see what's // a lightmap and what's not; esp. useful when LMs are rather dark - // would be hardly visible if at all on black) // And to have it not that boring, add a neat backdrop. static const uint16 debugBG[16] = {0x0000, 0x3222, 0x4a36, 0x422a, 0x3222, 0x0a22, 0x4a22, 0x33a2, 0x0000, 0x2232, 0x364a, 0x2a42, 0x2232, 0x220a, 0x224a, 0xa233}; csRGBcolor* p = data; int y, x; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { const int bitNum = 6; int b = (~x) & 0xf; int px = (debugBG[y & 0xf] & (1 << b)); if (b < bitNum) { px <<= bitNum - b; } else { px >>= b - bitNum; } p->blue = ~(1 << bitNum) + px; p++; } } #endif glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB8, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data); delete[] data; } } void csGLSuperLightmap::DeleteTexture () { if (texHandle != (GLuint)~0) { csGLTextureManager::UnsetTexture (GL_TEXTURE_2D, texHandle); glDeleteTextures (1, &texHandle); texHandle = (GLuint)~0; th = 0; } } void csGLSuperLightmap::FreeRLM (csGLRendererLightmap* rlm) { if (--numRLMs == 0) { DeleteTexture (); } // IncRef() ourselves manually. // Otherwise freeing the RLM could trigger our own destruction - // causing an assertion in block allocator (due to how BA frees items and // the safety assertions on BA destruction.) csRefTrackerAccess::TrackIncRef (this, scfRefCount); scfRefCount++; GetRLMAlloc ()->Free (rlm); DecRef (); } csPtr<iRendererLightmap> csGLSuperLightmap::RegisterLightmap (int left, int top, int width, int height) { csGLRendererLightmap* rlm = GetRLMAlloc ()->Alloc (); rlm->slm = this; rlm->rect.Set (left, top, left + width, top + height); numRLMs++; return csPtr<iRendererLightmap> (rlm); } csPtr<iImage> csGLSuperLightmap::Dump () { // @@@ hmm... or just return an empty image? if (texHandle == (GLuint)~0) return 0; GLint tw, th; csGLGraphics3D::statecache->SetTexture (GL_TEXTURE_2D, texHandle); glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &tw); glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &th); uint8* data = new uint8[tw * th * 4]; glGetTexImage (GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); csImageMemory* lmimg = new csImageMemory (tw, th, data, true, CS_IMGFMT_TRUECOLOR | CS_IMGFMT_ALPHA); return csPtr<iImage> (lmimg); } iTextureHandle* csGLSuperLightmap::GetTexture () { if (th == 0) { CreateTexture (); th.AttachNew (new csGLBasicTextureHandle ( txtmgr->G3D, iTextureHandle::texType2D, texHandle)); } return th; } } CS_PLUGIN_NAMESPACE_END(gl3d) <commit_msg> - Vincent reverted r28473 for one file at res' request.<commit_after>/* Copyright (C) 1998-2004 by Jorrit Tyberghein (C) 2003 by Philip Aumayr (C) 2004-2007 by Frank Richter This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgfx/imagememory.h" #include "csgfx/packrgb.h" #include "csgfx/rgbpixel.h" #include "csutil/blockallocator.h" #include "gl_render3d.h" #include "gl_txtmgr_basictex.h" #include "gl_txtmgr_lightmap.h" CS_PLUGIN_NAMESPACE_BEGIN(gl3d) { CS_LEAKGUARD_IMPLEMENT(csGLRendererLightmap); CS_LEAKGUARD_IMPLEMENT(csGLSuperLightmap); class csRLMAlloc : public csBlockAllocator<csGLRendererLightmap> { public: csRLMAlloc () : csBlockAllocator<csGLRendererLightmap> (512) { } }; CS_IMPLEMENT_STATIC_VAR (GetRLMAlloc, csRLMAlloc, ()) //--------------------------------------------------------------------------- void csGLRendererLightmap::DecRef () { csRefTrackerAccess::TrackDecRef (scfObject, scfRefCount); scfRefCount--; if (scfRefCount == 0) { CS_ASSERT (slm != 0); slm->FreeRLM (this); return; } } csGLRendererLightmap::csGLRendererLightmap () : scfImplementationType (this) { } csGLRendererLightmap::~csGLRendererLightmap () { #ifdef CS_DEBUG if (slm->texHandle != (GLuint)~0) { csRGBcolor* pat = new csRGBcolor[rect.Width () * rect.Height ()]; int x, y; csRGBcolor* p = pat; for (y = 0; y < rect.Height (); y++) { for (x = 0; x < rect.Width (); x++) { p->red = ((x ^ y) & 1) * 0xff; p++; } } csGLGraphics3D::statecache->SetTexture ( GL_TEXTURE_2D, slm->texHandle); glTexSubImage2D (GL_TEXTURE_2D, 0, rect.xmin, rect.ymin, rect.Width (), rect.Height (), GL_RGB, GL_UNSIGNED_BYTE, pat); delete[] pat; } #endif } void csGLRendererLightmap::GetSLMCoords (int& left, int& top, int& width, int& height) { left = rect.xmin; top = rect.ymin; width = rect.Width (); height = rect.Height (); } void csGLRendererLightmap::SetData (csRGBcolor* data) { slm->CreateTexture (); csGLGraphics3D::statecache->SetTexture ( GL_TEXTURE_2D, slm->texHandle); const uint8* packed = csPackRGB::PackRGBcolorToRGB (data, rect.Width () * rect.Height ()); glTexSubImage2D (GL_TEXTURE_2D, 0, rect.xmin, rect.ymin, rect.Width (), rect.Height (), GL_RGB, GL_UNSIGNED_BYTE, packed); csPackRGB::DiscardPackedRGB (packed); } void csGLRendererLightmap::SetLightCellSize (int size) { (void)size; } //--------------------------------------------------------------------------- void csGLSuperLightmap::DecRef () { csRefTrackerAccess::TrackDecRef (scfObject, scfRefCount); scfRefCount--; if (scfRefCount == 0) { if (txtmgr != 0) txtmgr->superLMs.Delete (this); delete this; return; } } csGLSuperLightmap::csGLSuperLightmap (csGLTextureManager* txtmgr, int width, int height) : scfImplementationType (this) { w = width; h = height; texHandle = (GLuint)~0; numRLMs = 0; csGLSuperLightmap::txtmgr = txtmgr; } csGLSuperLightmap::~csGLSuperLightmap () { DeleteTexture (); } void csGLSuperLightmap::CreateTexture () { if (texHandle == (GLuint)~0) { glGenTextures (1, &texHandle); csGLGraphics3D::statecache->SetTexture ( GL_TEXTURE_2D, texHandle); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); csRGBcolor* data = new csRGBcolor [w * h]; #ifdef CS_DEBUG // Fill the background for debugging purposes (to quickly see what's // a lightmap and what's not; esp. useful when LMs are rather dark - // would be hardly visible if at all on black) // And to have it not that boring, add a neat backdrop. static const uint16 debugBG[16] = {0x0000, 0x3222, 0x4a36, 0x422a, 0x3222, 0x0a22, 0x4a22, 0x33a2, 0x0000, 0x2232, 0x364a, 0x2a42, 0x2232, 0x220a, 0x224a, 0xa233}; csRGBcolor* p = data; int y, x; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { const int bitNum = 6; int b = (~x) & 0xf; int px = (debugBG[y & 0xf] & (1 << b)); if (b < bitNum) { px <<= bitNum - b; } else { px >>= b - bitNum; } p->blue = ~(1 << bitNum) + px; p++; } } #endif glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB8, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data); delete[] data; } } void csGLSuperLightmap::DeleteTexture () { if (texHandle != (GLuint)~0) { csGLTextureManager::UnsetTexture (GL_TEXTURE_2D, texHandle); glDeleteTextures (1, &texHandle); texHandle = (GLuint)~0; th = 0; } } void csGLSuperLightmap::FreeRLM (csGLRendererLightmap* rlm) { if (--numRLMs == 0) { DeleteTexture (); } // IncRef() ourselves manually. // Otherwise freeing the RLM could trigger our own destruction - // causing an assertion in block allocator (due to how BA frees items and // the safety assertions on BA destruction.) csRefTrackerAccess::TrackIncRef (this, scfRefCount); scfRefCount++; GetRLMAlloc ()->Free (rlm); DecRef (); } csPtr<iRendererLightmap> csGLSuperLightmap::RegisterLightmap (int left, int top, int width, int height) { csGLRendererLightmap* rlm = GetRLMAlloc ()->Alloc (); rlm->slm = this; rlm->rect.Set (left, top, left + width, top + height); numRLMs++; return csPtr<iRendererLightmap> (rlm); } csPtr<iImage> csGLSuperLightmap::Dump () { // @@@ hmm... or just return an empty image? if (texHandle == (GLuint)~0) return 0; GLint tw, th; csGLGraphics3D::statecache->SetTexture (GL_TEXTURE_2D, texHandle); glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &tw); glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &th); uint8* data = new uint8[tw * th * 4]; glGetTexImage (GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); csImageMemory* lmimg = new csImageMemory (tw, th, data, true, CS_IMGFMT_TRUECOLOR | CS_IMGFMT_ALPHA); return csPtr<iImage> (lmimg); } iTextureHandle* csGLSuperLightmap::GetTexture () { if (th == 0) { CreateTexture (); th.AttachNew (new csGLBasicTextureHandle ( txtmgr->G3D, iTextureHandle::texType2D, texHandle)); } return th; } } CS_PLUGIN_NAMESPACE_END(gl3d) <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "planner/abstract_plan.h" #include "common/logger.h" #include <memory> namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { std::shared_ptr<planner::AbstractPlan> plan_tree; if (parse_tree.get() == nullptr) return plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch(parse_item_node_type){ case PARSE_NODE_TYPE_DROP: child_plan = std::make_unique(new planner::DropPlan("department-table")); break; case PARSE_NODE_TYPE_SCAN: child_plan = std::make_unique(new planner::SeqScanPlan()); break; default: LOG_INFO("Unsupported Parse Node Type"); } // Need to recurse and give base case. for every child in parse tree. if (child_plan != nullptr) { if (plan_tree != nullptr) plan_tree->AddChild(std::move(child_plan)); else plan_tree = child_plan; } return plan_tree; } } // namespace optimizer } // namespace peloton <commit_msg>remove make_unique<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "planner/abstract_plan.h" #include "common/logger.h" #include <memory> namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { std::shared_ptr<planner::AbstractPlan> plan_tree; if (parse_tree.get() == nullptr) return plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch(parse_item_node_type){ case PARSE_NODE_TYPE_DROP: child_plan = std::move(new planner::DropPlan("department-table")); break; case PARSE_NODE_TYPE_SCAN: child_plan = std::move(new planner::SeqScanPlan()); break; default: LOG_INFO("Unsupported Parse Node Type"); } // Need to recurse and give base case. for every child in parse tree. if (child_plan != nullptr) { if (plan_tree != nullptr) plan_tree->AddChild(std::move(child_plan)); else plan_tree = child_plan; } return plan_tree; } } // namespace optimizer } // namespace peloton <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "planner/abstract_plan.h" #include "planner/drop_plan.h" #include "planner/seq_scan_plan.h" #include "common/logger.h" #include <memory> namespace peloton { namespace planner { class AbstractPlan; } namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { std::shared_ptr<planner::AbstractPlan> plan_tree; // Base Case if (parse_tree.get() == nullptr) return plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan = nullptr; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch (parse_item_node_type) { case PARSE_NODE_TYPE_DROP: { std::unique_ptr<planner::AbstractPlan> child_DropPlan( new planner::DropPlan("department-table")); child_plan = std::move(child_DropPlan); } break; case PARSE_NODE_TYPE_SCAN: { std::unique_ptr<planner::AbstractPlan> child_SeqScanPlan( new planner::SeqScanPlan()); child_plan = std::move(child_SeqScanPlan); } break; default: LOG_INFO("Unsupported Parse Node Type"); } if (child_plan != nullptr) { if (plan_tree != nullptr) plan_tree->AddChild(std::move(child_plan)); else plan_tree = std::move(child_plan); } // Recurse auto children = parse_tree->GetChildren(); for (auto child : children) { auto child_parse = BuildPlanTree(child); child_plan = std::move(child_parse); } return plan_tree; } } // namespace optimizer } // namespace peloton <commit_msg>Modification<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "planner/abstract_plan.h" #include "planner/drop_plan.h" #include "planner/seq_scan_plan.h" #include "common/logger.h" #include <memory> namespace peloton { namespace planner { class AbstractPlan; } namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { std::shared_ptr<planner::AbstractPlan> plan_tree; // Base Case if (parse_tree.get() == nullptr) return plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan = nullptr; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch (parse_item_node_type) { case PARSE_NODE_TYPE_DROP: { std::unique_ptr<planner::AbstractPlan> child_DropPlan( new planner::DropPlan("department-table")); child_plan = std::move(child_DropPlan); } break; case PARSE_NODE_TYPE_SCAN: { std::unique_ptr<planner::AbstractPlan> child_SeqScanPlan( new planner::SeqScanPlan()); child_plan = std::move(child_SeqScanPlan); } break; default: LOG_INFO("Unsupported Parse Node Type"); } if (child_plan != nullptr) { if (plan_tree != nullptr) plan_tree->AddChild(std::move(child_plan)); else plan_tree = std::move(child_plan); } // Recurse auto &children = parse_tree->GetChildren(); for (auto &child : children) { std::shared_ptr<planner::AbstractPlan> child_parse = BuildPlanTree(child); child_plan = std::move(child_parse); } return plan_tree; } } // namespace optimizer } // namespace peloton <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/ApplicationUsage> #include <osg/Timer> #include <osg/Notify> #include <osgUtil/DisplayRequirementsVisitor> #include <osgDB/FileUtils> #include <osgProducer/OsgCameraGroup> using namespace Producer; using namespace osgProducer; class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback { public: RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler): _cameraGroup(cameraGroup), _sceneHandler(sceneHandler) {} virtual void operator()( const Producer::RenderSurface & rs) { osg::Timer timer; osg::Timer_t start_t = timer.tick(); if (_cameraGroup->getRealizeCallback()) { (*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs); } else if (_sceneHandler) _sceneHandler->init(); osg::Timer_t end_t = timer.tick(); double time = timer.delta_m(start_t,end_t); osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl; } OsgCameraGroup* _cameraGroup; OsgSceneHandler* _sceneHandler; }; std::string findCameraConfigFile(const std::string& configFile) { std::string foundFile = osgDB::findDataFile(configFile); if (foundFile.empty()) return ""; else return foundFile; } std::string extractCameraConfigFile(osg::ArgumentParser& arguments) { // report the usage options. if (arguments.getApplicationUsage()) { arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file"); } std::string filename; if (arguments.read("-c",filename)) return findCameraConfigFile(filename); char *ptr; if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) ) { osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl; return findCameraConfigFile(ptr); } return ""; } static osg::ApplicationUsageProxy OsgCameraGroup_e1(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"PRODUCER_CAMERA_CONFIG_FILE <filename>","specify the default producer camera config to use when opening osgProducer based applications."); OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup() { _init(); } OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg): Producer::CameraGroup(cfg) { _init(); } OsgCameraGroup::OsgCameraGroup(const std::string& configFile): Producer::CameraGroup(findCameraConfigFile(configFile)) { _init(); } OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments): Producer::CameraGroup(extractCameraConfigFile(arguments)) { _init(); _applicationUsage = arguments.getApplicationUsage(); for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); Producer::RenderSurface *rs = cam->getRenderSurface(); if (rs->getWindowName()==" *** RenderSurface *** ") { rs->setWindowName(arguments.getApplicationName()); } } } void OsgCameraGroup::_init() { _thread_model = ThreadPerCamera; _scene_data = NULL; _global_stateset = NULL; _background_color.set( 0.2f, 0.2f, 0.4f, 1.0f ); _LODScale = 1.0f; _fusionDistanceMode = osgUtil::SceneView::PROPORTIONAL_TO_SCREEN_DISTANCE; _fusionDistanceValue = 1.0f; _initialized = false; // set up the time and frame counter. _frameNumber = 0; _start_tick = _timer.tick(); if (!_frameStamp) _frameStamp = new osg::FrameStamp; // set up the maximum number of graphics contexts, before loading the scene graph // to ensure that texture objects and display buffers are configured to the correct size. osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() ); _applicationUsage = osg::ApplicationUsage::instance(); } void OsgCameraGroup::setSceneData( osg::Node *scene ) { if (_scene_data==scene) return; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->removeChild(_scene_data.get()); } _scene_data = scene; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->addChild(scene); } setUpSceneViewsWithData(); } void OsgCameraGroup::setSceneDecorator( osg::Group* decorator) { if (_scene_decorator==decorator) return; _scene_decorator = decorator; if (_scene_data.valid() && decorator) { decorator->addChild(_scene_data.get()); } setUpSceneViewsWithData(); } void OsgCameraGroup::setUpSceneViewsWithData() { for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ ) { if (_scene_decorator.valid()) { (*p)->setSceneData( _scene_decorator.get() ); } else if (_scene_data.valid()) { (*p)->setSceneData( _scene_data.get() ); } else { (*p)->setSceneData( 0 ); } (*p)->setFrameStamp( _frameStamp.get() ); (*p)->setGlobalStateSet( _global_stateset.get() ); (*p)->setBackgroundColor( _background_color ); (*p)->setLODScale( _LODScale ); (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue ); (*p)->getState()->reset(); } } void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs ) { _frameStamp = fs; setUpSceneViewsWithData(); } void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset ) { _global_stateset = sset; setUpSceneViewsWithData(); } void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor ) { _background_color = backgroundColor; setUpSceneViewsWithData(); } void OsgCameraGroup::setLODScale( float scale ) { // need to set a local variable? _LODScale = scale; setUpSceneViewsWithData(); } void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value) { // need to set a local variable? _fusionDistanceMode = mode; _fusionDistanceValue = value; setUpSceneViewsWithData(); } void OsgCameraGroup::advance() { if( !_initialized ) return; CameraGroup::advance(); } bool OsgCameraGroup::realize( ThreadingModel thread_model ) { if( _realized ) return _realized; _thread_model = thread_model; return realize(); } // small visitor to check for the existance of particle systems, // which currently arn't thread safe, so we would need to disable // multithreading of cull and draw. class SearchForParticleNodes : public osg::NodeVisitor { public: SearchForParticleNodes(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _foundParticles(false) { } virtual void apply(osg::Node& node) { if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true; if (!_foundParticles) traverse(node); } bool _foundParticles; }; bool OsgCameraGroup::realize() { if( _initialized ) return _realized; if (!_ds) _ds = osg::DisplaySettings::instance(); _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() ); _shvec.clear(); osg::Node* node = getTopMostSceneData(); if (node) { // traverse the scene graphs gathering the requirements of the OpenGL buffers. osgUtil::DisplayRequirementsVisitor drv; drv.setDisplaySettings(_ds.get()); node->accept(drv); } unsigned int numMultiSamples = 0; #ifdef __sgi // switch on anti-aliasing by default, just in case we have an Onyx :-) numMultiSamples = 4; #endif // set up each render stage to clear the appropriate buffers. GLbitfield clear_mask=0; if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT; if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT; if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT; for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); // create the scene handler. osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get()); sh->setDefaults(); sh->getState()->setContextID(i); _shvec.push_back( sh ); cam->setSceneHandler( sh ); // set up the clear mask. osgUtil::RenderStage *stage = sh->getRenderStage(); if (stage) stage->setClearMask(clear_mask); // set the realize callback. Producer::RenderSurface* rs = cam->getRenderSurface(); rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh)); // set up the visual chooser. if (_ds.valid() || numMultiSamples!=0) { Producer::VisualChooser* rs_vc = rs->getVisualChooser(); if (!rs_vc) { rs_vc = new Producer::VisualChooser; rs_vc->setSimpleConfiguration(); rs->setVisualChooser(rs_vc); } if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo(); if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits()); if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits()); rs_vc->setDepthSize(24); if (numMultiSamples) { #if defined( GLX_SAMPLES_SGIS ) rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples); #endif #if defined( GLX_SAMPLES_BUFFER_SGIS ) rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1); #endif } } } if( _global_stateset == NULL && _shvec.size() > 0 ) { SceneHandlerList::iterator p = _shvec.begin(); _global_stateset = (*p)->getGlobalStateSet(); } setUpSceneViewsWithData(); if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded) { SearchForParticleNodes sfpn; getTopMostSceneData()->accept(sfpn); if (sfpn._foundParticles) { osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl; osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl; _thread_model = Producer::CameraGroup::SingleThreaded; } else { std::set<RenderSurface*> renderSurfaceSet; for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); renderSurfaceSet.insert(cam->getRenderSurface()); } if (renderSurfaceSet.size()!=_cfg->getNumberOfCameras()) { // camera's must be sharing a RenderSurface, so we need to ensure that we're // running single threaded, to avoid OpenGL threading issues. osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw to avoid"<<std::endl; osg::notify(osg::INFO)<<" threading problems when camera's share a RenderSurface."<<std::endl; _thread_model = Producer::CameraGroup::SingleThreaded; } } } _initialized = CameraGroup::realize(); return _initialized; } osg::Node* OsgCameraGroup::getTopMostSceneData() { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } const osg::Node* OsgCameraGroup::getTopMostSceneData() const { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } void OsgCameraGroup::setView(const osg::Matrix& matrix) { Producer::Matrix pm(matrix.ptr()); setViewByMatrix(pm); } const osg::Matrix OsgCameraGroup::getViewMatrix() const { osg::Matrix matrix; if (_cfg && _cfg->getNumberOfCameras()>=1) { Producer::Camera *cam = _cfg->getCamera(0); matrix.set(cam->getViewMatrix()); } return matrix; } void OsgCameraGroup::sync() { CameraGroup::sync(); // set the frame stamp for the new frame. double time_since_start = _timer.delta_s(_start_tick,_timer.tick()); _frameStamp->setFrameNumber(_frameNumber++); _frameStamp->setReferenceTime(time_since_start); } void OsgCameraGroup::frame() { osg::Node* node = getTopMostSceneData(); if (node) node->getBound(); CameraGroup::frame(); } <commit_msg>Removed the _state.reset() call as it was doing OpenGL calls outside of the thread with the graphics context.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/ApplicationUsage> #include <osg/Timer> #include <osg/Notify> #include <osgUtil/DisplayRequirementsVisitor> #include <osgDB/FileUtils> #include <osgProducer/OsgCameraGroup> using namespace Producer; using namespace osgProducer; class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback { public: RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler): _cameraGroup(cameraGroup), _sceneHandler(sceneHandler) {} virtual void operator()( const Producer::RenderSurface & rs) { osg::Timer timer; osg::Timer_t start_t = timer.tick(); if (_cameraGroup->getRealizeCallback()) { (*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs); } else if (_sceneHandler) _sceneHandler->init(); osg::Timer_t end_t = timer.tick(); double time = timer.delta_m(start_t,end_t); osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl; } OsgCameraGroup* _cameraGroup; OsgSceneHandler* _sceneHandler; }; std::string findCameraConfigFile(const std::string& configFile) { std::string foundFile = osgDB::findDataFile(configFile); if (foundFile.empty()) return ""; else return foundFile; } std::string extractCameraConfigFile(osg::ArgumentParser& arguments) { // report the usage options. if (arguments.getApplicationUsage()) { arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file"); } std::string filename; if (arguments.read("-c",filename)) return findCameraConfigFile(filename); char *ptr; if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) ) { osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl; return findCameraConfigFile(ptr); } return ""; } static osg::ApplicationUsageProxy OsgCameraGroup_e1(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"PRODUCER_CAMERA_CONFIG_FILE <filename>","specify the default producer camera config to use when opening osgProducer based applications."); OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup() { _init(); } OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg): Producer::CameraGroup(cfg) { _init(); } OsgCameraGroup::OsgCameraGroup(const std::string& configFile): Producer::CameraGroup(findCameraConfigFile(configFile)) { _init(); } OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments): Producer::CameraGroup(extractCameraConfigFile(arguments)) { _init(); _applicationUsage = arguments.getApplicationUsage(); for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); Producer::RenderSurface *rs = cam->getRenderSurface(); if (rs->getWindowName()==" *** RenderSurface *** ") { rs->setWindowName(arguments.getApplicationName()); } } } void OsgCameraGroup::_init() { _thread_model = ThreadPerCamera; _scene_data = NULL; _global_stateset = NULL; _background_color.set( 0.2f, 0.2f, 0.4f, 1.0f ); _LODScale = 1.0f; _fusionDistanceMode = osgUtil::SceneView::PROPORTIONAL_TO_SCREEN_DISTANCE; _fusionDistanceValue = 1.0f; _initialized = false; // set up the time and frame counter. _frameNumber = 0; _start_tick = _timer.tick(); if (!_frameStamp) _frameStamp = new osg::FrameStamp; // set up the maximum number of graphics contexts, before loading the scene graph // to ensure that texture objects and display buffers are configured to the correct size. osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() ); _applicationUsage = osg::ApplicationUsage::instance(); } void OsgCameraGroup::setSceneData( osg::Node *scene ) { if (_scene_data==scene) return; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->removeChild(_scene_data.get()); } _scene_data = scene; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->addChild(scene); } setUpSceneViewsWithData(); } void OsgCameraGroup::setSceneDecorator( osg::Group* decorator) { if (_scene_decorator==decorator) return; _scene_decorator = decorator; if (_scene_data.valid() && decorator) { decorator->addChild(_scene_data.get()); } setUpSceneViewsWithData(); } void OsgCameraGroup::setUpSceneViewsWithData() { for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ ) { if (_scene_decorator.valid()) { (*p)->setSceneData( _scene_decorator.get() ); } else if (_scene_data.valid()) { (*p)->setSceneData( _scene_data.get() ); } else { (*p)->setSceneData( 0 ); } (*p)->setFrameStamp( _frameStamp.get() ); (*p)->setGlobalStateSet( _global_stateset.get() ); (*p)->setBackgroundColor( _background_color ); (*p)->setLODScale( _LODScale ); (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue ); } } void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs ) { _frameStamp = fs; setUpSceneViewsWithData(); } void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset ) { _global_stateset = sset; setUpSceneViewsWithData(); } void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor ) { _background_color = backgroundColor; setUpSceneViewsWithData(); } void OsgCameraGroup::setLODScale( float scale ) { // need to set a local variable? _LODScale = scale; setUpSceneViewsWithData(); } void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value) { // need to set a local variable? _fusionDistanceMode = mode; _fusionDistanceValue = value; setUpSceneViewsWithData(); } void OsgCameraGroup::advance() { if( !_initialized ) return; CameraGroup::advance(); } bool OsgCameraGroup::realize( ThreadingModel thread_model ) { if( _realized ) return _realized; _thread_model = thread_model; return realize(); } // small visitor to check for the existance of particle systems, // which currently arn't thread safe, so we would need to disable // multithreading of cull and draw. class SearchForParticleNodes : public osg::NodeVisitor { public: SearchForParticleNodes(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _foundParticles(false) { } virtual void apply(osg::Node& node) { if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true; if (!_foundParticles) traverse(node); } bool _foundParticles; }; bool OsgCameraGroup::realize() { if( _initialized ) return _realized; if (!_ds) _ds = osg::DisplaySettings::instance(); _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() ); _shvec.clear(); osg::Node* node = getTopMostSceneData(); if (node) { // traverse the scene graphs gathering the requirements of the OpenGL buffers. osgUtil::DisplayRequirementsVisitor drv; drv.setDisplaySettings(_ds.get()); node->accept(drv); } unsigned int numMultiSamples = 0; #ifdef __sgi // switch on anti-aliasing by default, just in case we have an Onyx :-) numMultiSamples = 4; #endif // set up each render stage to clear the appropriate buffers. GLbitfield clear_mask=0; if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT; if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT; if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT; for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); // create the scene handler. osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get()); sh->setDefaults(); sh->getState()->setContextID(i); _shvec.push_back( sh ); cam->setSceneHandler( sh ); // set up the clear mask. osgUtil::RenderStage *stage = sh->getRenderStage(); if (stage) stage->setClearMask(clear_mask); // set the realize callback. Producer::RenderSurface* rs = cam->getRenderSurface(); rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh)); // set up the visual chooser. if (_ds.valid() || numMultiSamples!=0) { Producer::VisualChooser* rs_vc = rs->getVisualChooser(); if (!rs_vc) { rs_vc = new Producer::VisualChooser; rs_vc->setSimpleConfiguration(); rs->setVisualChooser(rs_vc); } if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo(); if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits()); if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits()); rs_vc->setDepthSize(24); if (numMultiSamples) { #if defined( GLX_SAMPLES_SGIS ) rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples); #endif #if defined( GLX_SAMPLES_BUFFER_SGIS ) rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1); #endif } } } if( _global_stateset == NULL && _shvec.size() > 0 ) { SceneHandlerList::iterator p = _shvec.begin(); _global_stateset = (*p)->getGlobalStateSet(); } setUpSceneViewsWithData(); if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded) { SearchForParticleNodes sfpn; getTopMostSceneData()->accept(sfpn); if (sfpn._foundParticles) { osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl; osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl; _thread_model = Producer::CameraGroup::SingleThreaded; } else { std::set<RenderSurface*> renderSurfaceSet; for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); renderSurfaceSet.insert(cam->getRenderSurface()); } if (renderSurfaceSet.size()!=_cfg->getNumberOfCameras()) { // camera's must be sharing a RenderSurface, so we need to ensure that we're // running single threaded, to avoid OpenGL threading issues. osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw to avoid"<<std::endl; osg::notify(osg::INFO)<<" threading problems when camera's share a RenderSurface."<<std::endl; _thread_model = Producer::CameraGroup::SingleThreaded; } } } _initialized = CameraGroup::realize(); return _initialized; } osg::Node* OsgCameraGroup::getTopMostSceneData() { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } const osg::Node* OsgCameraGroup::getTopMostSceneData() const { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } void OsgCameraGroup::setView(const osg::Matrix& matrix) { Producer::Matrix pm(matrix.ptr()); setViewByMatrix(pm); } const osg::Matrix OsgCameraGroup::getViewMatrix() const { osg::Matrix matrix; if (_cfg && _cfg->getNumberOfCameras()>=1) { Producer::Camera *cam = _cfg->getCamera(0); matrix.set(cam->getViewMatrix()); } return matrix; } void OsgCameraGroup::sync() { CameraGroup::sync(); // set the frame stamp for the new frame. double time_since_start = _timer.delta_s(_start_tick,_timer.tick()); _frameStamp->setFrameNumber(_frameNumber++); _frameStamp->setReferenceTime(time_since_start); } void OsgCameraGroup::frame() { osg::Node* node = getTopMostSceneData(); if (node) node->getBound(); CameraGroup::frame(); } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "LibMTDevEventSource.h" #include "LinuxMTHelper.h" #include "TouchEvent.h" #include "Player.h" #include "AVGNode.h" #include "TouchStatus.h" #include "../base/Logger.h" #include "../base/Point.h" #include "../base/ObjectCounter.h" #include "../base/Exception.h" #include <linux/input.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <set> extern "C" { #include <mtdev.h> #include <mtdev-mapping.h> } using namespace std; namespace avg { LibMTDevEventSource::LibMTDevEventSource() : m_LastID(0), m_pMTDevice(0) { } LibMTDevEventSource::~LibMTDevEventSource() { if (m_pMTDevice) { mtdev_close(m_pMTDevice); delete m_pMTDevice; } } void LibMTDevEventSource::start() { string sDevice = "/dev/input/event3"; m_DeviceFD = ::open(sDevice.c_str(), O_RDONLY | O_NONBLOCK); if (m_DeviceFD == -1) { throw Exception(AVG_ERR_MT_INIT, string("Linux multitouch event source: Could not open device file '")+ sDevice+"'. "+strerror(errno)+"."); } m_pMTDevice = new mtdev; int err = mtdev_open(m_pMTDevice, m_DeviceFD); if (err == -1) { throw Exception(AVG_ERR_MT_INIT, string("Linux multitouch event source: Could not open mtdev '")+ sDevice+"'. "+strerror(errno)+"."); } input_absinfo* pAbsInfo; pAbsInfo = &(m_pMTDevice->caps.abs[MTDEV_POSITION_X]); m_Dimensions.tl.x = pAbsInfo->minimum; m_Dimensions.br.x = pAbsInfo->maximum; pAbsInfo = &(m_pMTDevice->caps.abs[MTDEV_POSITION_Y]); m_Dimensions.tl.y = pAbsInfo->minimum; m_Dimensions.br.y = pAbsInfo->maximum; MultitouchEventSource::start(); AVG_TRACE(Logger::CONFIG, "Linux MTDev Multitouch event source created."); } std::vector<EventPtr> LibMTDevEventSource::pollEvents() { struct input_event events[64]; int numEvents = mtdev_get(m_pMTDevice, m_DeviceFD, events, 64); if (numEvents < 0) { cerr << "numEvents: " << numEvents << endl; } /* if (numEvents > 0) { cerr << "---- read ----" << endl; } */ static int curSlot = 0; set<int> changedIDs; for (int i = 0; i < numEvents; ++i) { input_event event = events[i]; if (event.type == EV_ABS && event.code == ABS_MT_SLOT) { cerr << ">> slot " << event.value << endl; curSlot = event.value; } else { TouchData* pTouch; switch (event.code) { case ABS_MT_TRACKING_ID: // cerr << ">> ABS_MT_TRACKING_ID: " << event.value << endl; pTouch = &(m_Slots[curSlot]); if (event.value == -1) { TouchStatusPtr pTouchStatus = getTouchStatus(pTouch->id); // cerr << "up " << pTouch->id << endl; if (pTouchStatus) { // cerr << " --> remove" << endl; TouchEventPtr pOldEvent = pTouchStatus->getLastEvent(); TouchEventPtr pUpEvent = boost::dynamic_pointer_cast<TouchEvent>( pOldEvent->cloneAs(Event::CURSORUP)); pTouchStatus->updateEvent(pUpEvent); } pTouch->id = -1; } else { pTouch->id = event.value; } break; case ABS_MT_POSITION_X: // cerr << ">> ABS_MT_POSITION_X: " << event.value << endl; pTouch = &(m_Slots[curSlot]); pTouch->pos.x = event.value; break; case ABS_MT_POSITION_Y: // cerr << ">> ABS_MT_POSITION_Y: " << event.value << endl; pTouch = &(m_Slots[curSlot]); pTouch->pos.y = event.value; break; default: break; } // cerr << ">> new id: " << curSlot << endl; changedIDs.insert(curSlot); } } for (set<int>::iterator it = changedIDs.begin(); it != changedIDs.end(); ++it) { map<int, TouchData>::iterator it2 = m_Slots.find(*it); if (it2 != m_Slots.end()) { const TouchData& touch = it2->second; // cerr << "slot: " << *it << ", id: " << touch.id << ", pos: " << touch.pos // << endl; // AVG_ASSERT(touch.pos.x != 0); if (touch.id != -1) { TouchStatusPtr pTouchStatus = getTouchStatus(touch.id); if (!pTouchStatus) { // cerr << "down" << endl; // Down m_LastID++; TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSORDOWN, touch.pos); addTouchStatus((long)touch.id, pEvent); } else { // cerr << "move" << endl; // Move TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION, touch.pos); pTouchStatus->updateEvent(pEvent); } } } } /* static int numContacts = 0; static int tmpID; static IntPoint tmpPos; struct input_event event[64]; char * pReadPos = (char*)(void*)&event; ssize_t numBytes = 0; ssize_t newBytes = -1; while (newBytes != 0) { newBytes = read(m_DeviceFD, pReadPos+numBytes, sizeof(input_event)); if (newBytes == -1) { newBytes = 0; } numBytes += newBytes; } AVG_ASSERT(numBytes%sizeof(input_event) == 0); if (numBytes > 0) { cerr << "---- read ----" << endl; } for (unsigned i = 0; i < numBytes/sizeof(input_event); ++i) { switch (event[i].type) { case EV_ABS: cerr << "EV_ABS " << mtCodeToString(event[i].code) << endl; switch (event[i].code) { case ABS_MT_TRACKING_ID: numContacts++; tmpID = event[i].value; break; case ABS_MT_POSITION_X: tmpPos.x = event[i].value; break; case ABS_MT_POSITION_Y: tmpPos.y = event[i].value; break; default: break; } break; case EV_SYN: cerr << "EV_SYN " << synCodeToString(event[i].code) << endl; switch (event[i].code) { case SYN_MT_REPORT: { cerr << "id: " << tmpID << ", pos: " << tmpPos << endl; TouchStatusPtr pTouchStatus = getTouchStatus(tmpID); if (!pTouchStatus) { // Down m_LastID++; TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSORDOWN, tmpPos); addTouchStatus((long)tmpID, pEvent); } else { // Move TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION, tmpPos); pTouchStatus->updateEvent(pEvent); } } break; case SYN_REPORT: cerr << "SYN_REPORT" << endl; break; default: break; } break; default: // cerr << "Unexpected type " << eventTypeToString(event[i].type) << endl; break; } } */ return MultitouchEventSource::pollEvents(); } TouchEventPtr LibMTDevEventSource::createEvent(int id, Event::Type type, IntPoint pos) { DPoint size = getWindowSize(); DPoint normPos = DPoint(double(pos.x-m_Dimensions.tl.x)/m_Dimensions.width(), double(pos.y-m_Dimensions.tl.y)/m_Dimensions.height()); IntPoint screenPos(int(normPos.x*size.x+0.5), int(normPos.y*size.y+0.5)); return TouchEventPtr(new TouchEvent(id, type, screenPos, Event::TOUCH, DPoint(0,0), 0, 20, 1, DPoint(5,0), DPoint(0,5))); } } <commit_msg>Added AVG_LINUX_MULTITOUCH_DEVICE environment variable.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "LibMTDevEventSource.h" #include "LinuxMTHelper.h" #include "TouchEvent.h" #include "Player.h" #include "AVGNode.h" #include "TouchStatus.h" #include "../base/Logger.h" #include "../base/Point.h" #include "../base/ObjectCounter.h" #include "../base/Exception.h" #include "../base/OSHelper.h" #include <linux/input.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <set> extern "C" { #include <mtdev.h> #include <mtdev-mapping.h> } using namespace std; namespace avg { LibMTDevEventSource::LibMTDevEventSource() : m_LastID(0), m_pMTDevice(0) { } LibMTDevEventSource::~LibMTDevEventSource() { if (m_pMTDevice) { mtdev_close(m_pMTDevice); delete m_pMTDevice; } } void LibMTDevEventSource::start() { string sDevice("/dev/input/event3"); getEnv("AVG_LINUX_MULTITOUCH_DEVICE", sDevice); m_DeviceFD = ::open(sDevice.c_str(), O_RDONLY | O_NONBLOCK); if (m_DeviceFD == -1) { throw Exception(AVG_ERR_MT_INIT, string("Linux multitouch event source: Could not open device file '")+ sDevice+"'. "+strerror(errno)+"."); } m_pMTDevice = new mtdev; int err = mtdev_open(m_pMTDevice, m_DeviceFD); if (err == -1) { throw Exception(AVG_ERR_MT_INIT, string("Linux multitouch event source: Could not open mtdev '")+ sDevice+"'. "+strerror(errno)+"."); } input_absinfo* pAbsInfo; pAbsInfo = &(m_pMTDevice->caps.abs[MTDEV_POSITION_X]); m_Dimensions.tl.x = pAbsInfo->minimum; m_Dimensions.br.x = pAbsInfo->maximum; pAbsInfo = &(m_pMTDevice->caps.abs[MTDEV_POSITION_Y]); m_Dimensions.tl.y = pAbsInfo->minimum; m_Dimensions.br.y = pAbsInfo->maximum; MultitouchEventSource::start(); AVG_TRACE(Logger::CONFIG, "Linux MTDev Multitouch event source created."); } std::vector<EventPtr> LibMTDevEventSource::pollEvents() { struct input_event events[64]; int numEvents = mtdev_get(m_pMTDevice, m_DeviceFD, events, 64); if (numEvents < 0) { cerr << "numEvents: " << numEvents << endl; } /* if (numEvents > 0) { cerr << "---- read ----" << endl; } */ static int curSlot = 0; set<int> changedIDs; for (int i = 0; i < numEvents; ++i) { input_event event = events[i]; if (event.type == EV_ABS && event.code == ABS_MT_SLOT) { cerr << ">> slot " << event.value << endl; curSlot = event.value; } else { TouchData* pTouch; switch (event.code) { case ABS_MT_TRACKING_ID: // cerr << ">> ABS_MT_TRACKING_ID: " << event.value << endl; pTouch = &(m_Slots[curSlot]); if (event.value == -1) { TouchStatusPtr pTouchStatus = getTouchStatus(pTouch->id); // cerr << "up " << pTouch->id << endl; if (pTouchStatus) { // cerr << " --> remove" << endl; TouchEventPtr pOldEvent = pTouchStatus->getLastEvent(); TouchEventPtr pUpEvent = boost::dynamic_pointer_cast<TouchEvent>( pOldEvent->cloneAs(Event::CURSORUP)); pTouchStatus->updateEvent(pUpEvent); } pTouch->id = -1; } else { pTouch->id = event.value; } break; case ABS_MT_POSITION_X: // cerr << ">> ABS_MT_POSITION_X: " << event.value << endl; pTouch = &(m_Slots[curSlot]); pTouch->pos.x = event.value; break; case ABS_MT_POSITION_Y: // cerr << ">> ABS_MT_POSITION_Y: " << event.value << endl; pTouch = &(m_Slots[curSlot]); pTouch->pos.y = event.value; break; default: break; } // cerr << ">> new id: " << curSlot << endl; changedIDs.insert(curSlot); } } for (set<int>::iterator it = changedIDs.begin(); it != changedIDs.end(); ++it) { map<int, TouchData>::iterator it2 = m_Slots.find(*it); if (it2 != m_Slots.end()) { const TouchData& touch = it2->second; // cerr << "slot: " << *it << ", id: " << touch.id << ", pos: " << touch.pos // << endl; // AVG_ASSERT(touch.pos.x != 0); if (touch.id != -1) { TouchStatusPtr pTouchStatus = getTouchStatus(touch.id); if (!pTouchStatus) { // cerr << "down" << endl; // Down m_LastID++; TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSORDOWN, touch.pos); addTouchStatus((long)touch.id, pEvent); } else { // cerr << "move" << endl; // Move TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION, touch.pos); pTouchStatus->updateEvent(pEvent); } } } } /* static int numContacts = 0; static int tmpID; static IntPoint tmpPos; struct input_event event[64]; char * pReadPos = (char*)(void*)&event; ssize_t numBytes = 0; ssize_t newBytes = -1; while (newBytes != 0) { newBytes = read(m_DeviceFD, pReadPos+numBytes, sizeof(input_event)); if (newBytes == -1) { newBytes = 0; } numBytes += newBytes; } AVG_ASSERT(numBytes%sizeof(input_event) == 0); if (numBytes > 0) { cerr << "---- read ----" << endl; } for (unsigned i = 0; i < numBytes/sizeof(input_event); ++i) { switch (event[i].type) { case EV_ABS: cerr << "EV_ABS " << mtCodeToString(event[i].code) << endl; switch (event[i].code) { case ABS_MT_TRACKING_ID: numContacts++; tmpID = event[i].value; break; case ABS_MT_POSITION_X: tmpPos.x = event[i].value; break; case ABS_MT_POSITION_Y: tmpPos.y = event[i].value; break; default: break; } break; case EV_SYN: cerr << "EV_SYN " << synCodeToString(event[i].code) << endl; switch (event[i].code) { case SYN_MT_REPORT: { cerr << "id: " << tmpID << ", pos: " << tmpPos << endl; TouchStatusPtr pTouchStatus = getTouchStatus(tmpID); if (!pTouchStatus) { // Down m_LastID++; TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSORDOWN, tmpPos); addTouchStatus((long)tmpID, pEvent); } else { // Move TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION, tmpPos); pTouchStatus->updateEvent(pEvent); } } break; case SYN_REPORT: cerr << "SYN_REPORT" << endl; break; default: break; } break; default: // cerr << "Unexpected type " << eventTypeToString(event[i].type) << endl; break; } } */ return MultitouchEventSource::pollEvents(); } TouchEventPtr LibMTDevEventSource::createEvent(int id, Event::Type type, IntPoint pos) { DPoint size = getWindowSize(); DPoint normPos = DPoint(double(pos.x-m_Dimensions.tl.x)/m_Dimensions.width(), double(pos.y-m_Dimensions.tl.y)/m_Dimensions.height()); IntPoint screenPos(int(normPos.x*size.x+0.5), int(normPos.y*size.y+0.5)); return TouchEventPtr(new TouchEvent(id, type, screenPos, Event::TOUCH, DPoint(0,0), 0, 20, 1, DPoint(5,0), DPoint(0,5))); } } <|endoftext|>
<commit_before>/** * @file * * @brief Delegate implementation for the `leaf` plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include <numeric> #include <kdbassert.h> #include <kdbease.h> #include <kdblogger.h> #include "leaf_delegate.hpp" using std::accumulate; using std::ignore; using std::make_pair; using std::pair; using std::range_error; using std::string; using std::tie; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- namespace elektra { using CppKey = kdb::Key; /** * @brief This function splits the given keyset into directory leaves (marked with `DIRECTORY_POSTFIX`) and other keys. * * @param input The function searches for directory leaves in this key set. * * @return A pair of key sets, where the first key set contains all directory leaves and the second key set contains all other keys */ pair<CppKeySet, CppKeySet> splitDirectoryLeavesOther (CppKeySet const & input) { CppKeySet directoryLeaves; CppKeySet other; for (auto key : input) { if (key.getBaseName () == DIRECTORY_POSTFIX) { directoryLeaves.append (key); } else { other.append (key); } } return make_pair (directoryLeaves, other); } /** * @brief This function removes the directory postfix (`DIRECTORY_POSTFIX`) from the name of all keys in `directoryLeaves`. * * @pre All key names in `directoryLeaves` must end with `DIRECTORY_POSTFIX`. * * @param directoryLeaves This parameter contains the keys for which this function removes the directory postfix. * * @return A copy of the input, where each key name does not end with the directory postfix any more */ CppKeySet convertLeavesToDirectories (CppKeySet const & directoryLeaves) { CppKeySet directories; for (auto key : directoryLeaves) { CppKey directory = key.dup (); keySetBaseName (*directory, 0); directories.append (directory); } return directories; } /** * @brief This function returns a modified copy of `child`, where child is directly below `parent`. * * For example, if `child` has the name `user/parent/level1/level2/level3` and parent has the name `user/parent`, then the function will * return a key with the name `user/parent/level1`. * * @pre The key `child` has to be below `parent`. * * @param parent This parameter specifies a parent key of `child`. * @param keys This variable stores a child key of `parent`. * * @return A copy of `child` that is directly below `parent` */ CppKey convertToDirectChild (CppKey const & parent, CppKey const & child) { ELEKTRA_ASSERT (child.isBelow (parent), "The key `child` is not located below `parent`"); CppKey directChild = child.dup (); while (!directChild.isDirectBelow (parent)) { keySetBaseName (*directChild, 0); } return directChild; } /** * @brief This function determines if the given key is an array parent. * * @param parent This parameter specifies a possible array parent. * @param keys This variable stores the key set of `parent`. * * @retval true If `parent` is the parent key of an array * @retval false Otherwise */ bool isArrayParent (CppKey const & parent, CppKeySet const & keys) { CppKeySet children = accumulate (keys.begin (), keys.end (), CppKeySet{}, [&parent](CppKeySet collected, CppKey key) { if (key.isBelow (parent)) collected.append (key); return collected; }); for (auto child : children) { CppKey directChild = convertToDirectChild (parent, child); if (elektraArrayValidateName (*directChild) < 0) return false; } return true; } /** * @brief Split `keys` into two key sets, one for array parents and one for all other keys. * * @param keys This parameter contains the key set this function splits. * * @return A pair of key sets, where the first key set contains all array parents and the second key set contains all other keys */ pair<CppKeySet, CppKeySet> splitArrayParentsOther (CppKeySet const & keys) { CppKeySet arrayParents; CppKeySet others; keys.rewind (); CppKey previous; for (previous = keys.next (); keys.next (); previous = keys.current ()) { bool previousIsArray = previous.hasMeta ("array") || (keys.current ().isBelow (previous) && keys.current ().getBaseName ()[0] == '#' && isArrayParent (previous, keys)); (previousIsArray ? arrayParents : others).append (previous); } (previous.hasMeta ("array") ? arrayParents : others).append (previous); ELEKTRA_ASSERT (arrayParents.size () + others.size () == keys.size (), "Number of keys in split key sets: %zu ≠ number in given key set %zu", arrayParents.size () + others.size (), keys.size ()); return make_pair (arrayParents, others); } /** * @brief This function splits `keys` into two key sets, one for array parents and elements, and the other one for all other keys. * * @param arrayParents This key set contains a (copy) of all array parents of `keys`. * @param keys This parameter contains the key set this function splits. * * @return A pair of key sets, where the first key set contains all array parents and elements, * and the second key set contains all other keys */ pair<CppKeySet, CppKeySet> splitArrayOther (CppKeySet const & arrayParents, CppKeySet const & keys) { CppKeySet others = keys.dup (); CppKeySet arrays; for (auto parent : arrayParents) { arrays.append (others.cut (parent)); } return make_pair (arrays, others); } /** * @brief This function increases an array index of the given array element by one. * * @param parent This key set stores an array parent of `element`. The function will increase the index of `element` that is directly below * this key. * @param element This parameter stores an array element. * * @return A copy of `element`, where the index below `parent` was increased by one */ CppKey increaseArrayIndex (CppKey const & parent, CppKey const & element) { CppKey elementNewIndex = convertToDirectChild (parent, element); string postfix = elektraKeyGetRelativeName (*element, *elementNewIndex); if (elektraArrayIncName (*elementNewIndex)) { throw range_error ("Unable to increase index of key “" + elementNewIndex.getName () + "”"); } elementNewIndex.addName (postfix); ELEKTRA_LOG_DEBUG ("New name of “%s” is “%s”", element.getName ().c_str (), elementNewIndex.getName ().c_str ()); return elementNewIndex; } /** * @brief Increase the array index of array elements by one. * * Since it is also possible that one of the array parents is part of another array, this function also updates the indices of the given * array parents. * * @param parents This parameter contains the array parents for which this function increases the index by one. * @param parents This variable stores the arrays elements this function updates. * * @return A pair containing a copy of `parents` and `arrays`, where all indices specified by `parents` are increased by one */ pair<CppKeySet, CppKeySet> increaseArrayIndices (CppKeySet const & parents, CppKeySet const & arrays) { CppKeySet arraysIncreasedIndex = arrays.dup (); CppKeySet arrayParents = parents.dup (); CppKeySet updatedParents = parents.dup (); while (CppKey parent = arrayParents.pop ()) { ELEKTRA_LOG_DEBUG ("Increase indices for array parent “%s”", parent.getName ().c_str ()); CppKeySet newArrays; for (auto key : arraysIncreasedIndex) { if (key.isBelow (parent)) { auto updated = increaseArrayIndex (parent, key); if (updatedParents.lookup (key, KDB_O_POP)) updatedParents.append (updated); newArrays.append (updated); } else { newArrays.append (key); } } arraysIncreasedIndex = newArrays; } return make_pair (updatedParents, arraysIncreasedIndex); } /** * @brief Split `keys` into two key sets, one for directories (keys without children) and one for all other keys. * * @param keys This parameter contains the key set this function splits. * * @return A pair of key sets, where the first key set contains all directories and the second key set contains all leaves */ pair<CppKeySet, CppKeySet> splitDirectoriesLeaves (CppKeySet const & keys) { CppKeySet leaves; CppKeySet directories; keys.rewind (); CppKey previous; for (previous = keys.next (); keys.next (); previous = keys.current ()) { if (keys.current ().isBelow (previous)) { directories.append (previous); } else { leaves.append (previous); } } leaves.append (previous); return make_pair (directories, leaves); } /** * @brief Convert all keys in `parents` to an empty array parent and an array element with index `#0` storing the data of the old key. * * @param parents This parameter contains the set of array parent this function converts. * * @return A key set containing only empty array parents and corresponding array elements storing the values of the old array parent */ CppKeySet convertArrayParentsToLeaves (CppKeySet const & parents) { CppKeySet converted; for (auto parent : parents) { CppKey directory{ parent.getName (), KS_END }; CppKey leaf = parent.dup (); leaf.addBaseName ("#0"); converted.append (directory); converted.append (leaf); } return converted; } /** * @brief Convert all keys in `directories` to an empty key and a leaf key containing the data of the old key. * * @param directories This parameter contains a set of directory keys this function converts. * * @return A key set containing only empty directory keys and corresponding leaf keys storing the values of the old directory keys */ CppKeySet convertDirectoriesToLeaves (CppKeySet const & directories) { CppKeySet directoryLeaves; for (auto directory : directories) { CppKey emptyDirectory{ directory.getName (), KS_END }; CppKey leaf = directory.dup (); leaf.addBaseName (DIRECTORY_POSTFIX); directoryLeaves.append (leaf); directoryLeaves.append (emptyDirectory); } return directoryLeaves; } // -- Class -------------------------------------------------------------------------------------------------------------------------------- /** * @brief This constructor creates a new delegate object used by the `leaf` plugin * * @param config This key set contains configuration values provided by the `leaf` plugin */ LeafDelegate::LeafDelegate (CppKeySet config ELEKTRA_UNUSED) { } /** * @brief This method converts all leaf keys in the given key set to directory keys. * * @param keys This parameter specifies the key set this function converts. * * @retval ELEKTRA_PLUGIN_STATUS_SUCCESS If the plugin converted any value in the given key set * @retval ELEKTRA_PLUGIN_STATUS_NO_UPDATE If the plugin did not update `keys` */ int LeafDelegate::convertToDirectories (CppKeySet & keys) { CppKeySet directoryLeaves; CppKeySet nonDirectoryLeaves; tie (directoryLeaves, nonDirectoryLeaves) = splitDirectoryLeavesOther (keys); bool status = directoryLeaves.size () > 0 ? ELEKTRA_PLUGIN_STATUS_SUCCESS : ELEKTRA_PLUGIN_STATUS_NO_UPDATE; auto directories = convertLeavesToDirectories (directoryLeaves); keys.clear (); keys.append (nonDirectoryLeaves); keys.append (directories); return status; } /** * @brief This method converts all directory keys in the given key set to leaf keys. * * @param keys This parameter specifies the key set this function converts. * * @retval ELEKTRA_PLUGIN_STATUS_SUCCESS If the plugin converted any value in the given key set * @retval ELEKTRA_PLUGIN_STATUS_NO_UPDATE If the plugin did not update `keys` */ int LeafDelegate::convertToLeaves (CppKeySet & keys) { CppKeySet notArrayParents; CppKeySet arrayParents; CppKeySet arrays; CppKeySet nonArrays; CppKeySet directories; CppKeySet leaves; tie (arrayParents, ignore) = splitArrayParentsOther (keys); tie (arrays, nonArrays) = splitArrayOther (arrayParents, keys); tie (arrayParents, arrays) = increaseArrayIndices (arrayParents, arrays); notArrayParents.append (arrays); notArrayParents.append (nonArrays); notArrayParents = accumulate (notArrayParents.begin (), notArrayParents.end (), CppKeySet{}, [&arrayParents](CppKeySet collected, CppKey key) { if (!arrayParents.lookup (key)) collected.append (key); return collected; }); arrayParents = convertArrayParentsToLeaves (arrayParents); tie (directories, leaves) = splitDirectoriesLeaves (notArrayParents); bool status = directories.size () > 0 || arrayParents.size () > 0 ? ELEKTRA_PLUGIN_STATUS_SUCCESS : ELEKTRA_PLUGIN_STATUS_NO_UPDATE; auto directoryLeaves = convertDirectoriesToLeaves (directories); keys.clear (); keys.append (arrays); keys.append (arrayParents); keys.append (directoryLeaves); keys.append (leaves); return status; } } // end namespace elektra <commit_msg>Leaf: Describe array conversion algorithm<commit_after>/** * @file * * @brief Delegate implementation for the `leaf` plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include <numeric> #include <kdbassert.h> #include <kdbease.h> #include <kdblogger.h> #include "leaf_delegate.hpp" using std::accumulate; using std::ignore; using std::make_pair; using std::pair; using std::range_error; using std::string; using std::tie; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- namespace elektra { using CppKey = kdb::Key; /** * @brief This function splits the given keyset into directory leaves (marked with `DIRECTORY_POSTFIX`) and other keys. * * @param input The function searches for directory leaves in this key set. * * @return A pair of key sets, where the first key set contains all directory leaves and the second key set contains all other keys */ pair<CppKeySet, CppKeySet> splitDirectoryLeavesOther (CppKeySet const & input) { CppKeySet directoryLeaves; CppKeySet other; for (auto key : input) { if (key.getBaseName () == DIRECTORY_POSTFIX) { directoryLeaves.append (key); } else { other.append (key); } } return make_pair (directoryLeaves, other); } /** * @brief This function removes the directory postfix (`DIRECTORY_POSTFIX`) from the name of all keys in `directoryLeaves`. * * @pre All key names in `directoryLeaves` must end with `DIRECTORY_POSTFIX`. * * @param directoryLeaves This parameter contains the keys for which this function removes the directory postfix. * * @return A copy of the input, where each key name does not end with the directory postfix any more */ CppKeySet convertLeavesToDirectories (CppKeySet const & directoryLeaves) { CppKeySet directories; for (auto key : directoryLeaves) { CppKey directory = key.dup (); keySetBaseName (*directory, 0); directories.append (directory); } return directories; } /** * @brief This function returns a modified copy of `child`, where child is directly below `parent`. * * For example, if `child` has the name `user/parent/level1/level2/level3` and parent has the name `user/parent`, then the function will * return a key with the name `user/parent/level1`. * * @pre The key `child` has to be below `parent`. * * @param parent This parameter specifies a parent key of `child`. * @param keys This variable stores a child key of `parent`. * * @return A copy of `child` that is directly below `parent` */ CppKey convertToDirectChild (CppKey const & parent, CppKey const & child) { ELEKTRA_ASSERT (child.isBelow (parent), "The key `child` is not located below `parent`"); CppKey directChild = child.dup (); while (!directChild.isDirectBelow (parent)) { keySetBaseName (*directChild, 0); } return directChild; } /** * @brief This function determines if the given key is an array parent. * * @param parent This parameter specifies a possible array parent. * @param keys This variable stores the key set of `parent`. * * @retval true If `parent` is the parent key of an array * @retval false Otherwise */ bool isArrayParent (CppKey const & parent, CppKeySet const & keys) { CppKeySet children = accumulate (keys.begin (), keys.end (), CppKeySet{}, [&parent](CppKeySet collected, CppKey key) { if (key.isBelow (parent)) collected.append (key); return collected; }); for (auto child : children) { CppKey directChild = convertToDirectChild (parent, child); if (elektraArrayValidateName (*directChild) < 0) return false; } return true; } /** * @brief Split `keys` into two key sets, one for array parents and one for all other keys. * * @param keys This parameter contains the key set this function splits. * * @return A pair of key sets, where the first key set contains all array parents and the second key set contains all other keys */ pair<CppKeySet, CppKeySet> splitArrayParentsOther (CppKeySet const & keys) { CppKeySet arrayParents; CppKeySet others; keys.rewind (); CppKey previous; for (previous = keys.next (); keys.next (); previous = keys.current ()) { bool previousIsArray = previous.hasMeta ("array") || (keys.current ().isBelow (previous) && keys.current ().getBaseName ()[0] == '#' && isArrayParent (previous, keys)); (previousIsArray ? arrayParents : others).append (previous); } (previous.hasMeta ("array") ? arrayParents : others).append (previous); ELEKTRA_ASSERT (arrayParents.size () + others.size () == keys.size (), "Number of keys in split key sets: %zu ≠ number in given key set %zu", arrayParents.size () + others.size (), keys.size ()); return make_pair (arrayParents, others); } /** * @brief This function splits `keys` into two key sets, one for array parents and elements, and the other one for all other keys. * * @param arrayParents This key set contains a (copy) of all array parents of `keys`. * @param keys This parameter contains the key set this function splits. * * @return A pair of key sets, where the first key set contains all array parents and elements, * and the second key set contains all other keys */ pair<CppKeySet, CppKeySet> splitArrayOther (CppKeySet const & arrayParents, CppKeySet const & keys) { CppKeySet others = keys.dup (); CppKeySet arrays; for (auto parent : arrayParents) { arrays.append (others.cut (parent)); } return make_pair (arrays, others); } /** * @brief This function increases an array index of the given array element by one. * * @param parent This key set stores an array parent of `element`. The function will increase the index of `element` that is directly below * this key. * @param element This parameter stores an array element. * * @return A copy of `element`, where the index below `parent` was increased by one */ CppKey increaseArrayIndex (CppKey const & parent, CppKey const & element) { CppKey elementNewIndex = convertToDirectChild (parent, element); string postfix = elektraKeyGetRelativeName (*element, *elementNewIndex); if (elektraArrayIncName (*elementNewIndex)) { throw range_error ("Unable to increase index of key “" + elementNewIndex.getName () + "”"); } elementNewIndex.addName (postfix); ELEKTRA_LOG_DEBUG ("New name of “%s” is “%s”", element.getName ().c_str (), elementNewIndex.getName ().c_str ()); return elementNewIndex; } /** * @brief Increase the array index of array elements by one. * * Since it is also possible that one of the array parents is part of another array, this function also updates the indices of the given * array parents. * * @param parents This parameter contains the array parents for which this function increases the index by one. * @param parents This variable stores the arrays elements this function updates. * * @return A pair containing a copy of `parents` and `arrays`, where all indices specified by `parents` are increased by one */ pair<CppKeySet, CppKeySet> increaseArrayIndices (CppKeySet const & parents, CppKeySet const & arrays) { CppKeySet arraysIncreasedIndex = arrays.dup (); CppKeySet arrayParents = parents.dup (); CppKeySet updatedParents = parents.dup (); while (CppKey parent = arrayParents.pop ()) { ELEKTRA_LOG_DEBUG ("Increase indices for array parent “%s”", parent.getName ().c_str ()); CppKeySet newArrays; for (auto key : arraysIncreasedIndex) { if (key.isBelow (parent)) { auto updated = increaseArrayIndex (parent, key); if (updatedParents.lookup (key, KDB_O_POP)) updatedParents.append (updated); newArrays.append (updated); } else { newArrays.append (key); } } arraysIncreasedIndex = newArrays; } return make_pair (updatedParents, arraysIncreasedIndex); } /** * @brief Split `keys` into two key sets, one for directories (keys without children) and one for all other keys. * * @param keys This parameter contains the key set this function splits. * * @return A pair of key sets, where the first key set contains all directories and the second key set contains all leaves */ pair<CppKeySet, CppKeySet> splitDirectoriesLeaves (CppKeySet const & keys) { CppKeySet leaves; CppKeySet directories; keys.rewind (); CppKey previous; for (previous = keys.next (); keys.next (); previous = keys.current ()) { if (keys.current ().isBelow (previous)) { directories.append (previous); } else { leaves.append (previous); } } leaves.append (previous); return make_pair (directories, leaves); } /** * @brief Convert all keys in `parents` to an empty array parent and an array element with index `#0` storing the data of the old key. * * @param parents This parameter contains the set of array parent this function converts. * * @return A key set containing only empty array parents and corresponding array elements storing the values of the old array parent */ CppKeySet convertArrayParentsToLeaves (CppKeySet const & parents) { CppKeySet converted; for (auto parent : parents) { CppKey directory{ parent.getName (), KS_END }; CppKey leaf = parent.dup (); leaf.addBaseName ("#0"); converted.append (directory); converted.append (leaf); } return converted; } /** * @brief Convert all keys in `directories` to an empty key and a leaf key containing the data of the old key. * * @param directories This parameter contains a set of directory keys this function converts. * * @return A key set containing only empty directory keys and corresponding leaf keys storing the values of the old directory keys */ CppKeySet convertDirectoriesToLeaves (CppKeySet const & directories) { CppKeySet directoryLeaves; for (auto directory : directories) { CppKey emptyDirectory{ directory.getName (), KS_END }; CppKey leaf = directory.dup (); leaf.addBaseName (DIRECTORY_POSTFIX); directoryLeaves.append (leaf); directoryLeaves.append (emptyDirectory); } return directoryLeaves; } // -- Class -------------------------------------------------------------------------------------------------------------------------------- /** * @brief This constructor creates a new delegate object used by the `leaf` plugin * * @param config This key set contains configuration values provided by the `leaf` plugin */ LeafDelegate::LeafDelegate (CppKeySet config ELEKTRA_UNUSED) { } /** * @brief This method converts all leaf keys in the given key set to directory keys. * * @param keys This parameter specifies the key set this function converts. * * @retval ELEKTRA_PLUGIN_STATUS_SUCCESS If the plugin converted any value in the given key set * @retval ELEKTRA_PLUGIN_STATUS_NO_UPDATE If the plugin did not update `keys` */ int LeafDelegate::convertToDirectories (CppKeySet & keys) { CppKeySet directoryLeaves; CppKeySet nonDirectoryLeaves; /** * - Split array parents * - Split first array child containing directory value prefix, others * - Convert first array child back to array parent * - Decrease index of arrays * - Merge everything back together and convert directories to leaves */ tie (directoryLeaves, nonDirectoryLeaves) = splitDirectoryLeavesOther (keys); bool status = directoryLeaves.size () > 0 ? ELEKTRA_PLUGIN_STATUS_SUCCESS : ELEKTRA_PLUGIN_STATUS_NO_UPDATE; auto directories = convertLeavesToDirectories (directoryLeaves); keys.clear (); keys.append (nonDirectoryLeaves); keys.append (directories); return status; } /** * @brief This method converts all directory keys in the given key set to leaf keys. * * @param keys This parameter specifies the key set this function converts. * * @retval ELEKTRA_PLUGIN_STATUS_SUCCESS If the plugin converted any value in the given key set * @retval ELEKTRA_PLUGIN_STATUS_NO_UPDATE If the plugin did not update `keys` */ int LeafDelegate::convertToLeaves (CppKeySet & keys) { CppKeySet notArrayParents; CppKeySet arrayParents; CppKeySet arrays; CppKeySet nonArrays; CppKeySet directories; CppKeySet leaves; tie (arrayParents, ignore) = splitArrayParentsOther (keys); tie (arrays, nonArrays) = splitArrayOther (arrayParents, keys); tie (arrayParents, arrays) = increaseArrayIndices (arrayParents, arrays); notArrayParents.append (arrays); notArrayParents.append (nonArrays); notArrayParents = accumulate (notArrayParents.begin (), notArrayParents.end (), CppKeySet{}, [&arrayParents](CppKeySet collected, CppKey key) { if (!arrayParents.lookup (key)) collected.append (key); return collected; }); arrayParents = convertArrayParentsToLeaves (arrayParents); tie (directories, leaves) = splitDirectoriesLeaves (notArrayParents); bool status = directories.size () > 0 || arrayParents.size () > 0 ? ELEKTRA_PLUGIN_STATUS_SUCCESS : ELEKTRA_PLUGIN_STATUS_NO_UPDATE; auto directoryLeaves = convertDirectoriesToLeaves (directories); keys.clear (); keys.append (arrays); keys.append (arrayParents); keys.append (directoryLeaves); keys.append (leaves); return status; } } // end namespace elektra <|endoftext|>
<commit_before>#ifndef SRC_PORTS_EVENT_SOURCES_EVENT_SOURCES_HPP_ #define SRC_PORTS_EVENT_SOURCES_EVENT_SOURCES_HPP_ #include <cassert> #include <functional> #include <memory> #include <vector> #include <core/traits.hpp> #include <core/connection.hpp> #include <ports/port_traits.hpp> #include <core/detail/active_connection_proxy.hpp> #include <iostream> namespace fc { /** * \brief minimal output port for events. * * fulfills active_source * can be connected to multiples sinks and stores these in a shared std::vector. * * \tparam event_t type of event stored, needs to fulfill copy_constructable. * \invariant shared pointer event_handlers != 0. */ template<class event_t> struct event_out_port { typedef typename std::remove_reference<event_t>::type result_t; typedef typename detail::handle_type<result_t>::type handler_t; event_out_port() = default; event_out_port(const event_out_port&) = default; template<class... T> void fire(T&&... event) { static_assert(sizeof...(T) == 0 || sizeof...(T) == 1, "we only allow single events, or void events atm"); assert(event_handlers); for (auto& target : (*event_handlers)) { assert(target); target(static_cast<event_t>(event)...); } } size_t nr_connected_handlers() const { assert(event_handlers); return event_handlers->size(); } /** * \brief connects new connectable target to port. * \param new_handler the new target to be connected. * \pre new_handler is not empty function * \post event_handlers.empty() == false */ auto connect(handler_t new_handler) { assert(event_handlers); assert(new_handler); //connecting empty functions is illegal event_handlers->push_back(new_handler); assert(!event_handlers->empty()); return port_connection<decltype(*this), handler_t, result_t>(); } private: // stores event_handlers in shared vector, since the port is stored in a node // but will be copied, when it is connected. The node needs to send // to all connected event_handlers, when an event is fired. typedef std::vector<handler_t> handler_vector; std::shared_ptr<handler_vector> event_handlers = std::make_shared<handler_vector>(0); }; // traits // TODO prefer to test this algorithmically template<class T> struct is_port<event_out_port<T>> : public std::true_type {}; } // namespace fc #endif /* SRC_PORTS_EVENT_SOURCES_EVENT_SOURCES_HPP_ */ <commit_msg>added check for conversion in event_source.fire<commit_after>#ifndef SRC_PORTS_EVENT_SOURCES_EVENT_SOURCES_HPP_ #define SRC_PORTS_EVENT_SOURCES_EVENT_SOURCES_HPP_ #include <cassert> #include <functional> #include <memory> #include <vector> #include <core/traits.hpp> #include <core/connection.hpp> #include <ports/port_traits.hpp> #include <core/detail/active_connection_proxy.hpp> #include <iostream> namespace fc { /** * \brief minimal output port for events. * * fulfills active_source * can be connected to multiples sinks and stores these in a shared std::vector. * * \tparam event_t type of event stored, needs to fulfill copy_constructable. * \invariant shared pointer event_handlers != 0. */ template<class event_t> struct event_out_port { typedef typename std::remove_reference<event_t>::type result_t; typedef typename detail::handle_type<result_t>::type handler_t; event_out_port() = default; event_out_port(const event_out_port&) = default; template<class... T> void fire(T&&... event) { static_assert(sizeof...(T) == 0 || sizeof...(T) == 1, "we only allow single events, or void events atm"); static_assert(std::is_void<event_t>() || std::is_constructible< typename std::remove_reference<T>::type..., typename std::remove_reference<event_t>::type>(), "tried to call fire with a type, not implicitly convertible to type of port." "If conversion is required, do the cast before calling fire."); assert(event_handlers); for (auto& target : (*event_handlers)) { assert(target); target(static_cast<event_t>(event)...); } } size_t nr_connected_handlers() const { assert(event_handlers); return event_handlers->size(); } /** * \brief connects new connectable target to port. * \param new_handler the new target to be connected. * \pre new_handler is not empty function * \post event_handlers.empty() == false */ auto connect(handler_t new_handler) { assert(event_handlers); assert(new_handler); //connecting empty functions is illegal event_handlers->push_back(new_handler); assert(!event_handlers->empty()); return port_connection<decltype(*this), handler_t, result_t>(); } private: // stores event_handlers in shared vector, since the port is stored in a node // but will be copied, when it is connected. The node needs to send // to all connected event_handlers, when an event is fired. typedef std::vector<handler_t> handler_vector; std::shared_ptr<handler_vector> event_handlers = std::make_shared<handler_vector>(0); }; // traits // TODO prefer to test this algorithmically template<class T> struct is_port<event_out_port<T>> : public std::true_type {}; } // namespace fc #endif /* SRC_PORTS_EVENT_SOURCES_EVENT_SOURCES_HPP_ */ <|endoftext|>
<commit_before>#include "netupdater.h" namespace openalpp { NetUpdater::NetUpdater(ost::UDPSocket *socket,ost::TCPStream *controlsocket, const ALuint buffer1,ALuint buffer2, ALenum format,unsigned int frequency, unsigned int packetsize) : StreamUpdater(buffer1,buffer2,format,frequency), socket_(socket) , controlsocket_(controlsocket), packetsize_(packetsize) { } void NetUpdater::Run() { void *buffer=malloc(packetsize_); unsigned int len; while(1) { if(socket_->isPending(ost::SOCKET_PENDING_INPUT,2000)) { len=socket_->Recv(buffer,packetsize_); Update(buffer,len); } else { Sleep(50); if(controlsocket_ && controlsocket_->isPending(ost::SOCKET_PENDING_INPUT,100)) { char instr[100]; *controlsocket_ >> instr; break; } } } free(buffer); } } <commit_msg>Added flag for ending receive loop<commit_after>#include "netupdater.h" namespace openalpp { NetUpdater::NetUpdater(ost::UDPSocket *socket,ost::TCPStream *controlsocket, const ALuint buffer1,ALuint buffer2, ALenum format,unsigned int frequency, unsigned int packetsize) : StreamUpdater(buffer1,buffer2,format,frequency), socket_(socket) , controlsocket_(controlsocket), packetsize_(packetsize) { } void NetUpdater::Run() { void *buffer=malloc(packetsize_); unsigned int len; runmutex_.EnterMutex(); while(!stoprunning_) { runmutex_.LeaveMutex(); if(socket_->isPending(ost::SOCKET_PENDING_INPUT,1000)) { len=socket_->Recv(buffer,packetsize_); Update(buffer,len); } else { if(controlsocket_ && controlsocket_->isPending(ost::SOCKET_PENDING_INPUT,100)) { char instr[100]; *controlsocket_ >> instr; runmutex_.EnterMutex(); break; } } runmutex_.EnterMutex(); } runmutex_.LeaveMutex(); free(buffer); } } <|endoftext|>
<commit_before>#pragma once #include <string> #include <map> #include <vector> class RefeusProcess { private: std::string executable; private: std::map<std::string,std::string> environmentmap; private: std::vector<std::string> parametersvector; private: void configureNewRefeusDocument(); private: void configureOpenRefeusDocument(std::string pathname); private: void configureCloudSetting(); private: void usage(); public: RefeusProcess(); public: bool argParser(char* cmd); public: void langCheck(int check); public: void setEnvironment(std::string env_name, std::string env_value); public: std::vector<std::string> &split(const std::string &string_to_split, char delimiter_character, std::vector<std::string> &element_vector); public: bool start(); }; #endif <commit_msg>reoder member functions<commit_after>#pragma once #include <string> #include <map> #include <vector> class RefeusProcess { private: std::map<std::string,std::string> environmentmap; private: std::string executable; private: std::vector<std::string> parametersvector; private: void configureCloudSetting(); private: void configureDebug(); private: void configureNewRefeusDocument(); private: void configureOpenRefeusDocument(std::string pathname); private: void usage(); public: RefeusProcess(); public: bool argParser(std::string command_line); public: void langCheck(int check); public: void setEnvironment(std::string env_name, std::string env_value); public: std::vector<std::string> &split(const std::string &string_to_split, char delimiter_character, std::vector<std::string> &element_vector); public: int start(); }; <|endoftext|>
<commit_before>// // MIT License // Copyright (c) 2017 Roman Orlov // See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT // #ifndef _TFL_META17_HPP_ #define _TFL_META17_HPP_ #include <cstddef> #include <utility> namespace tfl::detail { // // Entity representing one flag with its type and index // template<typename T, size_t N> struct name_index { typedef T type; static constexpr size_t index = N; }; struct empty; // // Sequence of name_index entities // template<typename Head=empty, typename... Tail> struct name_index_sequence; template<typename T, typename... Args> struct to_name_index_sequence; template<size_t... I, typename... Args> struct to_name_index_sequence<std::index_sequence<I...>, Args...> { typedef name_index_sequence<name_index<Args, I>...> type; }; // // Helper class counting occurrences of T in Args // template<typename T, typename... Args> struct counter { static constexpr size_t value = (0 + ... + std::is_same<T, Args>::value); }; // // Helper class checking that every type is unique. // Every type must appear in sequence only once. // template<typename... Args> struct is_unique { static constexpr bool value = (... && (counter<Args, Args...>::value == 1)); }; template<typename T, typename U> struct index_getter; // // List is empty, so type index is -1 // template<typename T> struct index_getter<T, name_index_sequence<empty>> { static constexpr size_t value = -1; }; struct index { size_t value = -1; index() = default; constexpr explicit index(size_t v): value(v) {} constexpr explicit operator size_t() const { return value; } }; constexpr index operator << (index const& lhs, index const& rhs) { return lhs.value < rhs.value ? lhs : rhs; } // // Find type by matching it with each element in the list // template<typename T, typename... Args> struct index_getter<T, name_index_sequence<Args...>> { static constexpr size_t value = static_cast<size_t>( (index{} << ... << (std::is_same<T, typename Args::type> ::value ? index{Args::index} : index{}))); }; } // namespace tfl::detail #endif <commit_msg>No need for list terminator in C++17<commit_after>// // MIT License // Copyright (c) 2017 Roman Orlov // See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT // #ifndef _TFL_META17_HPP_ #define _TFL_META17_HPP_ #include <cstddef> #include <utility> namespace tfl::detail { // // Entity representing one flag with its type and index // template<typename T, size_t N> struct name_index { typedef T type; static constexpr size_t index = N; }; // // Sequence of name_index entities // template<typename... Args> struct name_index_sequence; template<typename T, typename... Args> struct to_name_index_sequence; template<size_t... I, typename... Args> struct to_name_index_sequence<std::index_sequence<I...>, Args...> { typedef name_index_sequence<name_index<Args, I>...> type; }; // // Helper class counting occurrences of T in Args // template<typename T, typename... Args> struct counter { static constexpr size_t value = (0 + ... + std::is_same<T, Args>::value); }; // // Helper class checking that every type is unique. // Every type must appear in sequence only once. // template<typename... Args> struct is_unique { static constexpr bool value = (... && (counter<Args, Args...>::value == 1)); }; template<typename T, typename U> struct index_getter; struct index { size_t value = -1; index() = default; constexpr explicit index(size_t v): value(v) {} constexpr explicit operator size_t() const { return value; } }; constexpr index operator << (index const& lhs, index const& rhs) { return lhs.value < rhs.value ? lhs : rhs; } // // Find type by matching it with each element in the list // template<typename T, typename... Args> struct index_getter<T, name_index_sequence<Args...>> { static constexpr size_t value = static_cast<size_t>( (index{} << ... << (std::is_same<T, typename Args::type> ::value ? index{Args::index} : index{}))); }; } // namespace tfl::detail #endif <|endoftext|>
<commit_before>// // TestMapScene.cpp // everlost // // Created by Cedric Porter on 14-5-3. // // #include "TestMapScene.h" USING_NS_CC; Scene* TestMapScene::createScene() { auto scene = Scene::createWithPhysics(); scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); auto layer = TestMapScene::create(); scene->addChild(layer); return scene; } bool TestMapScene::init() { bool ret = false; do { CC_BREAK_IF(!Layer::init()); Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); auto node = Sprite::create("close.png"); CC_BREAK_IF(!node); auto body = PhysicsBody::createCircle(node->getContentSize().width / 2); node->setPhysicsBody(body); node->setPosition(Point(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)); this->addChild(node); auto map = TMXTiledMap::create("map1.tmx"); map->setPosition(origin.x - map->getTileSize().width / 2, origin.y + map->getTileSize().height / 2); this->addChild(map, 0, 101); auto collisionLayer = map->getLayer("Collision"); auto pTile = collisionLayer->getTiles(); Size size = collisionLayer->getLayerSize(); for (ssize_t i = 0; i < size.width * size.height; i++) { auto tileGid = pTile[i]; auto prop = map->getPropertiesForGID(tileGid).asValueMap(); auto collision = prop["Collidable"]; auto Collidable = collision.asString(); if (! Collidable.empty() && Collidable == "True") { auto node = Node::create(); this->addChild(node); Size sz = collisionLayer->getLayerSize(); int y = i / collisionLayer->getLayerSize().width; int x = i - y * collisionLayer->getLayerSize().width; y = collisionLayer->getLayerSize().height - y; log("(%d, %d), i %d", x, y, i); auto pt = Point(x * map->getTileSize().width, y * map->getTileSize().height); node->setPosition(origin + pt); log("pos (%f, %f)", node->getPosition().x, node->getPosition().y); log("pt (%f, %f)", pt.x, pt.y); auto body = PhysicsBody::createBox(map->getTileSize()); body->setDynamic(false); node->setPhysicsBody(body); } } ret = true; } while (0); return ret; }<commit_msg>use mouse to move the ball for TestMapScene<commit_after>// // TestMapScene.cpp // everlost // // Created by Cedric Porter on 14-5-3. // // #include "TestMapScene.h" USING_NS_CC; Scene* TestMapScene::createScene() { auto scene = Scene::createWithPhysics(); scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); auto layer = TestMapScene::create(); scene->addChild(layer); return scene; } bool TestMapScene::init() { bool ret = false; do { CC_BREAK_IF(!Layer::init()); Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); auto node = Sprite::create("close.png"); CC_BREAK_IF(!node); auto body = PhysicsBody::createCircle(node->getContentSize().width / 2); node->setPhysicsBody(body); node->setPosition(Point(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)); this->addChild(node); auto map = TMXTiledMap::create("map1.tmx"); map->setPosition(origin.x - map->getTileSize().width / 2, origin.y + map->getTileSize().height / 2); this->addChild(map, 0, 101); auto collisionLayer = map->getLayer("Collision"); auto pTile = collisionLayer->getTiles(); Size size = collisionLayer->getLayerSize(); for (ssize_t i = 0; i < size.width * size.height; i++) { auto tileGid = pTile[i]; auto prop = map->getPropertiesForGID(tileGid).asValueMap(); auto collision = prop["Collidable"]; auto Collidable = collision.asString(); if (! Collidable.empty() && Collidable == "True") { auto node = Node::create(); this->addChild(node); Size sz = collisionLayer->getLayerSize(); int y = i / collisionLayer->getLayerSize().width; int x = i - y * collisionLayer->getLayerSize().width; y = collisionLayer->getLayerSize().height - y; log("(%d, %d), i %d", x, y, i); auto pt = Point(x * map->getTileSize().width, y * map->getTileSize().height); node->setPosition(origin + pt); log("pos (%f, %f)", node->getPosition().x, node->getPosition().y); log("pt (%f, %f)", pt.x, pt.y); auto body = PhysicsBody::createBox(map->getTileSize()); body->setDynamic(false); node->setPhysicsBody(body); } } auto touchListner = EventListenerTouchOneByOne::create(); bool touchMoved = false; touchListner->onTouchBegan = [this, &touchMoved](Touch* touch, Event* event) -> bool { touchMoved = true; return true; }; touchListner->onTouchMoved = [this, body, &touchMoved](Touch* touch, Event* event) { if (touchMoved) { auto location = touch->getLocation(); auto offset = location - body->getPosition(); body->applyForce(Vect(offset.x * 100, offset.y * 100)); } }; touchListner->onTouchEnded = [this, &touchMoved](Touch* touch, Event* event) { touchMoved = false; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListner, this); ret = true; } while (0); return ret; }<|endoftext|>
<commit_before>// Copyright 2017 Global Phasing Ltd. #ifndef GEMMI_VERSION_HPP_ #define GEMMI_VERSION_HPP_ #define GEMMI_VERSION "0.1.2" #endif <commit_msg>bump version before uploading to PyPI<commit_after>// Copyright 2017 Global Phasing Ltd. #ifndef GEMMI_VERSION_HPP_ #define GEMMI_VERSION_HPP_ #define GEMMI_VERSION "0.1.3" #endif <|endoftext|>
<commit_before>#pragma once #ifndef IBOTPP_LOADER_HPP #define IBOTPP_LOADER_HPP #include <string> #include <boost/container/vector.hpp> #include <clang/CodeGen/CodeGenAction.h> #include <clang/Driver/Compilation.h> #include <clang/Driver/Driver.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/Interpreter.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/Host.h> #include <llvm/Support/Program.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/raw_ostream.h> #include <ibotpp/module.hpp> namespace ibotpp { class loader { private: std::unique_ptr<llvm::LLVMContext> llvm_context; llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diag_ids; llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diag_options; clang::DiagnosticsEngine diag_engine; std::unique_ptr<clang::driver::Driver> driver; llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> invocation; clang::CompilerInstance compiler; public: loader(void) : llvm_context(new llvm::LLVMContext()), diag_ids(new clang::DiagnosticIDs()), diag_options(new clang::DiagnosticOptions()), diag_engine(diag_ids, diag_options.get(), new clang::TextDiagnosticPrinter(llvm::errs(), diag_options.get())), invocation(new clang::CompilerInvocation()) { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); auto error_or_clang_path = llvm::sys::findProgramByName("clang++"); if(!error_or_clang_path) { throw std::runtime_error("failed to find path of clang executable"); } driver = std::unique_ptr<clang::driver::Driver>( new clang::driver::Driver(error_or_clang_path.get(), llvm::sys::getDefaultTargetTriple(), diag_engine)); driver->setCheckInputsExist(false); compiler.createDiagnostics(); if(!compiler.hasDiagnostics()) { throw std::runtime_error("failed to create compiler instance with diagnostics"); } } std::unique_ptr<ibotpp::module> load(const std::string &path) { return get_module_value(load_llvm_module(path)); } std::unique_ptr<llvm::Module> load_llvm_module(const std::string &path) { auto compilation = driver->BuildCompilation({"-c++", "-std=c++11", "-include", "module.hpp", path.c_str()}); if(!compilation) { throw std::runtime_error("failed to build driver compilation"); } auto &jobs = compilation->getJobs(); auto &cmd = llvm::cast<clang::driver::Command>(*jobs.begin()); auto &args = cmd.getArguments(); clang::CompilerInvocation::CreateFromArgs(*invocation, args.data(), args.data() + args.size(), diag_engine); //llvm::errs() << "clang invocation: "; //jobs.Print(llvm::errs(), " ", true); //llvm::errs() << "\n"; compiler.setInvocation(invocation.get()); clang::EmitLLVMOnlyAction action(llvm_context.get()); if(!compiler.ExecuteAction(action)) { throw std::runtime_error("failed to execute action"); } return action.takeModule(); } std::unique_ptr<ibotpp::module> get_module_value(std::unique_ptr<llvm::Module> module) { auto fn = module->getFunction("module"); if(!fn) { throw std::runtime_error("failed to find module function"); } std::string err; auto exec_engine = llvm::EngineBuilder(std::move(module)) .setEngineKind(llvm::EngineKind::Either) .setErrorStr(&err) .create(); if(!exec_engine) { throw std::runtime_error("failed to create execution engine: " + err); } exec_engine->finalizeObject(); auto value = exec_engine->runFunction(fn, {}); auto ptr = reinterpret_cast<ibotpp::module *>(value.PointerVal); return std::unique_ptr<ibotpp::module>(ptr); } }; } #endif <commit_msg>loader: add llvm_destroy_obj guard to class<commit_after>#pragma once #ifndef IBOTPP_LOADER_HPP #define IBOTPP_LOADER_HPP #include <string> #include <boost/container/vector.hpp> #include <clang/CodeGen/CodeGenAction.h> #include <clang/Driver/Compilation.h> #include <clang/Driver/Driver.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/Interpreter.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/Host.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/Program.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/raw_ostream.h> #include <ibotpp/module.hpp> namespace ibotpp { class loader { private: std::unique_ptr<llvm::LLVMContext> llvm_context; llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diag_ids; llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diag_options; clang::DiagnosticsEngine diag_engine; std::unique_ptr<clang::driver::Driver> driver; llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> invocation; clang::CompilerInstance compiler; llvm::llvm_shutdown_obj llvm_destructor; public: loader(void) : llvm_context(new llvm::LLVMContext()), diag_ids(new clang::DiagnosticIDs()), diag_options(new clang::DiagnosticOptions()), diag_engine(diag_ids, diag_options.get(), new clang::TextDiagnosticPrinter(llvm::errs(), diag_options.get())), invocation(new clang::CompilerInvocation()) { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); auto error_or_clang_path = llvm::sys::findProgramByName("clang++"); if(!error_or_clang_path) { throw std::runtime_error("failed to find path of clang executable"); } driver = std::unique_ptr<clang::driver::Driver>( new clang::driver::Driver(error_or_clang_path.get(), llvm::sys::getDefaultTargetTriple(), diag_engine)); driver->setCheckInputsExist(false); compiler.createDiagnostics(); if(!compiler.hasDiagnostics()) { throw std::runtime_error("failed to create compiler instance with diagnostics"); } } std::unique_ptr<ibotpp::module> load(const std::string &path) { return get_module_value(load_llvm_module(path)); } std::unique_ptr<llvm::Module> load_llvm_module(const std::string &path) { auto compilation = driver->BuildCompilation({"-c++", "-std=c++11", "-include", "module.hpp", path.c_str()}); if(!compilation) { throw std::runtime_error("failed to build driver compilation"); } auto &jobs = compilation->getJobs(); auto &cmd = llvm::cast<clang::driver::Command>(*jobs.begin()); auto &args = cmd.getArguments(); clang::CompilerInvocation::CreateFromArgs(*invocation, args.data(), args.data() + args.size(), diag_engine); //llvm::errs() << "clang invocation: "; //jobs.Print(llvm::errs(), " ", true); //llvm::errs() << "\n"; compiler.setInvocation(invocation.get()); clang::EmitLLVMOnlyAction action(llvm_context.get()); if(!compiler.ExecuteAction(action)) { throw std::runtime_error("failed to execute action"); } return action.takeModule(); } std::unique_ptr<ibotpp::module> get_module_value(std::unique_ptr<llvm::Module> module) { auto fn = module->getFunction("module"); if(!fn) { throw std::runtime_error("failed to find module function"); } std::string err; auto exec_engine = llvm::EngineBuilder(std::move(module)) .setEngineKind(llvm::EngineKind::Either) .setErrorStr(&err) .create(); if(!exec_engine) { throw std::runtime_error("failed to create execution engine: " + err); } exec_engine->finalizeObject(); auto value = exec_engine->runFunction(fn, {}); auto ptr = reinterpret_cast<ibotpp::module *>(value.PointerVal); return std::unique_ptr<ibotpp::module>(ptr); } }; } #endif <|endoftext|>
<commit_before>/// \file kernel/userver.hh /// \brief Definition of the UServer class. #ifndef KERNEL_USERVER_HH # define KERNEL_USERVER_HH # include <cstdarg> # include <sstream> # include <libport/config.h> # if LIBPORT_HAVE_WINDOWS_H // Without this, windows.h may include winsock.h, which will conflict with // winsock2.h when we will try to include it. # define WIN32_LEAN_AND_MEAN # endif # include <libport/fwd.hh> # include <libport/compiler.hh> # include <libport/file-library.hh> # include <libport/ufloat.h> # include <libport/utime.hh> # include <kernel/fwd.hh> # include <urbi/export.hh> # include <kernel/utypes.hh> // Do not include runner/fwd.hh etc. which are not public. namespace runner { class Runner; } namespace scheduler { class Scheduler; } extern const char* DISPLAY_FORMAT; extern const char* DISPLAY_FORMAT1; extern const char* DISPLAY_FORMAT2; /// Global variable for the server extern class UServer* urbiserver; //! UServer class: handles all URBI system processing. /*! There must be one UServer defined in the program and it must be overloaded to make it specific to the particular robot. UServer is used to store the UConnection list and the UDevice list. This object does all the internal processing of URBI and handles the pool of UCommand's. */ class USDK_API UServer { public: UServer(const char* mainName); virtual ~UServer (); public: //! Initialization of the server. Displays the header message & init stuff /*! This function must be called once the server is operational and able to print messages. It is a requirement for URBI compliance to print the header at start, so this function *must* be called. Beside, it also do initalization work for the devices and system variables. */ void initialize (); /// Process the jobs. /// \return the time when should be called again. libport::utime_t work (); /// Set the system.args list in URBI. void main (int argc, const char* argv[]); /// Package information about this server. static const libport::PackageInfo& package_info (); //! Displays a formatted error message. /*! This function uses the virtual URobot::display() function to make the message printing robot-specific. It formats the output in a standard URBI way by adding an ERROR key between brackets at the end. */ void error (const char* s, ...) __attribute__ ((__format__ (__printf__, 2, 3))); //! Displays a formatted message. /*! This function uses the virtual URobot::display() function to make the message printing robot-specific. It formats the output in a standard URBI way by adding an empty key between brackets at the end. If you want to specify a key, use the echoKey() function. \param s is the formatted string containing the message. \sa echoKey() */ void echo (const char* s, ...) __attribute__ ((__format__ (__printf__, 2, 3))); //! Display a formatted message, with a key. /*! This function uses the virtual URobot::display() function to make the message printing robot-specific. It formats the output in a standard URBI way by adding a key between brackets at the end. This key can be "" or NULL.It can be used to visually extract information from the flux of messages printed by the server. \param key is the message key. Maxlength = 5 chars. \param s is the formatted string containing the message. \param args Arguments for the format string. */ void vecho_key (const char* key, const char* s, va_list args) __attribute__ ((__format__ (__printf__, 3, 0))); void echoKey (const char* key, const char* s, ...) __attribute__ ((__format__ (__printf__, 3, 4))); /// Send debugging data. /*! This function uses the virtual URobot::display() function to make the message printing robot-specific. \param s is the formatted string containing the message \param args Arguments for the format string. */ void vdebug (const char* s, va_list args) __attribute__ ((__format__ (__printf__, 2, 0))); void debug (const char* s, ...) __attribute__ ((__format__ (__printf__, 2, 3))); //! Overload this function to return the running time of the server. /*! The running time of the server must be in milliseconds. */ virtual libport::utime_t getTime () = 0; //! Overload this function to return the remaining power of the robot /*! The remaining power is expressed as percentage. 0 for empty batteries and 1 for full power. */ virtual ufloat getPower () = 0; //! Overload this function to return a specific header for your URBI server /*! Used to give some information specific to your server in the standardized header which is displayed on the server output at start and in the connection when a new connection is created.\n Typical custom header should be like: *** URBI version xx.xx for \<robotname\> robot\\n\n *** (c) Copyright \<year\> \<name\>\\n The function should return in header the line corresponding to 'line' or an empty string (not NULL!) when there is no line any more. Each line is supposed to end with a carriage return \\n and each line should start with three empty spaces. This complicated method is necessary to allow the connection to stamp every line with the standard URBI prefix [time:tag]. \param line is the requested line number \param header the custom header \param maxlength the maximum length allowed for the header (the parameter has been malloc'ed for that size). Typical size is 1024 octets and should be enough for any reasonable header. */ virtual void getCustomHeader (unsigned int line, char* header, size_t maxlength) = 0; /// Path to explore when looking for .u files. libport::file_library search_path; /// Return the full file name, handle paths. /// Return \a f on failure. virtual std::string find_file (const libport::path& path); /// Type of UCommandQueue enum QueueType { /// The UComandQueue contains URBI code. QUEUE_URBI, /// THe UCommandQueu contains data, not to be messed with. QUEUE_DATA }; /// Load a file into the connection. /// Returns UFAIL if anything goes wrong, USUCCESS otherwise. virtual UErrorValue load_file(const std::string& file_name, UQueue& loadQueue, QueueType t = QUEUE_URBI); /// Load \a fn in the ghostqueue. UErrorValue load_init_file(const char* fn); /// Save content to a file /// This function must be redefined by the robot-specific server. /// Returns UFAIL if anything goes wrong, USUCCESS otherwise. virtual UErrorValue save_file(const std::string& filename, const std::string& content) = 0; //! Overload this function to specify how your system will reboot virtual void reboot () = 0; //! Overload this function to specify how your system will shutdown virtual void shutdown (); //! Function called before work /*! Redefine this virtual function if you need to do pre-processing before the work function starts. */ virtual void beforeWork (); //! Function called after work /*! Redefine this virtual function if you need to do post-processing before the work function ends. */ virtual void afterWork (); /// Display a message on the robot console. void display (const char*); /// Display a set of messages on the robot console. void display (const char**); //! Accessor for lastTime_. libport::utime_t lastTime (); //! Update lastTime_ to current time. //! Update the server's time using the robot-specific implementation /*! It is necessary to have an update of the server time to increase the performance of successive calls to getTime. It allows also to see a whole processing session (like the processing of the command tree) as occuring AT the same time, from the server's point of view. */ void updateTime (); /*--------------. | Connections. | `--------------*/ /// Add a new connection to the connection list. /// Take ownership on c. Also perform some error testing on the connection /// value and UError return code /// \precondition c != 0 void connection_add(UConnection* c); /// Remove from connection_. /// Also perform some error testing on the connection /// value and UError return code /// Destroy \a c. void connection_remove(UConnection* c); /// \returns A usual connection to stop dependencies. /// (kernel/ghost-connection.hh is not public). UConnection& ghost_connection_get(); /*--------------------. | Scheduler, runner. | `--------------------*/ public: const scheduler::Scheduler& getScheduler () const; scheduler::Scheduler& getScheduler (); runner::Runner& getCurrentRunner () const; protected: //! Overload this function to specify how your robot is displaying messages. virtual void effectiveDisplay (const char*) = 0; private: // Pointer to stop the header dependency. scheduler::Scheduler* scheduler_; private: /// \{ Various parts of @c UServer::work. /// Scan currently opened connections for ongoing work void work_handle_connections_ (); /// Scan currently opened connections for deleting marked commands or /// killall order void work_handle_stopall_ (); void work_test_cpuoverload_ (); /// \} public: /// Shows debug or not. bool debugOutput; private: /// Name of the main device. std::string mainName_; public: /// Stops all commands in all connections. bool stopall; enum { /// Urbi TCP Port. TCP_PORT = 54000, }; private: /// Store the time on the last call to updateTime(). libport::utime_t lastTime_; /// List of active connections: includes one UGhostConnection. // FIXME: This is meant to become a runner::Job and move out of this class. /// A pointer to stop dependencies. std::auto_ptr<kernel::ConnectionSet> connections_; /// The ghost connection used for urbi.u, URBI.INI, etc. // Does not need to be an auto_ptr, as it is stored in connections_ // which handles memory management. UGhostConnection* ghost_; }; /*-------------------------. | Freestanding functions. | `-------------------------*/ /// Send debugging messages via ::urbiserver. void vdebug (const char* fmt, va_list args) __attribute__ ((__format__ (__printf__, 1, 0))); /// Send debugging messages via ::urbiserver. void debug (const char* fmt, ...) __attribute__ ((__format__ (__printf__, 1, 2))); // Send debugging messages. # if URBI_DEBUG // Must be invoked with two pairs of parens. # define DEBUG(Msg) debug Msg # else # define DEBUG(Msg) ((void) 0) # endif # include <kernel/userver.hxx> #endif // !KERNEL_USERVER_HH <commit_msg>Add missing include.<commit_after>/// \file kernel/userver.hh /// \brief Definition of the UServer class. #ifndef KERNEL_USERVER_HH # define KERNEL_USERVER_HH # include <cstdarg> # include <memory> # include <sstream> # include <libport/config.h> # if LIBPORT_HAVE_WINDOWS_H // Without this, windows.h may include winsock.h, which will conflict with // winsock2.h when we will try to include it. # define WIN32_LEAN_AND_MEAN # endif # include <libport/fwd.hh> # include <libport/compiler.hh> # include <libport/file-library.hh> # include <libport/ufloat.h> # include <libport/utime.hh> # include <kernel/fwd.hh> # include <urbi/export.hh> # include <kernel/utypes.hh> // Do not include runner/fwd.hh etc. which are not public. namespace runner { class Runner; } namespace scheduler { class Scheduler; } extern const char* DISPLAY_FORMAT; extern const char* DISPLAY_FORMAT1; extern const char* DISPLAY_FORMAT2; /// Global variable for the server extern class UServer* urbiserver; //! UServer class: handles all URBI system processing. /*! There must be one UServer defined in the program and it must be overloaded to make it specific to the particular robot. UServer is used to store the UConnection list and the UDevice list. This object does all the internal processing of URBI and handles the pool of UCommand's. */ class USDK_API UServer { public: UServer(const char* mainName); virtual ~UServer (); public: //! Initialization of the server. Displays the header message & init stuff /*! This function must be called once the server is operational and able to print messages. It is a requirement for URBI compliance to print the header at start, so this function *must* be called. Beside, it also do initalization work for the devices and system variables. */ void initialize (); /// Process the jobs. /// \return the time when should be called again. libport::utime_t work (); /// Set the system.args list in URBI. void main (int argc, const char* argv[]); /// Package information about this server. static const libport::PackageInfo& package_info (); //! Displays a formatted error message. /*! This function uses the virtual URobot::display() function to make the message printing robot-specific. It formats the output in a standard URBI way by adding an ERROR key between brackets at the end. */ void error (const char* s, ...) __attribute__ ((__format__ (__printf__, 2, 3))); //! Displays a formatted message. /*! This function uses the virtual URobot::display() function to make the message printing robot-specific. It formats the output in a standard URBI way by adding an empty key between brackets at the end. If you want to specify a key, use the echoKey() function. \param s is the formatted string containing the message. \sa echoKey() */ void echo (const char* s, ...) __attribute__ ((__format__ (__printf__, 2, 3))); //! Display a formatted message, with a key. /*! This function uses the virtual URobot::display() function to make the message printing robot-specific. It formats the output in a standard URBI way by adding a key between brackets at the end. This key can be "" or NULL.It can be used to visually extract information from the flux of messages printed by the server. \param key is the message key. Maxlength = 5 chars. \param s is the formatted string containing the message. \param args Arguments for the format string. */ void vecho_key (const char* key, const char* s, va_list args) __attribute__ ((__format__ (__printf__, 3, 0))); void echoKey (const char* key, const char* s, ...) __attribute__ ((__format__ (__printf__, 3, 4))); /// Send debugging data. /*! This function uses the virtual URobot::display() function to make the message printing robot-specific. \param s is the formatted string containing the message \param args Arguments for the format string. */ void vdebug (const char* s, va_list args) __attribute__ ((__format__ (__printf__, 2, 0))); void debug (const char* s, ...) __attribute__ ((__format__ (__printf__, 2, 3))); //! Overload this function to return the running time of the server. /*! The running time of the server must be in milliseconds. */ virtual libport::utime_t getTime () = 0; //! Overload this function to return the remaining power of the robot /*! The remaining power is expressed as percentage. 0 for empty batteries and 1 for full power. */ virtual ufloat getPower () = 0; //! Overload this function to return a specific header for your URBI server /*! Used to give some information specific to your server in the standardized header which is displayed on the server output at start and in the connection when a new connection is created.\n Typical custom header should be like: *** URBI version xx.xx for \<robotname\> robot\\n\n *** (c) Copyright \<year\> \<name\>\\n The function should return in header the line corresponding to 'line' or an empty string (not NULL!) when there is no line any more. Each line is supposed to end with a carriage return \\n and each line should start with three empty spaces. This complicated method is necessary to allow the connection to stamp every line with the standard URBI prefix [time:tag]. \param line is the requested line number \param header the custom header \param maxlength the maximum length allowed for the header (the parameter has been malloc'ed for that size). Typical size is 1024 octets and should be enough for any reasonable header. */ virtual void getCustomHeader (unsigned int line, char* header, size_t maxlength) = 0; /// Path to explore when looking for .u files. libport::file_library search_path; /// Return the full file name, handle paths. /// Return \a f on failure. virtual std::string find_file (const libport::path& path); /// Type of UCommandQueue enum QueueType { /// The UComandQueue contains URBI code. QUEUE_URBI, /// THe UCommandQueu contains data, not to be messed with. QUEUE_DATA }; /// Load a file into the connection. /// Returns UFAIL if anything goes wrong, USUCCESS otherwise. virtual UErrorValue load_file(const std::string& file_name, UQueue& loadQueue, QueueType t = QUEUE_URBI); /// Load \a fn in the ghostqueue. UErrorValue load_init_file(const char* fn); /// Save content to a file /// This function must be redefined by the robot-specific server. /// Returns UFAIL if anything goes wrong, USUCCESS otherwise. virtual UErrorValue save_file(const std::string& filename, const std::string& content) = 0; //! Overload this function to specify how your system will reboot virtual void reboot () = 0; //! Overload this function to specify how your system will shutdown virtual void shutdown (); //! Function called before work /*! Redefine this virtual function if you need to do pre-processing before the work function starts. */ virtual void beforeWork (); //! Function called after work /*! Redefine this virtual function if you need to do post-processing before the work function ends. */ virtual void afterWork (); /// Display a message on the robot console. void display (const char*); /// Display a set of messages on the robot console. void display (const char**); //! Accessor for lastTime_. libport::utime_t lastTime (); //! Update lastTime_ to current time. //! Update the server's time using the robot-specific implementation /*! It is necessary to have an update of the server time to increase the performance of successive calls to getTime. It allows also to see a whole processing session (like the processing of the command tree) as occuring AT the same time, from the server's point of view. */ void updateTime (); /*--------------. | Connections. | `--------------*/ /// Add a new connection to the connection list. /// Take ownership on c. Also perform some error testing on the connection /// value and UError return code /// \precondition c != 0 void connection_add(UConnection* c); /// Remove from connection_. /// Also perform some error testing on the connection /// value and UError return code /// Destroy \a c. void connection_remove(UConnection* c); /// \returns A usual connection to stop dependencies. /// (kernel/ghost-connection.hh is not public). UConnection& ghost_connection_get(); /*--------------------. | Scheduler, runner. | `--------------------*/ public: const scheduler::Scheduler& getScheduler () const; scheduler::Scheduler& getScheduler (); runner::Runner& getCurrentRunner () const; protected: //! Overload this function to specify how your robot is displaying messages. virtual void effectiveDisplay (const char*) = 0; private: // Pointer to stop the header dependency. scheduler::Scheduler* scheduler_; private: /// \{ Various parts of @c UServer::work. /// Scan currently opened connections for ongoing work void work_handle_connections_ (); /// Scan currently opened connections for deleting marked commands or /// killall order void work_handle_stopall_ (); void work_test_cpuoverload_ (); /// \} public: /// Shows debug or not. bool debugOutput; private: /// Name of the main device. std::string mainName_; public: /// Stops all commands in all connections. bool stopall; enum { /// Urbi TCP Port. TCP_PORT = 54000, }; private: /// Store the time on the last call to updateTime(). libport::utime_t lastTime_; /// List of active connections: includes one UGhostConnection. // FIXME: This is meant to become a runner::Job and move out of this class. /// A pointer to stop dependencies. std::auto_ptr<kernel::ConnectionSet> connections_; /// The ghost connection used for urbi.u, URBI.INI, etc. // Does not need to be an auto_ptr, as it is stored in connections_ // which handles memory management. UGhostConnection* ghost_; }; /*-------------------------. | Freestanding functions. | `-------------------------*/ /// Send debugging messages via ::urbiserver. void vdebug (const char* fmt, va_list args) __attribute__ ((__format__ (__printf__, 1, 0))); /// Send debugging messages via ::urbiserver. void debug (const char* fmt, ...) __attribute__ ((__format__ (__printf__, 1, 2))); // Send debugging messages. # if URBI_DEBUG // Must be invoked with two pairs of parens. # define DEBUG(Msg) debug Msg # else # define DEBUG(Msg) ((void) 0) # endif # include <kernel/userver.hxx> #endif // !KERNEL_USERVER_HH <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef CTRANS_HPP #define CTRANS_HPP #include <algorithm> #include <mapnik/box2d.hpp> #include <mapnik/vertex.hpp> #include <mapnik/coord_array.hpp> #include <mapnik/proj_transform.hpp> namespace mapnik { typedef coord_array<coord2d> CoordinateArray; template <typename Transform, typename Geometry> struct MAPNIK_DECL coord_transform { coord_transform(Transform const& t, Geometry& geom) : t_(t), geom_(geom) {} unsigned vertex(double *x, double *y) const { unsigned command = geom_.vertex(x, y); t_.forward(x, y); return command; } void rewind(unsigned pos) { geom_.rewind(pos); } private: Transform const& t_; Geometry& geom_; }; template <typename Transform, typename Geometry> struct MAPNIK_DECL coord_transform2 { typedef std::size_t size_type; typedef typename Geometry::value_type value_type; coord_transform2(Transform const& t, Geometry const& geom, proj_transform const& prj_trans) : t_(t), geom_(geom), prj_trans_(prj_trans) {} unsigned vertex(double *x, double *y) const { unsigned command = SEG_MOVETO; bool ok = false; bool skipped_points = false; double z = 0; while (!ok && command != SEG_END) { command = geom_.vertex(x, y); ok = prj_trans_.backward(*x, *y, z); if (!ok) { skipped_points = true; } } if (skipped_points && (command == SEG_LINETO)) { command = SEG_MOVETO; } t_.forward(x, y); return command; } void rewind(unsigned pos) { geom_.rewind(pos); } Geometry const& geom() const { return geom_; } private: Transform const& t_; Geometry const& geom_; proj_transform const& prj_trans_; }; template <typename Transform, typename Geometry> struct MAPNIK_DECL coord_transform3 { coord_transform3(Transform const& t, Geometry const& geom, proj_transform const& prj_trans, int dx, int dy) : t_(t), geom_(geom), prj_trans_(prj_trans), dx_(dx), dy_(dy) {} unsigned vertex(double *x, double *y) const { unsigned command = geom_.vertex(x, y); double z = 0; prj_trans_.backward(*x, *y, z); t_.forward(x, y); *x += dx_; *y += dy_; return command; } void rewind(unsigned pos) { geom_.rewind(pos); } private: Transform const& t_; Geometry const& geom_; proj_transform const& prj_trans_; int dx_; int dy_; }; class CoordTransform { private: int width_; int height_; double sx_; double sy_; box2d<double> extent_; double offset_x_; double offset_y_; public: CoordTransform(int width, int height, const box2d<double>& extent, double offset_x = 0, double offset_y = 0) : width_(width), height_(height), extent_(extent), offset_x_(offset_x), offset_y_(offset_y) { sx_ = double(width_) / extent_.width(); sy_ = double(height_) / extent_.height(); } inline int width() const { return width_; } inline int height() const { return height_; } inline double scale_x() const { return sx_; } inline double scale_y() const { return sy_; } inline void forward(double *x, double *y) const { *x = (*x - extent_.minx()) * sx_ - offset_x_; *y = (extent_.maxy() - *y) * sy_ - offset_y_; } inline void backward(double *x, double *y) const { *x = extent_.minx() + (*x + offset_x_) / sx_; *y = extent_.maxy() - (*y + offset_y_) / sy_; } inline coord2d& forward(coord2d& c) const { forward(&c.x, &c.y); return c; } inline coord2d& backward(coord2d& c) const { backward(&c.x, &c.y); return c; } inline box2d<double> forward(const box2d<double>& e, proj_transform const& prj_trans) const { double x0 = e.minx(); double y0 = e.miny(); double x1 = e.maxx(); double y1 = e.maxy(); double z = 0.0; prj_trans.backward(x0, y0, z); forward(&x0, &y0); prj_trans.backward(x1, y1, z); forward(&x1, &y1); return box2d<double>(x0, y0, x1, y1); } inline box2d<double> forward(const box2d<double>& e) const { double x0 = e.minx(); double y0 = e.miny(); double x1 = e.maxx(); double y1 = e.maxy(); forward(&x0, &y0); forward(&x1, &y1); return box2d<double>(x0, y0, x1, y1); } inline box2d<double> backward(const box2d<double>& e, proj_transform const& prj_trans) const { double x0 = e.minx(); double y0 = e.miny(); double x1 = e.maxx(); double y1 = e.maxy(); double z = 0.0; backward(&x0, &y0); prj_trans.forward(x0, y0, z); backward(&x1, &y1); prj_trans.forward(x1, y1, z); return box2d<double>(x0, y0, x1, y1); } inline box2d<double> backward(const box2d<double>& e) const { double x0 = e.minx(); double y0 = e.miny(); double x1 = e.maxx(); double y1 = e.maxy(); backward(&x0, &y0); backward(&x1, &y1); return box2d<double>(x0, y0, x1, y1); } inline CoordinateArray& forward(CoordinateArray& coords) const { for (unsigned i = 0; i < coords.size(); ++i) { forward(coords[i]); } return coords; } inline CoordinateArray& backward(CoordinateArray& coords) const { for (unsigned i = 0; i < coords.size(); ++i) { backward(coords[i]); } return coords; } inline box2d<double> const& extent() const { return extent_; } }; } #endif //CTRANS_HPP <commit_msg>use static_cast<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef CTRANS_HPP #define CTRANS_HPP #include <algorithm> #include <mapnik/box2d.hpp> #include <mapnik/vertex.hpp> #include <mapnik/coord_array.hpp> #include <mapnik/proj_transform.hpp> namespace mapnik { typedef coord_array<coord2d> CoordinateArray; template <typename Transform, typename Geometry> struct MAPNIK_DECL coord_transform { coord_transform(Transform const& t, Geometry& geom) : t_(t), geom_(geom) {} unsigned vertex(double *x, double *y) const { unsigned command = geom_.vertex(x, y); t_.forward(x, y); return command; } void rewind(unsigned pos) { geom_.rewind(pos); } private: Transform const& t_; Geometry& geom_; }; template <typename Transform, typename Geometry> struct MAPNIK_DECL coord_transform2 { typedef std::size_t size_type; typedef typename Geometry::value_type value_type; coord_transform2(Transform const& t, Geometry const& geom, proj_transform const& prj_trans) : t_(t), geom_(geom), prj_trans_(prj_trans) {} unsigned vertex(double *x, double *y) const { unsigned command = SEG_MOVETO; bool ok = false; bool skipped_points = false; double z = 0; while (!ok && command != SEG_END) { command = geom_.vertex(x, y); ok = prj_trans_.backward(*x, *y, z); if (!ok) { skipped_points = true; } } if (skipped_points && (command == SEG_LINETO)) { command = SEG_MOVETO; } t_.forward(x, y); return command; } void rewind(unsigned pos) { geom_.rewind(pos); } Geometry const& geom() const { return geom_; } private: Transform const& t_; Geometry const& geom_; proj_transform const& prj_trans_; }; template <typename Transform, typename Geometry> struct MAPNIK_DECL coord_transform3 { coord_transform3(Transform const& t, Geometry const& geom, proj_transform const& prj_trans, int dx, int dy) : t_(t), geom_(geom), prj_trans_(prj_trans), dx_(dx), dy_(dy) {} unsigned vertex(double *x, double *y) const { unsigned command = geom_.vertex(x, y); double z = 0; prj_trans_.backward(*x, *y, z); t_.forward(x, y); *x += dx_; *y += dy_; return command; } void rewind(unsigned pos) { geom_.rewind(pos); } private: Transform const& t_; Geometry const& geom_; proj_transform const& prj_trans_; int dx_; int dy_; }; class CoordTransform { private: int width_; int height_; double sx_; double sy_; box2d<double> extent_; double offset_x_; double offset_y_; public: CoordTransform(int width, int height, const box2d<double>& extent, double offset_x = 0, double offset_y = 0) : width_(width), height_(height), extent_(extent), offset_x_(offset_x), offset_y_(offset_y) { sx_ = static_cast<double>(width_) / extent_.width(); sy_ = static_cast<double>(height_) / extent_.height(); } inline int width() const { return width_; } inline int height() const { return height_; } inline double scale_x() const { return sx_; } inline double scale_y() const { return sy_; } inline void forward(double *x, double *y) const { *x = (*x - extent_.minx()) * sx_ - offset_x_; *y = (extent_.maxy() - *y) * sy_ - offset_y_; } inline void backward(double *x, double *y) const { *x = extent_.minx() + (*x + offset_x_) / sx_; *y = extent_.maxy() - (*y + offset_y_) / sy_; } inline coord2d& forward(coord2d& c) const { forward(&c.x, &c.y); return c; } inline coord2d& backward(coord2d& c) const { backward(&c.x, &c.y); return c; } inline box2d<double> forward(const box2d<double>& e, proj_transform const& prj_trans) const { double x0 = e.minx(); double y0 = e.miny(); double x1 = e.maxx(); double y1 = e.maxy(); double z = 0.0; prj_trans.backward(x0, y0, z); forward(&x0, &y0); prj_trans.backward(x1, y1, z); forward(&x1, &y1); return box2d<double>(x0, y0, x1, y1); } inline box2d<double> forward(const box2d<double>& e) const { double x0 = e.minx(); double y0 = e.miny(); double x1 = e.maxx(); double y1 = e.maxy(); forward(&x0, &y0); forward(&x1, &y1); return box2d<double>(x0, y0, x1, y1); } inline box2d<double> backward(const box2d<double>& e, proj_transform const& prj_trans) const { double x0 = e.minx(); double y0 = e.miny(); double x1 = e.maxx(); double y1 = e.maxy(); double z = 0.0; backward(&x0, &y0); prj_trans.forward(x0, y0, z); backward(&x1, &y1); prj_trans.forward(x1, y1, z); return box2d<double>(x0, y0, x1, y1); } inline box2d<double> backward(const box2d<double>& e) const { double x0 = e.minx(); double y0 = e.miny(); double x1 = e.maxx(); double y1 = e.maxy(); backward(&x0, &y0); backward(&x1, &y1); return box2d<double>(x0, y0, x1, y1); } inline CoordinateArray& forward(CoordinateArray& coords) const { for (unsigned i = 0; i < coords.size(); ++i) { forward(coords[i]); } return coords; } inline CoordinateArray& backward(CoordinateArray& coords) const { for (unsigned i = 0; i < coords.size(); ++i) { backward(coords[i]); } return coords; } inline box2d<double> const& extent() const { return extent_; } }; } #endif //CTRANS_HPP <|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QITYPE_DETAILS_FUNCTIONTYPE_HXX_ #define _QITYPE_DETAILS_FUNCTIONTYPE_HXX_ #include <qitype/genericvalue.hpp> #include <qitype/details/bindtype.hxx> namespace qi { inline CallableType::CallableType() : _resultType(0) { } inline Type* CallableType::resultType() { return _resultType; } inline const std::vector<Type*>& CallableType::argumentsType() { return _argumentsType; } inline GenericValuePtr GenericFunction::operator()(const std::vector<GenericValuePtr>& args) { return call(args); } inline GenericFunction::GenericFunction() : type(0), value(0) {} inline GenericFunction::GenericFunction(const GenericFunction& b) { type = b.type; value = type?type->clone(b.value):0; } inline GenericFunction& GenericFunction::operator=(const GenericFunction& b) { this->~GenericFunction(); type = b.type; value = type?type->clone(b.value):0; return *this; } inline GenericFunction::~GenericFunction() { if (type) type->destroy(value); } inline GenericValuePtr GenericFunction::call(const std::vector<GenericValuePtr>& args) { return type->call(value, args); } } // namespace qi #endif // _QITYPE_DETAILS_FUNCTIONTYPE_HXX_ <commit_msg>Implement std::swap on GenericFunction.<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QITYPE_DETAILS_FUNCTIONTYPE_HXX_ #define _QITYPE_DETAILS_FUNCTIONTYPE_HXX_ #include <qitype/genericvalue.hpp> #include <qitype/details/bindtype.hxx> namespace qi { inline CallableType::CallableType() : _resultType(0) { } inline Type* CallableType::resultType() { return _resultType; } inline const std::vector<Type*>& CallableType::argumentsType() { return _argumentsType; } inline GenericValuePtr GenericFunction::operator()(const std::vector<GenericValuePtr>& args) { return call(args); } inline GenericFunction::GenericFunction() : type(0), value(0) {} inline GenericFunction::GenericFunction(const GenericFunction& b) { type = b.type; value = type?type->clone(b.value):0; } inline GenericFunction& GenericFunction::operator=(const GenericFunction& b) { this->~GenericFunction(); type = b.type; value = type?type->clone(b.value):0; return *this; } inline GenericFunction::~GenericFunction() { if (type) type->destroy(value); } inline GenericValuePtr GenericFunction::call(const std::vector<GenericValuePtr>& args) { return type->call(value, args); } } // namespace qi namespace std { template<> inline void swap(::qi::GenericFunction& a, ::qi::GenericFunction & b) { swap(a.value, b.value); swap(a.type, b.type); } } #endif // _QITYPE_DETAILS_FUNCTIONTYPE_HXX_ <|endoftext|>
<commit_before>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org> * http://www.berlin-consortium.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #include <fcntl.h> using namespace Prague; extern char *ptsname(int); /* prototype not in any system header */ extern int grantpt(int); extern int unlockpt(int); int ptybuf::openpty() { char *ptr; ptydev = "/dev/ptmx"; /* in case open fails */ int fdm = open(ptydev.c_str(), O_RDWR); if (fdm < 0) return -1; if (grantpt(fdm) < 0) /* grant access to slave */ { close(fdm); return -2; } if (unlockpt(fdm) < 0) /* clear slave's lock flag */ { close(fdm); return -3; } if ((ptr = ptsname(fdm)) == 0) /* get slave's name */ { close(fdm); return -4; } ptydev = ptr; /* return name of slave */ data->fd = fdm; return fdm; /* return fd of master */ } int ptybuf::opentty() { int fds; /* following should allocate controlling terminal */ if ((fds = open(ptydev.c_str(), O_RDWR)) < 0) { close(fd()); return(-5); } /* if (ioctl(fds, I_PUSH, "ptem") < 0) { close(fd()); close(fds); return(-6); } if (ioctl(fds, I_PUSH, "ldterm") < 0) { close(fd()); close(fds); return(-7); } if (ioctl(fds, I_PUSH, "ttcompat") < 0) { close(fd()); close(fds); return(-8); } */ return(fds); } <commit_msg>fix a bug to make it compile on solaris<commit_after>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org> * http://www.berlin-consortium.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #include <fcntl.h> using namespace Prague; extern char *ptsname(int); /* prototype not in any system header */ extern int grantpt(int); extern int unlockpt(int); int ptybuf::openpty() { char *ptr; ptydev = "/dev/ptmx"; /* in case open fails */ int fdm = open(ptydev.c_str(), O_RDWR); if (fdm < 0) return -1; if (grantpt(fdm) < 0) /* grant access to slave */ { close(fdm); return -2; } if (unlockpt(fdm) < 0) /* clear slave's lock flag */ { close(fdm); return -3; } if ((ptr = ptsname(fdm)) == 0) /* get slave's name */ { close(fdm); return -4; } ptydev = ptr; /* return name of slave */ fd(fdm); return fdm; /* return fd of master */ } int ptybuf::opentty() { int fds; /* following should allocate controlling terminal */ if ((fds = open(ptydev.c_str(), O_RDWR)) < 0) { close(fd()); return(-5); } /* if (ioctl(fds, I_PUSH, "ptem") < 0) { close(fd()); close(fds); return(-6); } if (ioctl(fds, I_PUSH, "ldterm") < 0) { close(fd()); close(fds); return(-7); } if (ioctl(fds, I_PUSH, "ttcompat") < 0) { close(fd()); close(fds); return(-8); } */ return(fds); } <|endoftext|>
<commit_before> #include <map.hpp> #include <datasource_cache.hpp> #include <font_engine_freetype.hpp> #include <agg_renderer.hpp> #include <filter_factory.hpp> #include <color_factory.hpp> #include <image_util.hpp> #include <iostream> using namespace mapnik; int main ( int argc , char** argv) { if (argc != 2) { std::cout << "usage: ./rundemo <plugins_dir>\n"; return EXIT_SUCCESS; } std::cout << " running demo ... \n"; datasource_cache::instance()->register_datasources(argv[1]); freetype_engine::instance()->register_font("/usr/share/fonts/bitstream-vera/Vera.ttf"); Map m(800,600); m.setBackground(color_factory::from_string("white")); // create styles // Provinces (polygon) feature_type_style provpoly_style; rule_type provpoly_rule_on; provpoly_rule_on.set_filter(create_filter("[NAME_EN] = 'Ontario'")); provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183))); provpoly_style.add_rule(provpoly_rule_on); rule_type provpoly_rule_qc; provpoly_rule_qc.set_filter(create_filter("[NAME_EN] = 'Quebec'")); provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203))); provpoly_style.add_rule(provpoly_rule_qc); m.insert_style("provinces",provpoly_style); // Provinces (polyline) feature_type_style provlines_style; stroke provlines_stk (Color(0,0,0),1.0); provlines_stk.add_dash(8, 4); provlines_stk.add_dash(2, 2); provlines_stk.add_dash(2, 2); rule_type provlines_rule; provlines_rule.append(line_symbolizer(provlines_stk)); provlines_style.add_rule(provlines_rule); m.insert_style("provlines",provlines_style); // Drainage feature_type_style qcdrain_style; rule_type qcdrain_rule; qcdrain_rule.set_filter(create_filter("[HYC] = 8")); qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255))); qcdrain_style.add_rule(qcdrain_rule); m.insert_style("drainage",qcdrain_style); // Roads 3 and 4 (The "grey" roads) feature_type_style roads34_style; rule_type roads34_rule; roads34_rule.set_filter(create_filter("[CLASS] = 3 or [CLASS] = 4")); stroke roads34_rule_stk(Color(171,158,137),2.0); roads34_rule_stk.set_line_cap(ROUND_CAP); roads34_rule_stk.set_line_join(ROUND_JOIN); roads34_rule.append(line_symbolizer(roads34_rule_stk)); roads34_style.add_rule(roads34_rule); m.insert_style("smallroads",roads34_style); // Roads 2 (The thin yellow ones) feature_type_style roads2_style_1; rule_type roads2_rule_1; roads2_rule_1.set_filter(create_filter("[CLASS] = 2")); stroke roads2_rule_stk_1(Color(171,158,137),4.0); roads2_rule_stk_1.set_line_cap(ROUND_CAP); roads2_rule_stk_1.set_line_join(ROUND_JOIN); roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1)); roads2_style_1.add_rule(roads2_rule_1); m.insert_style("road-border", roads2_style_1); feature_type_style roads2_style_2; rule_type roads2_rule_2; roads2_rule_2.set_filter(create_filter("[CLASS] = 2")); stroke roads2_rule_stk_2(Color(255,250,115),2.0); roads2_rule_stk_2.set_line_cap(ROUND_CAP); roads2_rule_stk_2.set_line_join(ROUND_JOIN); roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2)); roads2_style_2.add_rule(roads2_rule_2); m.insert_style("road-fill", roads2_style_2); // Roads 1 (The big orange ones, the highways) feature_type_style roads1_style_1; rule_type roads1_rule_1; roads1_rule_1.set_filter(create_filter("[CLASS] = 1")); stroke roads1_rule_stk_1(Color(188,149,28),7.0); roads1_rule_stk_1.set_line_cap(ROUND_CAP); roads1_rule_stk_1.set_line_join(ROUND_JOIN); roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1)); roads1_style_1.add_rule(roads1_rule_1); m.insert_style("highway-border", roads1_style_1); feature_type_style roads1_style_2; rule_type roads1_rule_2; roads1_rule_2.set_filter(create_filter("[CLASS] = 1")); stroke roads1_rule_stk_2(Color(242,191,36),5.0); roads1_rule_stk_2.set_line_cap(ROUND_CAP); roads1_rule_stk_2.set_line_join(ROUND_JOIN); roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2)); roads1_style_2.add_rule(roads1_rule_2); m.insert_style("highway-fill", roads1_style_2); // Populated Places feature_type_style popplaces_style; rule_type popplaces_rule; text_symbolizer popplaces_text_symbolizer("GEONAME",10,Color(0,0,0)); popplaces_text_symbolizer.set_halo_fill(Color(255,255,200)); popplaces_text_symbolizer.set_halo_radius(1); popplaces_rule.append(popplaces_text_symbolizer); popplaces_style.add_rule(popplaces_rule); m.insert_style("popplaces",popplaces_style ); // Layers // Provincial polygons { parameters p; p["type"]="shape"; p["file"]="../data/boundaries"; Layer lyr("Provinces"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provinces"); m.addLayer(lyr); } // Drainage { parameters p; p["type"]="shape"; p["file"]="../data/qcdrainage"; Layer lyr("Quebec Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } { parameters p; p["type"]="shape"; p["file"]="../data/ontdrainage"; Layer lyr("Ontario Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } // Provincial boundaries { parameters p; p["type"]="shape"; p["file"]="../data/boundaries_l"; Layer lyr("Provincial borders"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provlines"); m.addLayer(lyr); } // Roads { parameters p; p["type"]="shape"; p["file"]="../data/roads"; Layer lyr("Roads"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("smallroads"); lyr.add_style("road-border"); lyr.add_style("road-fill"); lyr.add_style("highway-border"); lyr.add_style("highway-fill"); m.addLayer(lyr); } // popplaces { parameters p; p["type"]="shape"; p["file"]="../data/popplaces"; Layer lyr("Populated Places"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("popplaces"); m.addLayer(lyr); } m.zoomToBox(Envelope<double>(1405120.04127408,-247003.813399447,1706357.31328276,-25098.593149577)); Image32 buf(m.getWidth(),m.getHeight()); agg_renderer<Image32> ren(m,buf); ren.apply(); ImageUtils::save_to_file("demo.jpg","jpeg",buf); ImageUtils::save_to_file("demo.png","png",buf); std::cout << "Two maps have been rendered in the current directory:\n" "- demo.jpg\n" "- demo.png\n" "Have a look!\n"; return EXIT_SUCCESS; } <commit_msg>added copyleft header<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // $Id$ #include <map.hpp> #include <datasource_cache.hpp> #include <font_engine_freetype.hpp> #include <agg_renderer.hpp> #include <filter_factory.hpp> #include <color_factory.hpp> #include <image_util.hpp> #include <iostream> using namespace mapnik; int main ( int argc , char** argv) { if (argc != 2) { std::cout << "usage: ./rundemo <plugins_dir>\n"; return EXIT_SUCCESS; } std::cout << " running demo ... \n"; datasource_cache::instance()->register_datasources(argv[1]); freetype_engine::instance()->register_font("/usr/share/fonts/bitstream-vera/Vera.ttf"); Map m(800,600); m.setBackground(color_factory::from_string("white")); // create styles // Provinces (polygon) feature_type_style provpoly_style; rule_type provpoly_rule_on; provpoly_rule_on.set_filter(create_filter("[NAME_EN] = 'Ontario'")); provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183))); provpoly_style.add_rule(provpoly_rule_on); rule_type provpoly_rule_qc; provpoly_rule_qc.set_filter(create_filter("[NAME_EN] = 'Quebec'")); provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203))); provpoly_style.add_rule(provpoly_rule_qc); m.insert_style("provinces",provpoly_style); // Provinces (polyline) feature_type_style provlines_style; stroke provlines_stk (Color(0,0,0),1.0); provlines_stk.add_dash(8, 4); provlines_stk.add_dash(2, 2); provlines_stk.add_dash(2, 2); rule_type provlines_rule; provlines_rule.append(line_symbolizer(provlines_stk)); provlines_style.add_rule(provlines_rule); m.insert_style("provlines",provlines_style); // Drainage feature_type_style qcdrain_style; rule_type qcdrain_rule; qcdrain_rule.set_filter(create_filter("[HYC] = 8")); qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255))); qcdrain_style.add_rule(qcdrain_rule); m.insert_style("drainage",qcdrain_style); // Roads 3 and 4 (The "grey" roads) feature_type_style roads34_style; rule_type roads34_rule; roads34_rule.set_filter(create_filter("[CLASS] = 3 or [CLASS] = 4")); stroke roads34_rule_stk(Color(171,158,137),2.0); roads34_rule_stk.set_line_cap(ROUND_CAP); roads34_rule_stk.set_line_join(ROUND_JOIN); roads34_rule.append(line_symbolizer(roads34_rule_stk)); roads34_style.add_rule(roads34_rule); m.insert_style("smallroads",roads34_style); // Roads 2 (The thin yellow ones) feature_type_style roads2_style_1; rule_type roads2_rule_1; roads2_rule_1.set_filter(create_filter("[CLASS] = 2")); stroke roads2_rule_stk_1(Color(171,158,137),4.0); roads2_rule_stk_1.set_line_cap(ROUND_CAP); roads2_rule_stk_1.set_line_join(ROUND_JOIN); roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1)); roads2_style_1.add_rule(roads2_rule_1); m.insert_style("road-border", roads2_style_1); feature_type_style roads2_style_2; rule_type roads2_rule_2; roads2_rule_2.set_filter(create_filter("[CLASS] = 2")); stroke roads2_rule_stk_2(Color(255,250,115),2.0); roads2_rule_stk_2.set_line_cap(ROUND_CAP); roads2_rule_stk_2.set_line_join(ROUND_JOIN); roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2)); roads2_style_2.add_rule(roads2_rule_2); m.insert_style("road-fill", roads2_style_2); // Roads 1 (The big orange ones, the highways) feature_type_style roads1_style_1; rule_type roads1_rule_1; roads1_rule_1.set_filter(create_filter("[CLASS] = 1")); stroke roads1_rule_stk_1(Color(188,149,28),7.0); roads1_rule_stk_1.set_line_cap(ROUND_CAP); roads1_rule_stk_1.set_line_join(ROUND_JOIN); roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1)); roads1_style_1.add_rule(roads1_rule_1); m.insert_style("highway-border", roads1_style_1); feature_type_style roads1_style_2; rule_type roads1_rule_2; roads1_rule_2.set_filter(create_filter("[CLASS] = 1")); stroke roads1_rule_stk_2(Color(242,191,36),5.0); roads1_rule_stk_2.set_line_cap(ROUND_CAP); roads1_rule_stk_2.set_line_join(ROUND_JOIN); roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2)); roads1_style_2.add_rule(roads1_rule_2); m.insert_style("highway-fill", roads1_style_2); // Populated Places feature_type_style popplaces_style; rule_type popplaces_rule; text_symbolizer popplaces_text_symbolizer("GEONAME",10,Color(0,0,0)); popplaces_text_symbolizer.set_halo_fill(Color(255,255,200)); popplaces_text_symbolizer.set_halo_radius(1); popplaces_rule.append(popplaces_text_symbolizer); popplaces_style.add_rule(popplaces_rule); m.insert_style("popplaces",popplaces_style ); // Layers // Provincial polygons { parameters p; p["type"]="shape"; p["file"]="../data/boundaries"; Layer lyr("Provinces"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provinces"); m.addLayer(lyr); } // Drainage { parameters p; p["type"]="shape"; p["file"]="../data/qcdrainage"; Layer lyr("Quebec Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } { parameters p; p["type"]="shape"; p["file"]="../data/ontdrainage"; Layer lyr("Ontario Hydrography"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("drainage"); m.addLayer(lyr); } // Provincial boundaries { parameters p; p["type"]="shape"; p["file"]="../data/boundaries_l"; Layer lyr("Provincial borders"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("provlines"); m.addLayer(lyr); } // Roads { parameters p; p["type"]="shape"; p["file"]="../data/roads"; Layer lyr("Roads"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("smallroads"); lyr.add_style("road-border"); lyr.add_style("road-fill"); lyr.add_style("highway-border"); lyr.add_style("highway-fill"); m.addLayer(lyr); } // popplaces { parameters p; p["type"]="shape"; p["file"]="../data/popplaces"; Layer lyr("Populated Places"); lyr.set_datasource(datasource_cache::instance()->create(p)); lyr.add_style("popplaces"); m.addLayer(lyr); } m.zoomToBox(Envelope<double>(1405120.04127408,-247003.813399447,1706357.31328276,-25098.593149577)); Image32 buf(m.getWidth(),m.getHeight()); agg_renderer<Image32> ren(m,buf); ren.apply(); ImageUtils::save_to_file("demo.jpg","jpeg",buf); ImageUtils::save_to_file("demo.png","png",buf); std::cout << "Two maps have been rendered in the current directory:\n" "- demo.jpg\n" "- demo.png\n" "Have a look!\n"; return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include <iostream> #include "drake/systems/LCMSystem.h" #include "drake/systems/LinearSystem.h" #include "drake/systems/cascade_system.h" #include "drake/systems/plants/BotVisualizer.h" #include "drake/systems/plants/RigidBodySystem.h" #include "QuadrotorInput.h" #include "QuadrotorOutput.h" using namespace std; using namespace Drake; using namespace Eigen; int main(int argc, char* argv[]) { const size_t num_lidar_points = 100; SimulationOptions options = default_simulation_options; options.realtime_factor = 1.0; options.initial_step_size = 0.01; // Get the final time of the simulation. double final_time = argc >= 2 ? atof(argv[1]) : std::numeric_limits<double>::infinity(); // Get the simulation's maximum acceptable delay in seconds. if (argc >= 3) { options.timeout_seconds = atof(argv[2]); } // Determine whether a warning should be printed or an exception should be // thrown if the simulation is delayed by more than the timeout threshold. if (argc >= 4) { options.warn_real_time_violation = (std::string(argv[3]).compare("warn") == 0); } cout << "Running simulation for " << final_time << " seconds with a maximum real-time delay of " << options.timeout_seconds << " seconds. Will " << (options.warn_real_time_violation ? "print warning" : "throw exception") << " if real-time max-delay is violated." << endl; shared_ptr<lcm::LCM> lcm = make_shared<lcm::LCM>(); if (!lcm->good()) return 1; DrakeJoint::FloatingBaseType floating_base_type = DrakeJoint::QUATERNION; auto rigid_body_sys = make_shared<RigidBodySystem>(); rigid_body_sys->addRobotFromFile( getDrakePath() + "/examples/Quadrotor/warehouse.sdf", floating_base_type); rigid_body_sys->penetration_stiffness = 20.0; rigid_body_sys->penetration_damping = 2.0; auto const& tree = rigid_body_sys->getRigidBodyTree(); rigid_body_sys->addRobotFromFile( getDrakePath() + "/examples/Quadrotor/quadrotor_fla.urdf", floating_base_type); auto sensor_frame = tree->findFrame("body"); auto accelerometer = make_shared<RigidBodyAccelerometer>( *rigid_body_sys, "accelerometer", sensor_frame); auto lidar2D = make_shared<RigidBodyDepthSensor>( *rigid_body_sys, "lidar2D", tree->findFrame("laser"), num_lidar_points, -3 * M_PI / 4, 3 * M_PI / 4, 30.0); auto gyroscope = make_shared<RigidBodyGyroscope>(*rigid_body_sys, "gyroscope", sensor_frame); auto magnetometer = make_shared<RigidBodyMagnetometer>( *rigid_body_sys, "magnetometer", sensor_frame, 0.0); auto rangefinder = make_shared<RigidBodyDepthSensor>( *rigid_body_sys, "rangefinder", tree->findFrame("rangefinder"), 1, 0, 0, 40.0); auto noise_model = make_shared<AdditiveGaussianNoiseModel<double, 3, Vector3d>>(0, 0.01); accelerometer->setNoiseModel(noise_model); accelerometer->setGravityCompensation(true); gyroscope->setNoiseModel(noise_model); magnetometer->setNoiseModel(noise_model); rigid_body_sys->addSensor(accelerometer); rigid_body_sys->addSensor(gyroscope); rigid_body_sys->addSensor(magnetometer); rigid_body_sys->addSensor(lidar2D); rigid_body_sys->addSensor(rangefinder); double box_width = 1000; double box_depth = 10; DrakeShapes::Box geom(Vector3d(box_width, box_width, box_depth)); Isometry3d T_element_to_link = Isometry3d::Identity(); T_element_to_link.translation() << 0, 0, -box_depth / 2; // top of the box is at z=0 auto& world = tree->bodies[0]; Vector4d color; color << 0.9297, 0.7930, 0.6758, 1; // was hex2dec({'ee','cb','ad'})'/256 in matlab world->addVisualElement( DrakeShapes::VisualElement(geom, T_element_to_link, color)); tree->addCollisionElement( RigidBody::CollisionElement(geom, T_element_to_link, world), *world, "terrain"); tree->updateStaticCollisionElements(); auto visualizer = make_shared<BotVisualizer<RigidBodySystem::StateVector>>(lcm, tree); auto quad_control_to_rbsys_input = make_shared<Gain<QuadrotorInput, RigidBodySystem::InputVector>>( Eigen::Matrix4d::Identity()); auto rbsys_output_to_quad_state = make_shared<Gain<RigidBodySystem::StateVector, QuadrotorOutput>>( Eigen::Matrix<double, 22 + num_lidar_points + 1, 22 + num_lidar_points + 1>::Identity()); auto sys_with_lcm_input = cascade(quad_control_to_rbsys_input, rigid_body_sys); auto sys_with_vis = cascade(sys_with_lcm_input, visualizer); VectorXd x0 = VectorXd::Zero(rigid_body_sys->getNumStates()); x0.head(tree->num_positions) = tree->getZeroConfiguration(); auto lcmio_with_vis = cascade(sys_with_vis, rbsys_output_to_quad_state); x0(0) = 0; x0(2) = 0.2; // x0(9) = 0.5; //yaw rate // x0(12) = 0.05; //Z dot runLCM(lcmio_with_vis, lcm, 0, final_time, x0, options); } <commit_msg>Removed redundant initialization of simulation options.<commit_after> #include <iostream> #include "drake/systems/LCMSystem.h" #include "drake/systems/LinearSystem.h" #include "drake/systems/cascade_system.h" #include "drake/systems/plants/BotVisualizer.h" #include "drake/systems/plants/RigidBodySystem.h" #include "QuadrotorInput.h" #include "QuadrotorOutput.h" using namespace std; using namespace Drake; using namespace Eigen; int main(int argc, char* argv[]) { const size_t num_lidar_points = 100; SimulationOptions options; // Get the final time of the simulation. double final_time = argc >= 2 ? atof(argv[1]) : std::numeric_limits<double>::infinity(); // Get the simulation's maximum acceptable delay in seconds. if (argc >= 3) { options.timeout_seconds = atof(argv[2]); } // Determine whether a warning should be printed or an exception should be // thrown if the simulation is delayed by more than the timeout threshold. if (argc >= 4) { options.warn_real_time_violation = (std::string(argv[3]).compare("warn") == 0); } cout << "Running simulation for " << final_time << " seconds with a maximum real-time delay of " << options.timeout_seconds << " seconds. Will " << (options.warn_real_time_violation ? "print warning" : "throw exception") << " if real-time max-delay is violated." << endl; shared_ptr<lcm::LCM> lcm = make_shared<lcm::LCM>(); if (!lcm->good()) return 1; DrakeJoint::FloatingBaseType floating_base_type = DrakeJoint::QUATERNION; auto rigid_body_sys = make_shared<RigidBodySystem>(); rigid_body_sys->addRobotFromFile( getDrakePath() + "/examples/Quadrotor/warehouse.sdf", floating_base_type); rigid_body_sys->penetration_stiffness = 20.0; rigid_body_sys->penetration_damping = 2.0; auto const& tree = rigid_body_sys->getRigidBodyTree(); rigid_body_sys->addRobotFromFile( getDrakePath() + "/examples/Quadrotor/quadrotor_fla.urdf", floating_base_type); auto sensor_frame = tree->findFrame("body"); auto accelerometer = make_shared<RigidBodyAccelerometer>( *rigid_body_sys, "accelerometer", sensor_frame); auto lidar2D = make_shared<RigidBodyDepthSensor>( *rigid_body_sys, "lidar2D", tree->findFrame("laser"), num_lidar_points, -3 * M_PI / 4, 3 * M_PI / 4, 30.0); auto gyroscope = make_shared<RigidBodyGyroscope>(*rigid_body_sys, "gyroscope", sensor_frame); auto magnetometer = make_shared<RigidBodyMagnetometer>( *rigid_body_sys, "magnetometer", sensor_frame, 0.0); auto rangefinder = make_shared<RigidBodyDepthSensor>( *rigid_body_sys, "rangefinder", tree->findFrame("rangefinder"), 1, 0, 0, 40.0); auto noise_model = make_shared<AdditiveGaussianNoiseModel<double, 3, Vector3d>>(0, 0.01); accelerometer->setNoiseModel(noise_model); accelerometer->setGravityCompensation(true); gyroscope->setNoiseModel(noise_model); magnetometer->setNoiseModel(noise_model); rigid_body_sys->addSensor(accelerometer); rigid_body_sys->addSensor(gyroscope); rigid_body_sys->addSensor(magnetometer); rigid_body_sys->addSensor(lidar2D); rigid_body_sys->addSensor(rangefinder); double box_width = 1000; double box_depth = 10; DrakeShapes::Box geom(Vector3d(box_width, box_width, box_depth)); Isometry3d T_element_to_link = Isometry3d::Identity(); T_element_to_link.translation() << 0, 0, -box_depth / 2; // top of the box is at z=0 auto& world = tree->bodies[0]; Vector4d color; color << 0.9297, 0.7930, 0.6758, 1; // was hex2dec({'ee','cb','ad'})'/256 in matlab world->addVisualElement( DrakeShapes::VisualElement(geom, T_element_to_link, color)); tree->addCollisionElement( RigidBody::CollisionElement(geom, T_element_to_link, world), *world, "terrain"); tree->updateStaticCollisionElements(); auto visualizer = make_shared<BotVisualizer<RigidBodySystem::StateVector>>(lcm, tree); auto quad_control_to_rbsys_input = make_shared<Gain<QuadrotorInput, RigidBodySystem::InputVector>>( Eigen::Matrix4d::Identity()); auto rbsys_output_to_quad_state = make_shared<Gain<RigidBodySystem::StateVector, QuadrotorOutput>>( Eigen::Matrix<double, 22 + num_lidar_points + 1, 22 + num_lidar_points + 1>::Identity()); auto sys_with_lcm_input = cascade(quad_control_to_rbsys_input, rigid_body_sys); auto sys_with_vis = cascade(sys_with_lcm_input, visualizer); VectorXd x0 = VectorXd::Zero(rigid_body_sys->getNumStates()); x0.head(tree->num_positions) = tree->getZeroConfiguration(); auto lcmio_with_vis = cascade(sys_with_vis, rbsys_output_to_quad_state); x0(0) = 0; x0(2) = 0.2; // x0(9) = 0.5; //yaw rate // x0(12) = 0.05; //Z dot runLCM(lcmio_with_vis, lcm, 0, final_time, x0, options); } <|endoftext|>
<commit_before>namespace W { template <typename T> class Bind : public Thing { public: }; class Result : public Thing { }; class Thing { public: virtual const Result& release(); virtual Bind<Thing> clone() = 0; }; class Container : public Thing { public: }; template <typename T> class Array : public Container { }; class Members : public Array<Node> { public: }; class Node : public Thing { public: virtual Bind<Node> call(const String& msg, Array<Argument> args) { } virtual Members& getMembers() = 0; }; class Message : public Thing { }; class Method : public Node { public: virtual Bind<Node>& call(const Message& msg) { } virtual Node& call(const Arguments& args) = 0; }; class Class : public Node { public: virtual const String& getName() const = 0; virtual const Array<Class>& getSupers() const = 0; virtual const Array<Class>& getSubs() const = 0; virtual Members& getMembers() { return _members; } Members& getMethods() { return _methods; } Members& getVariables() { return _variables; } Object incarnate() const {// World 객체를 만드는 것이다. return Object(*this); } virtual Bind<Node> call(const String& msg, Array<Argument> args) { } // Class의 각 _variables는 부모의 _variables를 clone() 한 뒤, 자기만의 심볼을 뒤에 push 한 것이다. // " _methods 동일. _members는 자연스럽게 이게 된 상태. // ! 논리적으로 _members 안에는 중복 이름이 있어서는 안된다. Members _variables; Members _methods; Chain<Node> _members; }; template <typename T> class Classer : public Class { // TClasser는 World에 visible 하지 않다: // visible하다는 것은 논리적으로는 "World에서 접근 가능함" 이라는 뜻이며, // 물리적으로는 "파싱테이블에 매핑되어있어서 Txt가 적절한 객체로 생성될 수 있음" 이라는 뜻이다. // C++안에서만 Classer<T>를 사용할 수 있다. public: }; class WorldClass : public Class { public: }; // Object는 World의 객체다. 객체는 항상 객체라는 타입이다. A라는 클래스의 객체와 B라는 클래스의 객체는 Native적으로, // 동일한 클래스의 객체다. 바로 이부분이 헷갈리기 쉬운 부분이며 동시에 World의 재사용성을 높여주는 부분이기도 하다. class Object : public Node { public: Object(Class& klass) { _class = klass; _variables = klass.getVariables(); _members.chain(klass.getMethods()); _members.chain(_variables); } Members& getMembers() { return _members; } Members& getVariables() { return _variables; } private: Weak<Class> _class; // 이게 뭘 가리키느냐에 따라서, 어떠한 World 객체인가가 결정되는 것이다. Members _variables; Chain<Node> _members; }; class MyFirstWorldModule : public Object { static const Result& _onInitializeMethods(List<Methods> tray) { W_DECL_FUNC(String& addString(String& arg1, String/*by val is ok.*/ arg2)) // RETURN_T=String& is by-ref and sharable. /* So, Above macro will expand like this, * * RET_T = "String&" * NAME = "addString" * __VA_ARGS__ = rest of arguments. * * class addStringMethod : public Method { * W_DECL_CLASS(addStringMethod, Method) * * typedef Mashall<RET_T>::MashalledType ReturnType; * ReturnType _return; * * public: * addStringMethod() * // Mashall<RET_T>::RefindType is String * // Mashall<RET_T>::MashalledType is Reference<String> * // Mashall<RET_T>::isReference is 1 * // Mashall<RET_T>::isSharable is 1 * * // Occupiable = Reference<Occupiable> 은, rhs의 Sharable의 값이 Occupiable로 들어간다 * // 이는 Occupiable은 어떻게 해서라도 값vs값의 할당이 일어나야 하기 때문이다. * // 물론 Reference<Occupiable> = Occupiable의 경우에는 Reference::operator=()가 된다. * // 그래서 아래의 경우에는 원본이 Bind로 라이프사이클이 관리되고, 그것이 Sharable이든 * // Occupiable이든 값은 return으로 들어갈 수 있다. * _return = Reference(Mashall<RET_T>::RefindType()); * * _arguments << Reference<MyFirstWorldModule>() // thisptr * * char* __VA_ARGS_를 split하고, loop를 돌면서 적합한 TClass<T>를 만들어서 arguments * 에 넣어야 한다. 이 것을 하는 도중에 T* arg, T * args, T *args 같은 케이스들도 * 문제없이 파싱할 수 있어야 한다. * * 어떻게? * * * _fptr = &MyFirstWorldModule::addString; * * } * * String& (addStringMethod::*_fptr)(String&, __VA_ARGS_...); * * // World에서 메소드를 실행하기 위한 가장 짦은 인터페이스이다. * // Native를 위한 인자의 가공이 시작된다. * virtual Bind<Node> call(const Arguments& args) { * if(Mashall<RET_T>::sharable) * if(is_ref) // is_ref에는 Reference로 반환한경우도 포함이 되어야 한다. * return _return = (me->*_fptr)(args[0].to<String>(), args[1].to.... 재귀 ); * else * // RET_T는 Sharable인데, 값으로 반환한 경우다. 불가피하게 퍼포먼스가 소모. * return _return = (me->*_fptr)(args[0].to<String>(), args[1].to.... 재귀 ).clone(); * } * }; */ } // 사용자는 이걸 따로 만들어야 한다. // 반환값은 동일하게 String& addString(String& arg1, String arg2/*값 복사가 1번더 일어난다*/) { static String added; added = arg1 + arg2; return added; } Reference addString(String& arg1, String& arg2) { // Reference의 사용방법1 : Reference<String> ret = new String(arg1 + arg2); // 방법2: Reference<String> ret = arg1.clone(); *ret += arg2; // 방법3: Reference<String> ret = (arg1 + arg2).clone(); // 방법4: Reference<String> ret = String::make(); *ret = arg1 + arg2; return ret; } public: }; } <commit_msg>+ [class-design] WRD_DECL macro usage.<commit_after>namespace W { template <typename T> class Bind : public Thing { public: }; class Result : public Thing { }; class Thing { public: virtual const Result& release(); virtual Bind<Thing> clone() = 0; }; class Container : public Thing { public: }; template <typename T> class Array : public Container { }; class Members : public Array<Node> { public: }; class Node : public Thing { public: virtual Bind<Node> call(const String& msg, Array<Argument> args) { } virtual Members& getMembers() = 0; }; class Message : public Thing { }; class Method : public Node { public: virtual Bind<Node>& call(const Message& msg) { } virtual Node& call(const Arguments& args) = 0; }; class Class : public Node { public: virtual const String& getName() const = 0; virtual const Array<Class>& getSupers() const = 0; virtual const Array<Class>& getSubs() const = 0; virtual Members& getMembers() { return _members; } Members& getMethods() { return _methods; } Members& getVariables() { return _variables; } Object incarnate() const {// World 객체를 만드는 것이다. return Object(*this); } virtual Bind<Node> call(const String& msg, Array<Argument> args) { } // Class의 각 _variables는 부모의 _variables를 clone() 한 뒤, 자기만의 심볼을 뒤에 push 한 것이다. // " _methods 동일. _members는 자연스럽게 이게 된 상태. // ! 논리적으로 _members 안에는 중복 이름이 있어서는 안된다. Members _variables; Members _methods; Chain<Node> _members; }; template <typename T> class Classer : public Class { // TClasser는 World에 visible 하지 않다: // visible하다는 것은 논리적으로는 "World에서 접근 가능함" 이라는 뜻이며, // 물리적으로는 "파싱테이블에 매핑되어있어서 Txt가 적절한 객체로 생성될 수 있음" 이라는 뜻이다. // C++안에서만 Classer<T>를 사용할 수 있다. public: }; class WorldClass : public Class { public: }; // Object는 World의 객체다. 객체는 항상 객체라는 타입이다. A라는 클래스의 객체와 B라는 클래스의 객체는 Native적으로, // 동일한 클래스의 객체다. 바로 이부분이 헷갈리기 쉬운 부분이며 동시에 World의 재사용성을 높여주는 부분이기도 하다. class Object : public Node { public: Object(Class& klass) { _class = klass; _variables = klass.getVariables(); _members.chain(klass.getMethods()); _members.chain(_variables); } Members& getMembers() { return _members; } Members& getVariables() { return _variables; } private: Weak<Class> _class; // 이게 뭘 가리키느냐에 따라서, 어떠한 World 객체인가가 결정되는 것이다. Members _variables; Chain<Node> _members; }; // RETURN_T=String& is by-ref and sharable. /* So, Above macro will expand like this, * * RET_T = "String&" * NAME = "addString" * __VA_ARGS__ = rest of arguments. * * class addStringMethod : public Method { * W_DECL_CLASS(addStringMethod, Method) * * typedef Mashall<RET_T>::MashalledType ReturnType; * ReturnType _return; * * public: * addStringMethod() * // Mashall<RET_T>::RefindType is String * // Mashall<RET_T>::MashalledType is Reference<String> * // Mashall<RET_T>::isReference is 1 * // Mashall<RET_T>::isSharable is 1 * * // Occupiable = Reference<Occupiable> 은, rhs의 Sharable의 값이 Occupiable로 들어간다 * // 이는 Occupiable은 어떻게 해서라도 값vs값의 할당이 일어나야 하기 때문이다. * // 물론 Reference<Occupiable> = Occupiable의 경우에는 Reference::operator=()가 된다. * // 그래서 아래의 경우에는 원본이 Bind로 라이프사이클이 관리되고, 그것이 Sharable이든 * // Occupiable이든 값은 return으로 들어갈 수 있다. * _return = Reference(Mashall<RET_T>::RefindType()); * * _arguments << Reference<MyFirstWorldModule>() // thisptr * * char* __VA_ARGS_를 split하고, loop를 돌면서 적합한 TClass<T>를 만들어서 arguments * 에 넣어야 한다. 이 것을 하는 도중에 T* arg, T * args, T *args 같은 케이스들도 * 문제없이 파싱할 수 있어야 한다. * * 어떻게? * * * _fptr = &MyFirstWorldModule::addString; * * } * * String& (addStringMethod::*_fptr)(String&, __VA_ARGS_...); * * // World에서 메소드를 실행하기 위한 가장 짦은 인터페이스이다. * // Native를 위한 인자의 가공이 시작된다. * virtual Bind<Node> call(const Arguments& args) { * if(Mashall<RET_T>::sharable) * if(is_ref) // is_ref에는 Reference로 반환한경우도 포함이 되어야 한다. * return _return = (me->*_fptr)(args[0].to<String>(), args[1].to.... 재귀 ); * else * // RET_T는 Sharable인데, 값으로 반환한 경우다. 불가피하게 퍼포먼스가 소모. * return _return = (me->*_fptr)(args[0].to<String>(), args[1].to.... 재귀 ).clone(); * } * }; */ #define WRD_DECL_2(T, S) ....... #define WRD_DECL_3(T, S, M) \ WRD_DECL_2(T,S) \ protected: \ static const Result& _onInitializeMethods(List<Method>& tray) { \ FOR_EACH() } // 사용법1: // .HPP에서 class MyFirstWorldModule : public Object { WRD_DECL_ONLY(MyFirstWorldModule, Object, String, addString, (String&, String&) // 조건1. ,로 구분한다. // 조건2. 인자명 없다. ) // static onInitializeMethods() 구현된다. // 조건3. 시작과 끝 ()를 넣는다. public: String addString(String& arg1, String& arg2) { // Reference의 사용방법1 : Reference<String> ret = new String(arg1 + arg2); // 방법2: Reference<String> ret = arg1.clone(); *ret += arg2; // 방법3: Reference<String> ret = (arg1 + arg2).clone(); // 방법4: Reference<String> ret = String::make(); *ret = arg1 + arg2; return ret; } }; // .CPP 구현 없음. // 사용법2: // .HPP에서 class MyFirstWorldModule : public Object { WRD_DECL(MyFirstWorldModule, Object) // static onInitializeMethods(); 선언 된다. public: String addString(String& arg1, String& arg2); // 여기서 정의해도 상관없다. }; // .CPP에서 WRD_DEF(MyFirstWorldModule, (String, addString, String&, String & const) // static onInitializeMethods() 구현들어간다. ) String MyFirstWorldModule::addString(String& arg1, String & const arg2) { ... dosomething ... } } <|endoftext|>
<commit_before>#include <float.h> #include "reductions.h" #include "multiclass.h" #include "cost_sensitive.h" #include "cb.h" #include "cb_algs.h" #include "rand48.h" #include "bs.h" using namespace LEARNER; namespace CBIFY { struct cbify { size_t k; size_t tau; float epsilon; size_t counter; size_t bags; v_array<float> count; v_array<uint32_t> predictions; CB::label cb_label; COST_SENSITIVE::label cs_label; COST_SENSITIVE::label second_cs_label; learner* cs; vw* all; }; uint32_t do_uniform(cbify& data) { //Draw an action return (uint32_t)ceil(frand48() * data.k); } uint32_t choose_bag(cbify& data) { //Draw an action return (uint32_t)floor(frand48() * data.bags); } float loss(uint32_t label, uint32_t final_prediction) { if (label != final_prediction) return 1.; else return 0.; } template <bool is_learn> void predict_or_learn_first(cbify& data, learner& base, example& ec) {//Explore tau times, then act according to optimal. MULTICLASS::multiclass* ld = (MULTICLASS::multiclass*)ec.ld; //Use CB to find current prediction for remaining rounds. if (data.tau && is_learn) { ld->prediction = (uint32_t)do_uniform(data); ec.loss = loss(ld->label, ld->prediction); data.tau--; uint32_t action = ld->prediction; CB::cb_class l = {ec.loss, action, 1.f / data.k, 0}; data.cb_label.costs.erase(); data.cb_label.costs.push_back(l); ec.ld = &(data.cb_label); base.learn(ec); ld->prediction = action; ec.loss = l.cost; } else { data.cb_label.costs.erase(); ec.ld = &(data.cb_label); base.predict(ec); ld->prediction = data.cb_label.prediction; ec.loss = loss(ld->label, ld->prediction); } ec.ld = ld; } template <bool is_learn> void predict_or_learn_greedy(cbify& data, learner& base, example& ec) {//Explore uniform random an epsilon fraction of the time. MULTICLASS::multiclass* ld = (MULTICLASS::multiclass*)ec.ld; ec.ld = &(data.cb_label); data.cb_label.costs.erase(); base.predict(ec); uint32_t action = data.cb_label.prediction; float base_prob = data.epsilon / data.k; if (frand48() < 1. - data.epsilon) { CB::cb_class l = {loss(ld->label, action), action, 1.f - data.epsilon + base_prob}; data.cb_label.costs.push_back(l); } else { action = do_uniform(data); CB::cb_class l = {loss(ld->label, action), action, base_prob}; if (action == data.cb_label.prediction) l.probability = 1.f - data.epsilon + base_prob; data.cb_label.costs.push_back(l); } if (is_learn) base.learn(ec); ld->prediction = action; ec.ld = ld; ec.loss = loss(ld->label, action); } template <bool is_learn> void predict_or_learn_bag(cbify& data, learner& base, example& ec) {//Randomize over predictions from a base set of predictors //Use CB to find current predictions. MULTICLASS::multiclass* ld = (MULTICLASS::multiclass*)ec.ld; ec.ld = &(data.cb_label); data.cb_label.costs.erase(); for (size_t j = 1; j <= data.k; j++) data.count[j] = 0; size_t bag = choose_bag(data); uint32_t action = 0; for (size_t i = 0; i < data.bags; i++) { base.predict(ec,i); data.count[data.cb_label.prediction]++; if (i == bag) action = data.cb_label.prediction; } assert(action != 0); if (is_learn) { float probability = (float)data.count[action] / (float)data.bags; CB::cb_class l = {loss(ld->label, action), action, probability}; data.cb_label.costs.push_back(l); for (size_t i = 0; i < data.bags; i++) { uint32_t count = BS::weight_gen(); for (uint32_t j = 0; j < count; j++) base.learn(ec,i); } } ld->prediction = action; ec.ld = ld; } uint32_t choose_action(v_array<float>& distribution) { float value = frand48(); for (uint32_t i = 0; i < distribution.size();i++) { if (value <= distribution[i]) return i+1; else value -= distribution[i]; } //some rounding problem presumably. return 1; } void safety(v_array<float>& distribution, float min_prob) { float added_mass = 0.; for (uint32_t i = 0; i < distribution.size();i++) if (distribution[i] > 0 && distribution[i] <= min_prob) { added_mass += min_prob - distribution[i]; distribution[i] = min_prob; } float ratio = 1.f / (1.f + added_mass); if (ratio < 0.999) { for (uint32_t i = 0; i < distribution.size(); i++) if (distribution[i] > min_prob) distribution[i] = distribution[i] * ratio; safety(distribution, min_prob); } } void gen_cs_label(vw& all, CB::cb_class& known_cost, example& ec, COST_SENSITIVE::label& cs_ld, uint32_t label) { COST_SENSITIVE::wclass wc; //get cost prediction for this label wc.x = CB_ALGS::get_cost_pred<false>(all, &known_cost, ec, label, all.sd->k); wc.class_index = label; wc.partial_prediction = 0.; wc.wap_value = 0.; //add correction if we observed cost for this action and regressor is wrong if( known_cost.action == label ) wc.x += (known_cost.cost - wc.x) / known_cost.probability; cs_ld.costs.push_back( wc ); } template <bool is_learn> void predict_or_learn_cover(cbify& data, learner& base, example& ec) {//Randomize over predictions from a base set of predictors //Use cost sensitive oracle to cover actions to form distribution. MULTICLASS::multiclass* ld = (MULTICLASS::multiclass*)ec.ld; data.counter++; data.count.erase(); data.cs_label.costs.erase(); for (uint32_t j = 0; j < data.k; j++) { data.count.push_back(0); COST_SENSITIVE::wclass wc; //get cost prediction for this label wc.x = FLT_MAX; wc.class_index = j+1; wc.partial_prediction = 0.; wc.wap_value = 0.; data.cs_label.costs.push_back(wc); } float additive_probability = 1.f / (float)data.bags; ec.ld = &data.cs_label; for (size_t i = 0; i < data.bags; i++) { //get predicted cost-sensitive predictions if (i == 0) data.cs->predict(ec, i); else data.cs->predict(ec,i+1); data.count[data.cs_label.prediction-1] += additive_probability; data.predictions[i] = (uint32_t)data.cs_label.prediction; } float min_prob = data.epsilon * min (1.f / data.k, 1.f / (float)sqrt(data.counter * data.k)); safety(data.count, min_prob); //compute random action uint32_t action = choose_action(data.count); if (is_learn) { data.cb_label.costs.erase(); float probability = (float)data.count[action-1]; CB::cb_class l = {loss(ld->label, action), action, probability}; data.cb_label.costs.push_back(l); ec.ld = &(data.cb_label); base.learn(ec); //Now update oracles //1. Compute loss vector data.cs_label.costs.erase(); float norm = min_prob * data.k; for (uint32_t j = 0; j < data.k; j++) { //data.cs_label now contains an unbiased estimate of cost of each class. gen_cs_label(*data.all, l, ec, data.cs_label, j+1); data.count[j] = 0; } ec.ld = &data.second_cs_label; //2. Update functions for (size_t i = 0; i < data.bags; i++) { //get predicted cost-sensitive predictions for (uint32_t j = 0; j < data.k; j++) { float pseudo_cost = data.cs_label.costs[j].x - data.epsilon * min_prob / (max(data.count[j], min_prob) / norm) + 1; data.second_cs_label.costs[j].class_index = j+1; data.second_cs_label.costs[j].x = pseudo_cost; } if (i != 0) data.cs->learn(ec,i+1); if (data.count[data.predictions[i]-1] < min_prob) norm += max(0, additive_probability - (min_prob - data.count[data.predictions[i]-1])); else norm += additive_probability; data.count[data.predictions[i]-1] += additive_probability; } } ld->prediction = action; ec.ld = ld; } void init_driver(cbify&) {} void finish_example(vw& all, cbify&, example& ec) { MULTICLASS::output_example(all, ec); VW::finish_example(all, &ec); } void finish(cbify& data) { CB::cb_label.delete_label(&data.cb_label); } learner* setup(vw& all, po::variables_map& vm) {//parse and set arguments cbify* data = (cbify*)calloc_or_die(1, sizeof(cbify)); data->epsilon = 0.05f; data->counter = 0; data->tau = 1000; data->all = &all; po::options_description cb_opts("CBIFY options"); cb_opts.add_options() ("first", po::value<size_t>(), "tau-first exploration") ("epsilon",po::value<float>() ,"epsilon-greedy exploration") ("bag",po::value<size_t>() ,"bagging-based exploration") ("cover",po::value<size_t>() ,"bagging-based exploration"); vm = add_options(all, cb_opts); data->k = (uint32_t)vm["cbify"].as<size_t>(); //appends nb_actions to options_from_file so it is saved to regressor later std::stringstream ss; ss << " --cbify " << data->k; all.file_options.append(ss.str()); all.p->lp = MULTICLASS::mc_label; learner* l; if (vm.count("cover")) { data->bags = (uint32_t)vm["cover"].as<size_t>(); data->cs = all.cost_sensitive; data->count.resize(data->k+1); data->predictions.resize(data->bags); data->second_cs_label.costs.resize(data->k); data->second_cs_label.costs.end = data->second_cs_label.costs.begin+data->k; if ( vm.count("epsilon") ) data->epsilon = vm["epsilon"].as<float>(); l = new learner(data, all.l, data->bags + 1); l->set_learn<cbify, predict_or_learn_cover<true> >(); l->set_predict<cbify, predict_or_learn_cover<false> >(); } else if (vm.count("bag")) { data->bags = (uint32_t)vm["bag"].as<size_t>(); data->count.resize(data->k+1); l = new learner(data, all.l, data->bags); l->set_learn<cbify, predict_or_learn_bag<true> >(); l->set_predict<cbify, predict_or_learn_bag<false> >(); } else if (vm.count("first") ) { data->tau = (uint32_t)vm["first"].as<size_t>(); l = new learner(data, all.l, 1); l->set_learn<cbify, predict_or_learn_first<true> >(); l->set_predict<cbify, predict_or_learn_first<false> >(); } else { if ( vm.count("epsilon") ) data->epsilon = vm["epsilon"].as<float>(); l = new learner(data, all.l, 1); l->set_learn<cbify, predict_or_learn_greedy<true> >(); l->set_predict<cbify, predict_or_learn_greedy<false> >(); } l->set_finish_example<cbify,finish_example>(); l->set_finish<cbify,finish>(); l->set_init_driver<cbify,init_driver>(); return l; } } <commit_msg>tau-first simplification<commit_after>#include <float.h> #include "reductions.h" #include "multiclass.h" #include "cost_sensitive.h" #include "cb.h" #include "cb_algs.h" #include "rand48.h" #include "bs.h" using namespace LEARNER; namespace CBIFY { struct cbify { size_t k; size_t tau; float epsilon; size_t counter; size_t bags; v_array<float> count; v_array<uint32_t> predictions; CB::label cb_label; COST_SENSITIVE::label cs_label; COST_SENSITIVE::label second_cs_label; learner* cs; vw* all; }; uint32_t do_uniform(cbify& data) { //Draw an action return (uint32_t)ceil(frand48() * data.k); } uint32_t choose_bag(cbify& data) { //Draw an action return (uint32_t)floor(frand48() * data.bags); } float loss(uint32_t label, uint32_t final_prediction) { if (label != final_prediction) return 1.; else return 0.; } template <bool is_learn> void predict_or_learn_first(cbify& data, learner& base, example& ec) {//Explore tau times, then act according to optimal. MULTICLASS::multiclass* ld = (MULTICLASS::multiclass*)ec.ld; //Use CB to find current prediction for remaining rounds. if (data.tau && is_learn) { uint32_t action = (uint32_t)do_uniform(data); ec.loss = loss(ld->label, action); data.tau--; CB::cb_class l = {ec.loss, action, 1.f / data.k, 0}; data.cb_label.costs.erase(); data.cb_label.costs.push_back(l); ec.ld = &(data.cb_label); base.learn(ec); ld->prediction = action; ec.loss = l.cost; } else { data.cb_label.costs.erase(); ec.ld = &(data.cb_label); base.predict(ec); ld->prediction = data.cb_label.prediction; ec.loss = loss(ld->label, ld->prediction); } ec.ld = ld; } template <bool is_learn> void predict_or_learn_greedy(cbify& data, learner& base, example& ec) {//Explore uniform random an epsilon fraction of the time. MULTICLASS::multiclass* ld = (MULTICLASS::multiclass*)ec.ld; ec.ld = &(data.cb_label); data.cb_label.costs.erase(); base.predict(ec); uint32_t action = data.cb_label.prediction; float base_prob = data.epsilon / data.k; if (frand48() < 1. - data.epsilon) { CB::cb_class l = {loss(ld->label, action), action, 1.f - data.epsilon + base_prob}; data.cb_label.costs.push_back(l); } else { action = do_uniform(data); CB::cb_class l = {loss(ld->label, action), action, base_prob}; if (action == data.cb_label.prediction) l.probability = 1.f - data.epsilon + base_prob; data.cb_label.costs.push_back(l); } if (is_learn) base.learn(ec); ld->prediction = action; ec.ld = ld; ec.loss = loss(ld->label, action); } template <bool is_learn> void predict_or_learn_bag(cbify& data, learner& base, example& ec) {//Randomize over predictions from a base set of predictors //Use CB to find current predictions. MULTICLASS::multiclass* ld = (MULTICLASS::multiclass*)ec.ld; ec.ld = &(data.cb_label); data.cb_label.costs.erase(); for (size_t j = 1; j <= data.k; j++) data.count[j] = 0; size_t bag = choose_bag(data); uint32_t action = 0; for (size_t i = 0; i < data.bags; i++) { base.predict(ec,i); data.count[data.cb_label.prediction]++; if (i == bag) action = data.cb_label.prediction; } assert(action != 0); if (is_learn) { float probability = (float)data.count[action] / (float)data.bags; CB::cb_class l = {loss(ld->label, action), action, probability}; data.cb_label.costs.push_back(l); for (size_t i = 0; i < data.bags; i++) { uint32_t count = BS::weight_gen(); for (uint32_t j = 0; j < count; j++) base.learn(ec,i); } } ld->prediction = action; ec.ld = ld; } uint32_t choose_action(v_array<float>& distribution) { float value = frand48(); for (uint32_t i = 0; i < distribution.size();i++) { if (value <= distribution[i]) return i+1; else value -= distribution[i]; } //some rounding problem presumably. return 1; } void safety(v_array<float>& distribution, float min_prob) { float added_mass = 0.; for (uint32_t i = 0; i < distribution.size();i++) if (distribution[i] > 0 && distribution[i] <= min_prob) { added_mass += min_prob - distribution[i]; distribution[i] = min_prob; } float ratio = 1.f / (1.f + added_mass); if (ratio < 0.999) { for (uint32_t i = 0; i < distribution.size(); i++) if (distribution[i] > min_prob) distribution[i] = distribution[i] * ratio; safety(distribution, min_prob); } } void gen_cs_label(vw& all, CB::cb_class& known_cost, example& ec, COST_SENSITIVE::label& cs_ld, uint32_t label) { COST_SENSITIVE::wclass wc; //get cost prediction for this label wc.x = CB_ALGS::get_cost_pred<false>(all, &known_cost, ec, label, all.sd->k); wc.class_index = label; wc.partial_prediction = 0.; wc.wap_value = 0.; //add correction if we observed cost for this action and regressor is wrong if( known_cost.action == label ) wc.x += (known_cost.cost - wc.x) / known_cost.probability; cs_ld.costs.push_back( wc ); } template <bool is_learn> void predict_or_learn_cover(cbify& data, learner& base, example& ec) {//Randomize over predictions from a base set of predictors //Use cost sensitive oracle to cover actions to form distribution. MULTICLASS::multiclass* ld = (MULTICLASS::multiclass*)ec.ld; data.counter++; data.count.erase(); data.cs_label.costs.erase(); for (uint32_t j = 0; j < data.k; j++) { data.count.push_back(0); COST_SENSITIVE::wclass wc; //get cost prediction for this label wc.x = FLT_MAX; wc.class_index = j+1; wc.partial_prediction = 0.; wc.wap_value = 0.; data.cs_label.costs.push_back(wc); } float additive_probability = 1.f / (float)data.bags; ec.ld = &data.cs_label; for (size_t i = 0; i < data.bags; i++) { //get predicted cost-sensitive predictions if (i == 0) data.cs->predict(ec, i); else data.cs->predict(ec,i+1); data.count[data.cs_label.prediction-1] += additive_probability; data.predictions[i] = (uint32_t)data.cs_label.prediction; } float min_prob = data.epsilon * min (1.f / data.k, 1.f / (float)sqrt(data.counter * data.k)); safety(data.count, min_prob); //compute random action uint32_t action = choose_action(data.count); if (is_learn) { data.cb_label.costs.erase(); float probability = (float)data.count[action-1]; CB::cb_class l = {loss(ld->label, action), action, probability}; data.cb_label.costs.push_back(l); ec.ld = &(data.cb_label); base.learn(ec); //Now update oracles //1. Compute loss vector data.cs_label.costs.erase(); float norm = min_prob * data.k; for (uint32_t j = 0; j < data.k; j++) { //data.cs_label now contains an unbiased estimate of cost of each class. gen_cs_label(*data.all, l, ec, data.cs_label, j+1); data.count[j] = 0; } ec.ld = &data.second_cs_label; //2. Update functions for (size_t i = 0; i < data.bags; i++) { //get predicted cost-sensitive predictions for (uint32_t j = 0; j < data.k; j++) { float pseudo_cost = data.cs_label.costs[j].x - data.epsilon * min_prob / (max(data.count[j], min_prob) / norm) + 1; data.second_cs_label.costs[j].class_index = j+1; data.second_cs_label.costs[j].x = pseudo_cost; } if (i != 0) data.cs->learn(ec,i+1); if (data.count[data.predictions[i]-1] < min_prob) norm += max(0, additive_probability - (min_prob - data.count[data.predictions[i]-1])); else norm += additive_probability; data.count[data.predictions[i]-1] += additive_probability; } } ld->prediction = action; ec.ld = ld; } void init_driver(cbify&) {} void finish_example(vw& all, cbify&, example& ec) { MULTICLASS::output_example(all, ec); VW::finish_example(all, &ec); } void finish(cbify& data) { CB::cb_label.delete_label(&data.cb_label); } learner* setup(vw& all, po::variables_map& vm) {//parse and set arguments cbify* data = (cbify*)calloc_or_die(1, sizeof(cbify)); data->epsilon = 0.05f; data->counter = 0; data->tau = 1000; data->all = &all; po::options_description cb_opts("CBIFY options"); cb_opts.add_options() ("first", po::value<size_t>(), "tau-first exploration") ("epsilon",po::value<float>() ,"epsilon-greedy exploration") ("bag",po::value<size_t>() ,"bagging-based exploration") ("cover",po::value<size_t>() ,"bagging-based exploration"); vm = add_options(all, cb_opts); data->k = (uint32_t)vm["cbify"].as<size_t>(); //appends nb_actions to options_from_file so it is saved to regressor later std::stringstream ss; ss << " --cbify " << data->k; all.file_options.append(ss.str()); all.p->lp = MULTICLASS::mc_label; learner* l; if (vm.count("cover")) { data->bags = (uint32_t)vm["cover"].as<size_t>(); data->cs = all.cost_sensitive; data->count.resize(data->k+1); data->predictions.resize(data->bags); data->second_cs_label.costs.resize(data->k); data->second_cs_label.costs.end = data->second_cs_label.costs.begin+data->k; if ( vm.count("epsilon") ) data->epsilon = vm["epsilon"].as<float>(); l = new learner(data, all.l, data->bags + 1); l->set_learn<cbify, predict_or_learn_cover<true> >(); l->set_predict<cbify, predict_or_learn_cover<false> >(); } else if (vm.count("bag")) { data->bags = (uint32_t)vm["bag"].as<size_t>(); data->count.resize(data->k+1); l = new learner(data, all.l, data->bags); l->set_learn<cbify, predict_or_learn_bag<true> >(); l->set_predict<cbify, predict_or_learn_bag<false> >(); } else if (vm.count("first") ) { data->tau = (uint32_t)vm["first"].as<size_t>(); l = new learner(data, all.l, 1); l->set_learn<cbify, predict_or_learn_first<true> >(); l->set_predict<cbify, predict_or_learn_first<false> >(); } else { if ( vm.count("epsilon") ) data->epsilon = vm["epsilon"].as<float>(); l = new learner(data, all.l, 1); l->set_learn<cbify, predict_or_learn_greedy<true> >(); l->set_predict<cbify, predict_or_learn_greedy<false> >(); } l->set_finish_example<cbify,finish_example>(); l->set_finish<cbify,finish>(); l->set_init_driver<cbify,init_driver>(); return l; } } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <utility> #include <vector> #include <string> #include "sequence/Common.hpp" #include "sequence/details/StringView.hpp" namespace sequence { // An Item represents a sequence entry. // It can be of the following types : // - INVALID : the item is not in a valid state. // - SINGLE : it's either a single file or directory. // - INDICED : it's a sequence with a set of numbers attached to it. // - PACKED : it's a contiguous sequence going from start to end inclusive. struct Item { enum : char { PADDING_CHAR = '#' }; enum Type { INVALID, SINGLE, INDICED, PACKED }; std::string filename; Index start = -1, end = -1; char padding = -1, step = -1; Indices indices; Item() = default; Item(const Item &other) = default; Item(Item &&other) = default; Item(CStringView filename); Item(CStringView filename, Indices &&indices); Item &operator=(const Item &other) = default; Item &operator=(Item &&other) = default; Type getType() const; bool operator<(const Item &other) const; bool operator==(const Item &other) const; }; // For convenience, Items is defined to be a vector of Item typedef std::vector<Item> Items; } // namespace sequence <commit_msg>Remove supplementary PADDING_CHAR definition<commit_after>#pragma once #include <cstdint> #include <utility> #include <vector> #include <string> #include "sequence/Common.hpp" #include "sequence/details/StringView.hpp" namespace sequence { // An Item represents a sequence entry. // It can be of the following types : // - INVALID : the item is not in a valid state. // - SINGLE : it's either a single file or directory. // - INDICED : it's a sequence with a set of numbers attached to it. // - PACKED : it's a contiguous sequence going from start to end inclusive. struct Item { enum Type { INVALID, SINGLE, INDICED, PACKED }; std::string filename; Index start = -1, end = -1; char padding = -1, step = -1; Indices indices; Item() = default; Item(const Item &other) = default; Item(Item &&other) = default; Item(CStringView filename); Item(CStringView filename, Indices &&indices); Item &operator=(const Item &other) = default; Item &operator=(Item &&other) = default; Type getType() const; bool operator<(const Item &other) const; bool operator==(const Item &other) const; }; // For convenience, Items is defined to be a vector of Item typedef std::vector<Item> Items; } // namespace sequence <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop_proxy.h" #include "remoting/jingle_glue/mock_objects.h" #include "remoting/host/capturer_fake.h" #include "remoting/host/chromoting_host.h" #include "remoting/host/chromoting_host_context.h" #include "remoting/host/host_mock_objects.h" #include "remoting/host/it2me_host_user_interface.h" #include "remoting/proto/video.pb.h" #include "remoting/protocol/protocol_mock_objects.h" #include "remoting/protocol/session_config.h" #include "testing/gmock_mutant.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::remoting::protocol::MockClientStub; using ::remoting::protocol::MockConnectionToClient; using ::remoting::protocol::MockConnectionToClientEventHandler; using ::remoting::protocol::MockHostStub; using ::remoting::protocol::MockSession; using ::remoting::protocol::MockVideoStub; using ::remoting::protocol::SessionConfig; using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::CreateFunctor; using testing::DeleteArg; using testing::DoAll; using testing::InSequence; using testing::InvokeArgument; using testing::InvokeWithoutArgs; using testing::Return; using testing::ReturnRef; using testing::Sequence; namespace remoting { namespace { void PostQuitTask(MessageLoop* message_loop) { message_loop->PostTask(FROM_HERE, MessageLoop::QuitClosure()); } // Run the task and delete it afterwards. This action is used to deal with // done callbacks. ACTION(RunDoneTask) { arg1.Run(); } ACTION_P(QuitMainMessageLoop, message_loop) { PostQuitTask(message_loop); } void DummyDoneTask() { } } // namespace class ChromotingHostTest : public testing::Test { public: ChromotingHostTest() { } virtual void SetUp() OVERRIDE { message_loop_proxy_ = base::MessageLoopProxy::current(); ON_CALL(context_, main_message_loop()) .WillByDefault(Return(&message_loop_)); ON_CALL(context_, encode_message_loop()) .WillByDefault(Return(&message_loop_)); ON_CALL(context_, network_message_loop()) .WillByDefault(Return(message_loop_proxy_.get())); ON_CALL(context_, ui_message_loop()) .WillByDefault(Return(message_loop_proxy_.get())); EXPECT_CALL(context_, main_message_loop()) .Times(AnyNumber()); EXPECT_CALL(context_, encode_message_loop()) .Times(AnyNumber()); EXPECT_CALL(context_, network_message_loop()) .Times(AnyNumber()); EXPECT_CALL(context_, ui_message_loop()) .Times(AnyNumber()); scoped_ptr<Capturer> capturer(new CapturerFake()); scoped_ptr<EventExecutor> event_executor(new MockEventExecutor()); desktop_environment_ = DesktopEnvironment::CreateFake( &context_, capturer.Pass(), event_executor.Pass()); scoped_ptr<protocol::SessionManager> session_manager( new protocol::MockSessionManager()); host_ = new ChromotingHost( &context_, &signal_strategy_, desktop_environment_.get(), session_manager.Pass()); disconnect_window_ = new MockDisconnectWindow(); continue_window_ = new MockContinueWindow(); local_input_monitor_ = new MockLocalInputMonitor(); it2me_host_user_interface_.reset(new It2MeHostUserInterface(&context_)); it2me_host_user_interface_->StartForTest( host_, base::Bind(&ChromotingHost::Shutdown, host_, base::Closure()), scoped_ptr<DisconnectWindow>(disconnect_window_), scoped_ptr<ContinueWindow>(continue_window_), scoped_ptr<LocalInputMonitor>(local_input_monitor_)); session_ = new MockSession(); session2_ = new MockSession(); session_config_ = SessionConfig::GetDefault(); session_jid_ = "user@domain/rest-of-jid"; session_config2_ = SessionConfig::GetDefault(); session2_jid_ = "user2@domain/rest-of-jid"; EXPECT_CALL(*session_, jid()) .WillRepeatedly(ReturnRef(session_jid_)); EXPECT_CALL(*session2_, jid()) .WillRepeatedly(ReturnRef(session2_jid_)); EXPECT_CALL(*session_, SetStateChangeCallback(_)) .Times(AnyNumber()); EXPECT_CALL(*session2_, SetStateChangeCallback(_)) .Times(AnyNumber()); EXPECT_CALL(*session_, config()) .WillRepeatedly(ReturnRef(session_config_)); EXPECT_CALL(*session2_, config()) .WillRepeatedly(ReturnRef(session_config2_)); EXPECT_CALL(*session_, Close()) .Times(AnyNumber()); EXPECT_CALL(*session2_, Close()) .Times(AnyNumber()); owned_connection_.reset(new MockConnectionToClient( session_, &host_stub_, desktop_environment_->event_executor())); connection_ = owned_connection_.get(); owned_connection2_.reset(new MockConnectionToClient( session2_, &host_stub2_, desktop_environment_->event_executor())); connection2_ = owned_connection2_.get(); ON_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillByDefault(DeleteArg<0>()); ON_CALL(video_stub2_, ProcessVideoPacketPtr(_, _)) .WillByDefault(DeleteArg<0>()); ON_CALL(*connection_, video_stub()) .WillByDefault(Return(&video_stub_)); ON_CALL(*connection_, client_stub()) .WillByDefault(Return(&client_stub_)); ON_CALL(*connection_, session()) .WillByDefault(Return(session_)); ON_CALL(*connection2_, video_stub()) .WillByDefault(Return(&video_stub2_)); ON_CALL(*connection2_, client_stub()) .WillByDefault(Return(&client_stub2_)); ON_CALL(*connection2_, session()) .WillByDefault(Return(session2_)); EXPECT_CALL(*connection_, video_stub()) .Times(AnyNumber()); EXPECT_CALL(*connection_, client_stub()) .Times(AnyNumber()); EXPECT_CALL(*connection_, session()) .Times(AnyNumber()); EXPECT_CALL(*connection2_, video_stub()) .Times(AnyNumber()); EXPECT_CALL(*connection2_, client_stub()) .Times(AnyNumber()); EXPECT_CALL(*connection2_, session()) .Times(AnyNumber()); } virtual void TearDown() OVERRIDE { owned_connection_.reset(); owned_connection2_.reset(); host_ = NULL; // Run message loop before destroying because protocol::Session is // destroyed asynchronously. message_loop_.RunAllPending(); } // Helper method to pretend a client is connected to ChromotingHost. void SimulateClientConnection(int connection_index, bool authenticate) { scoped_ptr<protocol::ConnectionToClient> connection = ((connection_index == 0) ? owned_connection_ : owned_connection2_). PassAs<protocol::ConnectionToClient>(); protocol::ConnectionToClient* connection_ptr = connection.get(); ClientSession* client = new ClientSession( host_.get(), connection.Pass(), desktop_environment_->event_executor(), desktop_environment_->capturer()); connection->set_host_stub(client); context_.network_message_loop()->PostTask( FROM_HERE, base::Bind(&ChromotingHostTest::AddClientToHost, host_, client)); if (authenticate) { context_.network_message_loop()->PostTask( FROM_HERE, base::Bind(&ClientSession::OnConnectionAuthenticated, base::Unretained(client), connection_ptr)); context_.network_message_loop()->PostTask( FROM_HERE, base::Bind(&ClientSession::OnConnectionChannelsConnected, base::Unretained(client), connection_ptr)); } if (connection_index == 0) { client_ = client; } else { client2_ = client; } } // Helper method to remove a client connection from ChromotingHost. void RemoveClientSession() { client_->OnConnectionClosed(connection_, protocol::OK); } static void AddClientToHost(scoped_refptr<ChromotingHost> host, ClientSession* session) { host->clients_.push_back(session); } void ShutdownHost() { message_loop_.PostTask( FROM_HERE, base::Bind(&ChromotingHost::Shutdown, host_, base::Bind(&PostQuitTask, &message_loop_))); } protected: MessageLoop message_loop_; scoped_refptr<base::MessageLoopProxy> message_loop_proxy_; MockConnectionToClientEventHandler handler_; MockSignalStrategy signal_strategy_; scoped_ptr<DesktopEnvironment> desktop_environment_; scoped_ptr<It2MeHostUserInterface> it2me_host_user_interface_; scoped_refptr<ChromotingHost> host_; MockChromotingHostContext context_; MockConnectionToClient* connection_; scoped_ptr<MockConnectionToClient> owned_connection_; ClientSession* client_; std::string session_jid_; MockSession* session_; // Owned by |connection_|. SessionConfig session_config_; MockVideoStub video_stub_; MockClientStub client_stub_; MockHostStub host_stub_; MockConnectionToClient* connection2_; scoped_ptr<MockConnectionToClient> owned_connection2_; ClientSession* client2_; std::string session2_jid_; MockSession* session2_; // Owned by |connection2_|. SessionConfig session_config2_; MockVideoStub video_stub2_; MockClientStub client_stub2_; MockHostStub host_stub2_; // Owned by |host_|. MockDisconnectWindow* disconnect_window_; MockContinueWindow* continue_window_; MockLocalInputMonitor* local_input_monitor_; }; TEST_F(ChromotingHostTest, DISABLED_StartAndShutdown) { host_->Start(); message_loop_.PostTask( FROM_HERE, base::Bind( &ChromotingHost::Shutdown, host_.get(), base::Bind(&PostQuitTask, &message_loop_))); message_loop_.Run(); } TEST_F(ChromotingHostTest, DISABLED_Connect) { host_->Start(); // When the video packet is received we first shutdown ChromotingHost // then execute the done task. { InSequence s; EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()); EXPECT_CALL(*connection_, Disconnect()) .RetiresOnSaturation(); } SimulateClientConnection(0, true); message_loop_.Run(); } TEST_F(ChromotingHostTest, DISABLED_Reconnect) { host_->Start(); // When the video packet is received we first disconnect the mock // connection. { InSequence s; EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs(this, &ChromotingHostTest::RemoveClientSession), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()); } // If Disconnect() is called we can break the main message loop. EXPECT_CALL(*connection_, Disconnect()) .WillOnce(QuitMainMessageLoop(&message_loop_)) .RetiresOnSaturation(); SimulateClientConnection(0, true); message_loop_.Run(); // Connect the client again. { InSequence s; EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()); } EXPECT_CALL(*connection_, Disconnect()) .RetiresOnSaturation(); SimulateClientConnection(0, true); message_loop_.Run(); } TEST_F(ChromotingHostTest, DISABLED_ConnectTwice) { host_->Start(); // When a video packet is received we connect the second mock // connection. { InSequence s; EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs( CreateFunctor( this, &ChromotingHostTest::SimulateClientConnection, 1, true)), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()); EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()); } EXPECT_CALL(*connection_, Disconnect()) .RetiresOnSaturation(); EXPECT_CALL(*connection2_, Disconnect()) .RetiresOnSaturation(); SimulateClientConnection(0, true); message_loop_.Run(); } } // namespace remoting <commit_msg>[Chromoting] Re-enable ChromotingHost unit tests.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop_proxy.h" #include "remoting/jingle_glue/mock_objects.h" #include "remoting/host/capturer_fake.h" #include "remoting/host/chromoting_host.h" #include "remoting/host/chromoting_host_context.h" #include "remoting/host/host_mock_objects.h" #include "remoting/host/it2me_host_user_interface.h" #include "remoting/proto/video.pb.h" #include "remoting/protocol/protocol_mock_objects.h" #include "remoting/protocol/session_config.h" #include "testing/gmock_mutant.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::remoting::protocol::MockClientStub; using ::remoting::protocol::MockConnectionToClient; using ::remoting::protocol::MockConnectionToClientEventHandler; using ::remoting::protocol::MockHostStub; using ::remoting::protocol::MockSession; using ::remoting::protocol::MockVideoStub; using ::remoting::protocol::SessionConfig; using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::CreateFunctor; using testing::DeleteArg; using testing::DoAll; using testing::InSequence; using testing::InvokeArgument; using testing::InvokeWithoutArgs; using testing::Return; using testing::ReturnRef; using testing::Sequence; namespace remoting { namespace { void PostQuitTask(MessageLoop* message_loop) { message_loop->PostTask(FROM_HERE, MessageLoop::QuitClosure()); } // Run the task and delete it afterwards. This action is used to deal with // done callbacks. ACTION(RunDoneTask) { arg1.Run(); } } // namespace class ChromotingHostTest : public testing::Test { public: ChromotingHostTest() { } virtual void SetUp() OVERRIDE { message_loop_proxy_ = base::MessageLoopProxy::current(); ON_CALL(context_, main_message_loop()) .WillByDefault(Return(&message_loop_)); ON_CALL(context_, encode_message_loop()) .WillByDefault(Return(&message_loop_)); ON_CALL(context_, network_message_loop()) .WillByDefault(Return(message_loop_proxy_.get())); ON_CALL(context_, ui_message_loop()) .WillByDefault(Return(message_loop_proxy_.get())); EXPECT_CALL(context_, main_message_loop()) .Times(AnyNumber()); EXPECT_CALL(context_, encode_message_loop()) .Times(AnyNumber()); EXPECT_CALL(context_, network_message_loop()) .Times(AnyNumber()); EXPECT_CALL(context_, ui_message_loop()) .Times(AnyNumber()); scoped_ptr<Capturer> capturer(new CapturerFake()); event_executor_ = new MockEventExecutor(); desktop_environment_ = DesktopEnvironment::CreateFake( &context_, capturer.Pass(), scoped_ptr<EventExecutor>(event_executor_)); session_manager_ = new protocol::MockSessionManager(); host_ = new ChromotingHost( &context_, &signal_strategy_, desktop_environment_.get(), scoped_ptr<protocol::SessionManager>(session_manager_)); disconnect_window_ = new MockDisconnectWindow(); continue_window_ = new MockContinueWindow(); local_input_monitor_ = new MockLocalInputMonitor(); it2me_host_user_interface_.reset(new It2MeHostUserInterface(&context_)); it2me_host_user_interface_->StartForTest( host_, base::Bind(&ChromotingHost::Shutdown, host_, base::Closure()), scoped_ptr<DisconnectWindow>(disconnect_window_), scoped_ptr<ContinueWindow>(continue_window_), scoped_ptr<LocalInputMonitor>(local_input_monitor_)); session_ = new MockSession(); session2_ = new MockSession(); session_config_ = SessionConfig::GetDefault(); session_jid_ = "user@domain/rest-of-jid"; session_config2_ = SessionConfig::GetDefault(); session2_jid_ = "user2@domain/rest-of-jid"; EXPECT_CALL(*session_, jid()) .WillRepeatedly(ReturnRef(session_jid_)); EXPECT_CALL(*session2_, jid()) .WillRepeatedly(ReturnRef(session2_jid_)); EXPECT_CALL(*session_, SetStateChangeCallback(_)) .Times(AnyNumber()); EXPECT_CALL(*session2_, SetStateChangeCallback(_)) .Times(AnyNumber()); EXPECT_CALL(*session_, SetRouteChangeCallback(_)) .Times(AnyNumber()); EXPECT_CALL(*session2_, SetRouteChangeCallback(_)) .Times(AnyNumber()); EXPECT_CALL(*session_, config()) .WillRepeatedly(ReturnRef(session_config_)); EXPECT_CALL(*session2_, config()) .WillRepeatedly(ReturnRef(session_config2_)); EXPECT_CALL(*session_, Close()) .Times(AnyNumber()); EXPECT_CALL(*session2_, Close()) .Times(AnyNumber()); owned_connection_.reset(new MockConnectionToClient( session_, &host_stub_, desktop_environment_->event_executor())); connection_ = owned_connection_.get(); owned_connection2_.reset(new MockConnectionToClient( session2_, &host_stub2_, desktop_environment_->event_executor())); connection2_ = owned_connection2_.get(); ON_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillByDefault(DeleteArg<0>()); ON_CALL(video_stub2_, ProcessVideoPacketPtr(_, _)) .WillByDefault(DeleteArg<0>()); ON_CALL(*connection_, video_stub()) .WillByDefault(Return(&video_stub_)); ON_CALL(*connection_, client_stub()) .WillByDefault(Return(&client_stub_)); ON_CALL(*connection_, session()) .WillByDefault(Return(session_)); ON_CALL(*connection2_, video_stub()) .WillByDefault(Return(&video_stub2_)); ON_CALL(*connection2_, client_stub()) .WillByDefault(Return(&client_stub2_)); ON_CALL(*connection2_, session()) .WillByDefault(Return(session2_)); EXPECT_CALL(*connection_, video_stub()) .Times(AnyNumber()); EXPECT_CALL(*connection_, client_stub()) .Times(AnyNumber()); EXPECT_CALL(*connection_, session()) .Times(AnyNumber()); EXPECT_CALL(*connection2_, video_stub()) .Times(AnyNumber()); EXPECT_CALL(*connection2_, client_stub()) .Times(AnyNumber()); EXPECT_CALL(*connection2_, session()) .Times(AnyNumber()); } // Helper method to pretend a client is connected to ChromotingHost. void SimulateClientConnection(int connection_index, bool authenticate) { scoped_ptr<protocol::ConnectionToClient> connection = ((connection_index == 0) ? owned_connection_ : owned_connection2_). PassAs<protocol::ConnectionToClient>(); protocol::ConnectionToClient* connection_ptr = connection.get(); ClientSession* client = new ClientSession( host_.get(), connection.Pass(), desktop_environment_->event_executor(), desktop_environment_->capturer()); connection_ptr->set_host_stub(client); context_.network_message_loop()->PostTask( FROM_HERE, base::Bind(&ChromotingHostTest::AddClientToHost, host_, client)); if (authenticate) { context_.network_message_loop()->PostTask( FROM_HERE, base::Bind(&ClientSession::OnConnectionAuthenticated, base::Unretained(client), connection_ptr)); context_.network_message_loop()->PostTask( FROM_HERE, base::Bind(&ClientSession::OnConnectionChannelsConnected, base::Unretained(client), connection_ptr)); } if (connection_index == 0) { client_ = client; } else { client2_ = client; } } // Helper method to remove a client connection from ChromotingHost. void RemoveClientSession() { client_->OnConnectionClosed(connection_, protocol::OK); } // Notify |host_| that |client_| has closed. void ClientSessionClosed() { host_->OnSessionClosed(client_); } // Notify |host_| that |client2_| has closed. void ClientSession2Closed() { host_->OnSessionClosed(client2_); } static void AddClientToHost(scoped_refptr<ChromotingHost> host, ClientSession* session) { host->clients_.push_back(session); } void ShutdownHost() { message_loop_.PostTask( FROM_HERE, base::Bind(&ChromotingHost::Shutdown, host_, base::Bind(&PostQuitTask, &message_loop_))); } void QuitMainMessageLoop() { PostQuitTask(&message_loop_); } protected: MessageLoop message_loop_; scoped_refptr<base::MessageLoopProxy> message_loop_proxy_; MockConnectionToClientEventHandler handler_; MockSignalStrategy signal_strategy_; MockEventExecutor* event_executor_; scoped_ptr<DesktopEnvironment> desktop_environment_; scoped_ptr<It2MeHostUserInterface> it2me_host_user_interface_; scoped_refptr<ChromotingHost> host_; MockChromotingHostContext context_; protocol::MockSessionManager* session_manager_; MockConnectionToClient* connection_; scoped_ptr<MockConnectionToClient> owned_connection_; ClientSession* client_; std::string session_jid_; MockSession* session_; // Owned by |connection_|. SessionConfig session_config_; MockVideoStub video_stub_; MockClientStub client_stub_; MockHostStub host_stub_; MockConnectionToClient* connection2_; scoped_ptr<MockConnectionToClient> owned_connection2_; ClientSession* client2_; std::string session2_jid_; MockSession* session2_; // Owned by |connection2_|. SessionConfig session_config2_; MockVideoStub video_stub2_; MockClientStub client_stub2_; MockHostStub host_stub2_; // Owned by |host_|. MockDisconnectWindow* disconnect_window_; MockContinueWindow* continue_window_; MockLocalInputMonitor* local_input_monitor_; }; TEST_F(ChromotingHostTest, StartAndShutdown) { EXPECT_CALL(*session_manager_, Init(_, host_.get())); EXPECT_CALL(*disconnect_window_, Hide()); EXPECT_CALL(*continue_window_, Hide()); host_->Start(); message_loop_.PostTask( FROM_HERE, base::Bind( &ChromotingHost::Shutdown, host_.get(), base::Bind(&PostQuitTask, &message_loop_))); message_loop_.Run(); } TEST_F(ChromotingHostTest, Connect) { EXPECT_CALL(*session_manager_, Init(_, host_.get())); EXPECT_CALL(*disconnect_window_, Hide()); EXPECT_CALL(*continue_window_, Hide()); host_->Start(); // When the video packet is received we first shut down ChromotingHost, // then execute the done task. { InSequence s; EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()) .WillRepeatedly(RunDoneTask()); EXPECT_CALL(*connection_, Disconnect()) .WillOnce( InvokeWithoutArgs(this, &ChromotingHostTest::ClientSessionClosed)) .RetiresOnSaturation(); EXPECT_CALL(*event_executor_, OnSessionFinished()); } SimulateClientConnection(0, true); message_loop_.Run(); } TEST_F(ChromotingHostTest, Reconnect) { EXPECT_CALL(*session_manager_, Init(_, host_.get())); EXPECT_CALL(*disconnect_window_, Hide()); EXPECT_CALL(*continue_window_, Hide()); host_->Start(); // When the video packet is received we first disconnect the mock // connection, then run the done task, then quit the message loop. { InSequence s; EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs(this, &ChromotingHostTest::RemoveClientSession), RunDoneTask(), InvokeWithoutArgs(this, &ChromotingHostTest::QuitMainMessageLoop))) .RetiresOnSaturation(); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()) .WillRepeatedly(RunDoneTask()); EXPECT_CALL(*event_executor_, OnSessionFinished()); } SimulateClientConnection(0, true); message_loop_.Run(); // Connect the second client. { InSequence s; EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()) .WillRepeatedly(RunDoneTask()); EXPECT_CALL(*connection2_, Disconnect()) .WillOnce( InvokeWithoutArgs(this, &ChromotingHostTest::ClientSession2Closed)) .RetiresOnSaturation(); EXPECT_CALL(*event_executor_, OnSessionFinished()); } SimulateClientConnection(1, true); message_loop_.Run(); } TEST_F(ChromotingHostTest, ConnectWhenAnotherClientIsConnected) { EXPECT_CALL(*session_manager_, Init(_, host_.get())); EXPECT_CALL(*disconnect_window_, Hide()); EXPECT_CALL(*continue_window_, Hide()); host_->Start(); // When a video packet is received we connect the second mock // connection. { InSequence s; EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs( CreateFunctor( this, &ChromotingHostTest::SimulateClientConnection, 1, true)), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(*disconnect_window_, Show(_, _, _)) .Times(0); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()) .WillRepeatedly(RunDoneTask()); EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _)) .WillOnce(DoAll( InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost), RunDoneTask())) .RetiresOnSaturation(); EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _)) .Times(AnyNumber()) .WillRepeatedly(RunDoneTask()); } EXPECT_CALL(*connection_, Disconnect()) .WillOnce( InvokeWithoutArgs(this, &ChromotingHostTest::ClientSessionClosed)) .RetiresOnSaturation(); EXPECT_CALL(*connection2_, Disconnect()) .WillOnce( InvokeWithoutArgs(this, &ChromotingHostTest::ClientSession2Closed)) .RetiresOnSaturation(); EXPECT_CALL(*event_executor_, OnSessionFinished()).Times(2); SimulateClientConnection(0, true); message_loop_.Run(); } } // namespace remoting <|endoftext|>
<commit_before>/* * ccookies.hpp * * Created on: 19.11.2014 * Author: andreas */ #ifndef CCOOKIES_HPP_ #define CCOOKIES_HPP_ #include <inttypes.h> #include <rofl/common/crofdpt.h> #include <rofl/common/cauxid.h> #include <rofl/common/crandom.h> #include <rofl/common/openflow/messages/cofmsg_packet_in.h> #include <rofl/common/openflow/messages/cofmsg_flow_removed.h> #include "roflibs/netlink/clogging.hpp" namespace roflibs { namespace common { namespace openflow { class ccookiebox; // forward declaration, see below class ccookie_owner { public: /** * */ virtual ~ccookie_owner(); public: /** * */ uint64_t acquire_cookie(); /** * */ void release_cookie(uint64_t cookie); protected: friend class ccookiebox; /** * */ virtual void handle_packet_in( rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) = 0; /** * */ virtual void handle_flow_removed( rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) = 0; }; class ccookie_find_by_owner { ccookie_owner* owner; public: ccookie_find_by_owner(ccookie_owner* owner) : owner(owner) {}; bool operator() (const std::pair<uint64_t, ccookie_owner*>& p) { return (p.second == owner); }; }; class ccookiebox { private: static ccookiebox* cookiebox; uint64_t next_cookie; std::map<uint64_t, ccookie_owner*> cookiestore; ccookiebox() : next_cookie(rofl::crandom(8).uint64()) {}; ~ccookiebox() {}; public: /** * */ static ccookiebox& get_instance() { if ((ccookiebox*)0 == ccookiebox::cookiebox) { ccookiebox::cookiebox = new ccookiebox(); } return *(ccookiebox::cookiebox); }; /** * */ void handle_packet_in( rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) { if (cookiestore.find(msg.get_cookie()) == cookiestore.end()) { rofcore::logging::debug << "[ccookiebox][handle_packet_in] cookie: 0x" << std::hex << (unsigned long long)msg.get_cookie() << std::dec << " not found, dropping packet" << std::endl; return; } cookiestore[msg.get_cookie()]->handle_packet_in(dpt, auxid, msg); }; /** * */ void handle_flow_removed( rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) { if (cookiestore.find(msg.get_cookie()) == cookiestore.end()) { rofcore::logging::debug << "[ccookiebox][handle_flow_removed] cookie: 0x" << std::hex << (unsigned long long)msg.get_cookie() << std::dec << " not found, dropping packet" << std::endl; return; } cookiestore[msg.get_cookie()]->handle_flow_removed(dpt, auxid, msg); }; private: friend class ccookie_owner; /** * */ void deregister_cookie_owner(ccookie_owner* owner) { std::map<uint64_t, ccookie_owner*>::iterator it; while ((it = find_if(cookiestore.begin(), cookiestore.end(), ccookie_find_by_owner(owner))) != cookiestore.end()) { cookiestore.erase(it); } }; /** * */ uint64_t acquire_cookie(ccookie_owner* owner) { do { next_cookie++; } while (cookiestore.find(next_cookie) != cookiestore.end()); cookiestore[next_cookie] = owner; return next_cookie; }; /** * */ void release_cookie(ccookie_owner* owner, uint64_t cookie) { if (cookiestore.find(cookie) == cookiestore.end()) { return; } if (cookiestore[cookie] != owner) { return; } cookiestore.erase(cookie); }; }; }; // end of namespace openflow }; // end of namespace common }; // end of namespace roflibs #endif /* CCOOKIES_HPP_ */ <commit_msg>ccookiebox => added output operator<commit_after>/* * ccookies.hpp * * Created on: 19.11.2014 * Author: andreas */ #ifndef CCOOKIES_HPP_ #define CCOOKIES_HPP_ #include <inttypes.h> #include <ostream> #include <rofl/common/crofdpt.h> #include <rofl/common/cauxid.h> #include <rofl/common/crandom.h> #include <rofl/common/openflow/messages/cofmsg_packet_in.h> #include <rofl/common/openflow/messages/cofmsg_flow_removed.h> #include "roflibs/netlink/clogging.hpp" namespace roflibs { namespace common { namespace openflow { class ccookiebox; // forward declaration, see below class ccookie_owner { public: /** * */ virtual ~ccookie_owner(); public: /** * */ uint64_t acquire_cookie(); /** * */ void release_cookie(uint64_t cookie); protected: friend class ccookiebox; /** * */ virtual void handle_packet_in( rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) = 0; /** * */ virtual void handle_flow_removed( rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) = 0; }; class ccookie_find_by_owner { ccookie_owner* owner; public: ccookie_find_by_owner(ccookie_owner* owner) : owner(owner) {}; bool operator() (const std::pair<uint64_t, ccookie_owner*>& p) { return (p.second == owner); }; }; class ccookiebox { private: static ccookiebox* cookiebox; uint64_t next_cookie; std::map<uint64_t, ccookie_owner*> cookiestore; ccookiebox() : next_cookie(rofl::crandom(8).uint64()) {}; ~ccookiebox() {}; public: /** * */ static ccookiebox& get_instance() { if ((ccookiebox*)0 == ccookiebox::cookiebox) { ccookiebox::cookiebox = new ccookiebox(); } return *(ccookiebox::cookiebox); }; /** * */ void handle_packet_in( rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) { if (cookiestore.find(msg.get_cookie()) == cookiestore.end()) { rofcore::logging::debug << "[ccookiebox][handle_packet_in] cookie: 0x" << std::hex << (unsigned long long)msg.get_cookie() << std::dec << " not found, dropping packet" << std::endl << *this; return; } cookiestore[msg.get_cookie()]->handle_packet_in(dpt, auxid, msg); }; /** * */ void handle_flow_removed( rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) { if (cookiestore.find(msg.get_cookie()) == cookiestore.end()) { rofcore::logging::debug << "[ccookiebox][handle_flow_removed] cookie: 0x" << std::hex << (unsigned long long)msg.get_cookie() << std::dec << " not found, dropping packet" << std::endl << *this; return; } cookiestore[msg.get_cookie()]->handle_flow_removed(dpt, auxid, msg); }; private: friend class ccookie_owner; /** * */ void deregister_cookie_owner(ccookie_owner* owner) { std::map<uint64_t, ccookie_owner*>::iterator it; while ((it = find_if(cookiestore.begin(), cookiestore.end(), ccookie_find_by_owner(owner))) != cookiestore.end()) { cookiestore.erase(it); } }; /** * */ uint64_t acquire_cookie(ccookie_owner* owner) { do { next_cookie++; } while (cookiestore.find(next_cookie) != cookiestore.end()); cookiestore[next_cookie] = owner; return next_cookie; }; /** * */ void release_cookie(ccookie_owner* owner, uint64_t cookie) { if (cookiestore.find(cookie) == cookiestore.end()) { return; } if (cookiestore[cookie] != owner) { return; } cookiestore.erase(cookie); }; public: friend std::ostream& operator<< (std::ostream& os, const ccookiebox& box) { os << rofcore::indent(0) << "<ccookiebox >" << std::endl; for (std::map<uint64_t, ccookie_owner*>::const_iterator it = box.cookiestore.begin(); it != box.cookiestore.end(); ++it) { os << rofcore::indent(2) << "cookie: 0x" << std::hex << (unsigned long long)it->first << std::dec << " => 0x" << std::hex << (unsigned long)it->second << std::dec << std::endl; } return os; }; }; }; // end of namespace openflow }; // end of namespace common }; // end of namespace roflibs #endif /* CCOOKIES_HPP_ */ <|endoftext|>
<commit_before>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http ://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "charpackets.h" #include "components/inventory.h" RoseCommon::SrvCharacterListReply::char_info::char_info( const std::string &name, uint8_t race /*= 0*/, uint16_t level /*= 0*/, uint16_t job /*= 0*/, uint32_t delete_time /*= 0*/, uint8_t platinum /*= 0*/, uint32_t face, uint32_t hair) : remain_sec_unitl_delete_(delete_time), level_(level), job_(job), race_(race), platinum_(platinum), name_(name), face_(face), hair_(hair) {} RoseCommon::SrvCharacterListReply::equip_item::equip_item( uint16_t id /*= 0*/, uint16_t gem /*= 0*/, uint8_t socket /*= 0*/, uint8_t grade /*= 0*/) : id_(id), gem_op_(gem), socket_(socket), grade_(grade) {} RoseCommon::SrvCharacterListReply::SrvCharacterListReply() : CRosePacket(ePacketType::PAKCC_CHAR_LIST_REPLY), character_count_(0) {} RoseCommon::SrvCharacterListReply::~SrvCharacterListReply() {} void RoseCommon::SrvCharacterListReply::addCharacter( const std::string &name, uint8_t race, uint16_t level, uint16_t job, uint32_t face, uint32_t hair, uint32_t delete_time /*= 0*/) { ++character_count_; char_info character(name, race, level, job, delete_time, false, face, hair); character_list_.push_back(character); } RoseCommon::SrvCharacterListReply::equipped_position RoseCommon::SrvCharacterListReply::getPosition(uint32_t slot) { using equipped_position = RoseCommon::SrvCharacterListReply::equipped_position; switch (slot) { case Inventory::GOGGLES: return equipped_position::EQUIP_GOGGLES; case Inventory::HELMET: return equipped_position::EQUIP_HELMET; case Inventory::ARMOR: return equipped_position::EQUIP_ARMOR; case Inventory::BACKPACK: return equipped_position::EQUIP_BACKPACK; case Inventory::GAUNTLET: return equipped_position::EQUIP_GAUNTLET; case Inventory::BOOTS: return equipped_position::EQUIP_BOOTS; case Inventory::WEAPON_R: return equipped_position::EQUIP_WEAPON_R; case Inventory::WEAPON_L: return equipped_position::EQUIP_WEAPON_L; } return equipped_position::EQUIP_WEAPON_R; } #include <iostream> void RoseCommon::SrvCharacterListReply::addEquipItem( uint8_t char_id, uint8_t slot, uint16_t item_id /*= 0*/, uint16_t gem /*= 0*/, uint8_t socket /*= 0*/, uint8_t grade /*= 0*/) { if (char_id < character_count_ && slot < MAX_EQUIPPED_ITEMS) { std::cout << "adding item " << (int)item_id << " to slot " << (int)slot << std::endl; equip_item item = character_list_[char_id].items_[slot]; item.id_ = item_id; item.gem_op_ = gem; item.socket_ = socket; item.grade_ = grade; character_list_[char_id].items_[slot] = item; } } void RoseCommon::SrvCharacterListReply::pack() { *this << character_count_; for (auto &character : character_list_) { *this << character.name_; *this << character.race_ << character.level_ << character.job_ << character.remain_sec_unitl_delete_ << character.platinum_; *this << character.face_ << character.hair_; for (int i = 0; i < MAX_EQUIPPED_ITEMS; ++i) { *this << character.items_[i].data; } } } <commit_msg>Removed debug<commit_after>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http ://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "charpackets.h" #include "components/inventory.h" RoseCommon::SrvCharacterListReply::char_info::char_info( const std::string &name, uint8_t race /*= 0*/, uint16_t level /*= 0*/, uint16_t job /*= 0*/, uint32_t delete_time /*= 0*/, uint8_t platinum /*= 0*/, uint32_t face, uint32_t hair) : remain_sec_unitl_delete_(delete_time), level_(level), job_(job), race_(race), platinum_(platinum), name_(name), face_(face), hair_(hair) {} RoseCommon::SrvCharacterListReply::equip_item::equip_item( uint16_t id /*= 0*/, uint16_t gem /*= 0*/, uint8_t socket /*= 0*/, uint8_t grade /*= 0*/) : id_(id), gem_op_(gem), socket_(socket), grade_(grade) {} RoseCommon::SrvCharacterListReply::SrvCharacterListReply() : CRosePacket(ePacketType::PAKCC_CHAR_LIST_REPLY), character_count_(0) {} RoseCommon::SrvCharacterListReply::~SrvCharacterListReply() {} void RoseCommon::SrvCharacterListReply::addCharacter( const std::string &name, uint8_t race, uint16_t level, uint16_t job, uint32_t face, uint32_t hair, uint32_t delete_time /*= 0*/) { ++character_count_; char_info character(name, race, level, job, delete_time, false, face, hair); character_list_.push_back(character); } RoseCommon::SrvCharacterListReply::equipped_position RoseCommon::SrvCharacterListReply::getPosition(uint32_t slot) { using equipped_position = RoseCommon::SrvCharacterListReply::equipped_position; switch (slot) { case Inventory::GOGGLES: return equipped_position::EQUIP_GOGGLES; case Inventory::HELMET: return equipped_position::EQUIP_HELMET; case Inventory::ARMOR: return equipped_position::EQUIP_ARMOR; case Inventory::BACKPACK: return equipped_position::EQUIP_BACKPACK; case Inventory::GAUNTLET: return equipped_position::EQUIP_GAUNTLET; case Inventory::BOOTS: return equipped_position::EQUIP_BOOTS; case Inventory::WEAPON_R: return equipped_position::EQUIP_WEAPON_R; case Inventory::WEAPON_L: return equipped_position::EQUIP_WEAPON_L; } return equipped_position::EQUIP_WEAPON_R; } void RoseCommon::SrvCharacterListReply::addEquipItem( uint8_t char_id, uint8_t slot, uint16_t item_id /*= 0*/, uint16_t gem /*= 0*/, uint8_t socket /*= 0*/, uint8_t grade /*= 0*/) { if (char_id < character_count_ && slot < MAX_EQUIPPED_ITEMS) { equip_item item = character_list_[char_id].items_[slot]; item.id_ = item_id; item.gem_op_ = gem; item.socket_ = socket; item.grade_ = grade; character_list_[char_id].items_[slot] = item; } } void RoseCommon::SrvCharacterListReply::pack() { *this << character_count_; for (auto &character : character_list_) { *this << character.name_; *this << character.race_ << character.level_ << character.job_ << character.remain_sec_unitl_delete_ << character.platinum_; *this << character.face_ << character.hair_; for (int i = 0; i < MAX_EQUIPPED_ITEMS; ++i) { *this << character.items_[i].data; } } } <|endoftext|>
<commit_before>/* Copyright (c) 2017-2018 Andrew Depke */ #include "BSDSocket.h" #if OS_WINDOWS #pragma comment(lib, "Ws2_32.lib") #include <Ws2tcpip.h> #include <memory> #define RED_INVALID_SOCKET INVALID_SOCKET #else #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/ioctl.h> #include <string.h> // memset() #define RED_INVALID_SOCKET -1 #endif namespace Red { bool BSDSocket::Initialize(const SocketDescription& InDescription) { Description = InDescription; int NativeType = 0; int NativeProtocol = 0; switch (InDescription.Protocol) { case SP_TCP: NativeType = SOCK_STREAM; NativeProtocol = IPPROTO_TCP; break; case SP_UDP: NativeType = SOCK_DGRAM; NativeProtocol = IPPROTO_UDP; break; case SP_IGMP: NativeType = SOCK_DGRAM; NativeProtocol = IPPROTO_IP; // Automatically Determine Protocol break; } SocketHandle = socket(AF_INET, NativeType, NativeProtocol); if (SocketHandle == RED_INVALID_SOCKET) { return false; } return Configure(); } bool BSDSocket::Shutdown() { bool Result = false; if (SocketHandle != RED_INVALID_SOCKET) { shutdown(SocketHandle, 2); // SHUT_RDWR #if OS_WINDOWS Result = (closesocket(SocketHandle) == 0); #else Result = (close(SocketHandle) == 0); #endif SocketHandle = RED_INVALID_SOCKET; } return Result; } bool BSDSocket::Connect(const IP4EndPoint& EndPoint) { if (SocketHandle != RED_INVALID_SOCKET) { sockaddr_in SocketAddress; SocketAddress.sin_family = AF_INET; SocketAddress.sin_addr.s_addr = htonl(EndPoint.Address.Address); SocketAddress.sin_port = htons(EndPoint.Port); if (connect(SocketHandle, (sockaddr*)&SocketAddress, sizeof(SocketAddress)) == 0) { return true; } } return false; } AsyncTask* BSDSocket::ConnectAsync(AsyncConnectArgs* Args, const IP4EndPoint& EndPoint) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { Args->Result.store(Connect(EndPoint)); Args->CompletedCallback(Args); }), this); return Task; } bool BSDSocket::Bind(unsigned short Port) { if (SocketHandle != RED_INVALID_SOCKET) { sockaddr_in SocketAddress; #if OS_WINDOWS std::memset(&SocketAddress, 0, sizeof(SocketAddress)); #else memset(&SocketAddress, 0, sizeof(SocketAddress)); #endif SocketAddress.sin_family = AF_INET; SocketAddress.sin_addr.s_addr = INADDR_ANY; // Automatically determine the private IP. SocketAddress.sin_port = htons(Port); if (bind(SocketHandle, (sockaddr*)&SocketAddress, sizeof(SocketAddress)) == 0) { return true; } } return false; } bool BSDSocket::Listen(int MaxBacklog) { if (SocketHandle != RED_INVALID_SOCKET) { if (listen(SocketHandle, MaxBacklog) == 0) { return true; } } return false; } ISocket* BSDSocket::Accept(IP4EndPoint& ClientAddress) { SOCKET ClientHandle; sockaddr_in SocketAddress; int SizeSmall = sizeof(SocketAddress); #if OS_WINDOWS ClientHandle = accept(SocketHandle, (sockaddr*)&SocketAddress, &SizeSmall); #else ClientHandle = accept(SocketHandle, (sockaddr*)&SocketAddress, (socklen_t*)&SizeSmall); #endif if (ClientHandle != RED_INVALID_SOCKET) { if (getpeername(ClientHandle, (sockaddr*)&SocketAddress, (socklen_t*)&SizeSmall) == 0) { BSDSocket* ClientSocket = new BSDSocket(); // Do not Initialize(), as that will allocate a separate socket. ClientSocket->SocketHandle = ClientHandle; ClientSocket->Description = Description; ClientSocket->Description.Type = ST_Client; ClientSocket->Configure(); ClientAddress = IP4EndPoint(ntohl(SocketAddress.sin_addr.s_addr), ntohs(SocketAddress.sin_port)); return ClientSocket; } // Manually kill the created socket. #if OS_WINDOWS closesocket(ClientHandle); #else close(ClientHandle); #endif } return nullptr; } AsyncTask* BSDSocket::AcceptAsync(AsyncAcceptArgs* Args) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { IP4EndPoint ClientAddressTemp; Args->Result.store(Accept(ClientAddressTemp)); Args->ClientAddress.store(ClientAddressTemp); Args->CompletedCallback(Args); }), this); return Task; } bool BSDSocket::Send(const unsigned char* Data, unsigned int Length, int& BytesSent) { BytesSent = send(SocketHandle, (const char*)Data, Length, 0); return BytesSent >= 0; } bool BSDSocket::Send(const IP4EndPoint& Destination, const unsigned char* Data, unsigned int Length, int& BytesSent) { sockaddr_in SocketAddress; SocketAddress.sin_family = AF_INET; SocketAddress.sin_addr.s_addr = htonl(Destination.Address.Address); SocketAddress.sin_port = htons(Destination.Port); BytesSent = sendto(SocketHandle, (const char*)Data, Length, 0, (sockaddr*)&SocketAddress, sizeof(SocketAddress)); return BytesSent >= 0; } AsyncTask* BSDSocket::SendAsync(AsyncSendArgs* Args, const unsigned char* Data, unsigned int Length) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { int BytesSentTemp; Args->Result.store(Send(Data, Length, BytesSentTemp)); Args->BytesSent.store(BytesSentTemp); Args->CompletedCallback(Args); }), this); return Task; } AsyncTask* BSDSocket::SendAsync(AsyncSendArgs* Args, const IP4EndPoint& Destination, const unsigned char* Data, unsigned int Length) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { int BytesSentTemp; Args->Result.store(Send(Destination, Data, Length, BytesSentTemp)); Args->BytesSent.store(BytesSentTemp); Args->CompletedCallback(Args); }), this); return Task; } bool BSDSocket::Receive(unsigned char* Data, unsigned int MaxReceivingBytes, int& BytesReceived) { BytesReceived = recv(SocketHandle, (char*)Data, MaxReceivingBytes, 0); return BytesReceived >= 0; } bool BSDSocket::Receive(IP4Address& Source, unsigned char* Data, unsigned int MaxReceivingBytes, int& BytesReceived) { sockaddr_in ClientAddress; int Size = sizeof(ClientAddress); BytesReceived = recvfrom(SocketHandle, (char*)Data, MaxReceivingBytes, 0, (sockaddr*)&ClientAddress, (socklen_t*)&Size); Source.Address = ntohl(ClientAddress.sin_addr.s_addr); return BytesReceived >= 0; } AsyncTask* BSDSocket::ReceiveAsync(AsyncReceiveArgs* Args, unsigned int MaxReceivingBytes) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { unsigned char* DataTemp = nullptr; int BytesReceivedTemp; Args->Result.store(Receive(DataTemp, MaxReceivingBytes, BytesReceivedTemp)); Args->Data.store(DataTemp); Args->BytesReceived.store(BytesReceivedTemp); Args->CompletedCallback(Args); }), this); return Task; } AsyncTask* BSDSocket::ReceiveAsync(AsyncReceiveFromArgs* Args, unsigned int MaxReceivingBytes) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { unsigned char* DataTemp = nullptr; int BytesReceivedTemp; IP4Address SourceTemp; Args->Result.store(Receive(SourceTemp, DataTemp, MaxReceivingBytes, BytesReceivedTemp)); Args->Data.store(DataTemp); Args->BytesReceived.store(BytesReceivedTemp); Args->Source.store(SourceTemp); Args->CompletedCallback(Args); }), this); return Task; } bool BSDSocket::JoinMulticastGroup(const IP4Address& GroupAddress) { ip_mreq Mreq; Mreq.imr_interface.s_addr = INADDR_ANY; Mreq.imr_multiaddr.s_addr = GroupAddress.Address; return (setsockopt(SocketHandle, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&Mreq, sizeof(Mreq)) == 0); } bool BSDSocket::LeaveMulticastGroup(const IP4Address& GroupAddress) { ip_mreq Mreq; Mreq.imr_interface.s_addr = INADDR_ANY; Mreq.imr_multiaddr.s_addr = GroupAddress.Address; return (setsockopt(SocketHandle, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&Mreq, sizeof(Mreq)) == 0); } bool BSDSocket::SetSendBufferSize(unsigned int Size) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_SNDBUF, (char*)&Size, sizeof(Size)) == 0); } bool BSDSocket::SetReceiveBufferSize(unsigned int Size) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_RCVBUF, (char*)&Size, sizeof(Size)) == 0); } bool BSDSocket::SetSendTimeout(unsigned int TimeoutMs) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_SNDTIMEO, (char*)&TimeoutMs, sizeof(TimeoutMs)) == 0); } bool BSDSocket::SetReceiveTimeout(unsigned int TimeoutMs) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_RCVTIMEO, (char*)&TimeoutMs, sizeof(TimeoutMs)) == 0); } bool BSDSocket::SetBroadcastsEnabled(bool Value) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_BROADCAST, (char*)&Value, sizeof(Value)) == 0); } IP4EndPoint BSDSocket::GetAddress() { sockaddr_in Address; int Size = sizeof(Address); #if OS_WINDOWS if (getsockname(SocketHandle, (sockaddr*)&Address, &Size) == 0) #else if (getsockname(SocketHandle, (sockaddr*)&Address, (socklen_t*)&Size) == 0) #endif { return IP4EndPoint(ntohl(Address.sin_addr.s_addr), ntohs(Address.sin_port)); } return IP4EndPoint(); } IP4EndPoint BSDSocket::GetPeerAddress() { sockaddr_in Address; int Size = sizeof(Address); #if OS_WINDOWS if (getpeername(SocketHandle, (sockaddr*)&Address, &Size) == 0) #else if (getpeername(SocketHandle, (sockaddr*)&Address, (socklen_t*)&Size) == 0) #endif { return IP4EndPoint(ntohl(Address.sin_addr.s_addr), ntohs(Address.sin_port)); } return IP4EndPoint(); } bool BSDSocket::Configure() { int Value = 0; Value = 1; if ((Description.Protocol == SP_TCP) && (setsockopt(SocketHandle, IPPROTO_TCP, TCP_NODELAY, (char*)&Value, sizeof(Value)) != 0)) { Shutdown(); return false; } Value = 1; if ((Description.Protocol == SP_TCP) && (setsockopt(SocketHandle, SOL_SOCKET, SO_KEEPALIVE, (char*)&Value, sizeof(Value)) != 0)) { Shutdown(); return false; } Value = Description.ReuseAddress ? 1 : 0; if ((Description.Type == ST_Server) && (setsockopt(SocketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&Value, sizeof(Value)) != 0)) { Shutdown(); return false; } if (Description.Protocol == SP_TCP) { Value = 1; if (Description.LingerTimeMs > 0) { linger Linger; Linger.l_onoff = true; Linger.l_linger = Description.LingerTimeMs / 1000; if (setsockopt(SocketHandle, SOL_SOCKET, SO_LINGER, (char*)&Linger, sizeof(Linger)) != 0) { Shutdown(); return false; } } else { if (setsockopt(SocketHandle, SOL_SOCKET, ~SO_LINGER, (char*)&Value, sizeof(Value)) != 0) { Shutdown(); return false; } } } if (Description.Protocol == SP_IGMP) { // Disable Multicast Loopback Value = 1; if (setsockopt(SocketHandle, IPPROTO_IP, IP_MULTICAST_LOOP, (char*)&Value, sizeof(Value)) != 0) { Shutdown(); return false; } } return true; } } // namespace Red <commit_msg>Added SP_Unknown Case<commit_after>/* Copyright (c) 2017-2018 Andrew Depke */ #include "BSDSocket.h" #if OS_WINDOWS #pragma comment(lib, "Ws2_32.lib") #include <Ws2tcpip.h> #include <memory> #define RED_INVALID_SOCKET INVALID_SOCKET #else #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/ioctl.h> #include <string.h> // memset() #define RED_INVALID_SOCKET -1 #endif namespace Red { bool BSDSocket::Initialize(const SocketDescription& InDescription) { Description = InDescription; int NativeType = 0; int NativeProtocol = 0; switch (InDescription.Protocol) { case SP_TCP: NativeType = SOCK_STREAM; NativeProtocol = IPPROTO_TCP; break; case SP_UDP: NativeType = SOCK_DGRAM; NativeProtocol = IPPROTO_UDP; break; case SP_IGMP: NativeType = SOCK_DGRAM; NativeProtocol = IPPROTO_IP; // Automatically Determine Protocol break; default: NativeType = SOCK_RAW; NativeProtocol = IPPROTO_IP; break; } SocketHandle = socket(AF_INET, NativeType, NativeProtocol); if (SocketHandle == RED_INVALID_SOCKET) { return false; } return Configure(); } bool BSDSocket::Shutdown() { bool Result = false; if (SocketHandle != RED_INVALID_SOCKET) { shutdown(SocketHandle, 2); // SHUT_RDWR #if OS_WINDOWS Result = (closesocket(SocketHandle) == 0); #else Result = (close(SocketHandle) == 0); #endif SocketHandle = RED_INVALID_SOCKET; } return Result; } bool BSDSocket::Connect(const IP4EndPoint& EndPoint) { if (SocketHandle != RED_INVALID_SOCKET) { sockaddr_in SocketAddress; SocketAddress.sin_family = AF_INET; SocketAddress.sin_addr.s_addr = htonl(EndPoint.Address.Address); SocketAddress.sin_port = htons(EndPoint.Port); if (connect(SocketHandle, (sockaddr*)&SocketAddress, sizeof(SocketAddress)) == 0) { return true; } } return false; } AsyncTask* BSDSocket::ConnectAsync(AsyncConnectArgs* Args, const IP4EndPoint& EndPoint) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { Args->Result.store(Connect(EndPoint)); Args->CompletedCallback(Args); }), this); return Task; } bool BSDSocket::Bind(unsigned short Port) { if (SocketHandle != RED_INVALID_SOCKET) { sockaddr_in SocketAddress; #if OS_WINDOWS std::memset(&SocketAddress, 0, sizeof(SocketAddress)); #else memset(&SocketAddress, 0, sizeof(SocketAddress)); #endif SocketAddress.sin_family = AF_INET; SocketAddress.sin_addr.s_addr = INADDR_ANY; // Automatically determine the private IP. SocketAddress.sin_port = htons(Port); if (bind(SocketHandle, (sockaddr*)&SocketAddress, sizeof(SocketAddress)) == 0) { return true; } } return false; } bool BSDSocket::Listen(int MaxBacklog) { if (SocketHandle != RED_INVALID_SOCKET) { if (listen(SocketHandle, MaxBacklog) == 0) { return true; } } return false; } ISocket* BSDSocket::Accept(IP4EndPoint& ClientAddress) { SOCKET ClientHandle; sockaddr_in SocketAddress; int SizeSmall = sizeof(SocketAddress); #if OS_WINDOWS ClientHandle = accept(SocketHandle, (sockaddr*)&SocketAddress, &SizeSmall); #else ClientHandle = accept(SocketHandle, (sockaddr*)&SocketAddress, (socklen_t*)&SizeSmall); #endif if (ClientHandle != RED_INVALID_SOCKET) { if (getpeername(ClientHandle, (sockaddr*)&SocketAddress, (socklen_t*)&SizeSmall) == 0) { BSDSocket* ClientSocket = new BSDSocket(); // Do not Initialize(), as that will allocate a separate socket. ClientSocket->SocketHandle = ClientHandle; ClientSocket->Description = Description; ClientSocket->Description.Type = ST_Client; ClientSocket->Configure(); ClientAddress = IP4EndPoint(ntohl(SocketAddress.sin_addr.s_addr), ntohs(SocketAddress.sin_port)); return ClientSocket; } // Manually kill the created socket. #if OS_WINDOWS closesocket(ClientHandle); #else close(ClientHandle); #endif } return nullptr; } AsyncTask* BSDSocket::AcceptAsync(AsyncAcceptArgs* Args) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { IP4EndPoint ClientAddressTemp; Args->Result.store(Accept(ClientAddressTemp)); Args->ClientAddress.store(ClientAddressTemp); Args->CompletedCallback(Args); }), this); return Task; } bool BSDSocket::Send(const unsigned char* Data, unsigned int Length, int& BytesSent) { BytesSent = send(SocketHandle, (const char*)Data, Length, 0); return BytesSent >= 0; } bool BSDSocket::Send(const IP4EndPoint& Destination, const unsigned char* Data, unsigned int Length, int& BytesSent) { sockaddr_in SocketAddress; SocketAddress.sin_family = AF_INET; SocketAddress.sin_addr.s_addr = htonl(Destination.Address.Address); SocketAddress.sin_port = htons(Destination.Port); BytesSent = sendto(SocketHandle, (const char*)Data, Length, 0, (sockaddr*)&SocketAddress, sizeof(SocketAddress)); return BytesSent >= 0; } AsyncTask* BSDSocket::SendAsync(AsyncSendArgs* Args, const unsigned char* Data, unsigned int Length) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { int BytesSentTemp; Args->Result.store(Send(Data, Length, BytesSentTemp)); Args->BytesSent.store(BytesSentTemp); Args->CompletedCallback(Args); }), this); return Task; } AsyncTask* BSDSocket::SendAsync(AsyncSendArgs* Args, const IP4EndPoint& Destination, const unsigned char* Data, unsigned int Length) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { int BytesSentTemp; Args->Result.store(Send(Destination, Data, Length, BytesSentTemp)); Args->BytesSent.store(BytesSentTemp); Args->CompletedCallback(Args); }), this); return Task; } bool BSDSocket::Receive(unsigned char* Data, unsigned int MaxReceivingBytes, int& BytesReceived) { BytesReceived = recv(SocketHandle, (char*)Data, MaxReceivingBytes, 0); return BytesReceived >= 0; } bool BSDSocket::Receive(IP4Address& Source, unsigned char* Data, unsigned int MaxReceivingBytes, int& BytesReceived) { sockaddr_in ClientAddress; int Size = sizeof(ClientAddress); BytesReceived = recvfrom(SocketHandle, (char*)Data, MaxReceivingBytes, 0, (sockaddr*)&ClientAddress, (socklen_t*)&Size); Source.Address = ntohl(ClientAddress.sin_addr.s_addr); return BytesReceived >= 0; } AsyncTask* BSDSocket::ReceiveAsync(AsyncReceiveArgs* Args, unsigned int MaxReceivingBytes) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { unsigned char* DataTemp = nullptr; int BytesReceivedTemp; Args->Result.store(Receive(DataTemp, MaxReceivingBytes, BytesReceivedTemp)); Args->Data.store(DataTemp); Args->BytesReceived.store(BytesReceivedTemp); Args->CompletedCallback(Args); }), this); return Task; } AsyncTask* BSDSocket::ReceiveAsync(AsyncReceiveFromArgs* Args, unsigned int MaxReceivingBytes) { AsyncTask* Task = new AsyncTask(std::async(std::launch::async, [=] { unsigned char* DataTemp = nullptr; int BytesReceivedTemp; IP4Address SourceTemp; Args->Result.store(Receive(SourceTemp, DataTemp, MaxReceivingBytes, BytesReceivedTemp)); Args->Data.store(DataTemp); Args->BytesReceived.store(BytesReceivedTemp); Args->Source.store(SourceTemp); Args->CompletedCallback(Args); }), this); return Task; } bool BSDSocket::JoinMulticastGroup(const IP4Address& GroupAddress) { ip_mreq Mreq; Mreq.imr_interface.s_addr = INADDR_ANY; Mreq.imr_multiaddr.s_addr = GroupAddress.Address; return (setsockopt(SocketHandle, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&Mreq, sizeof(Mreq)) == 0); } bool BSDSocket::LeaveMulticastGroup(const IP4Address& GroupAddress) { ip_mreq Mreq; Mreq.imr_interface.s_addr = INADDR_ANY; Mreq.imr_multiaddr.s_addr = GroupAddress.Address; return (setsockopt(SocketHandle, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&Mreq, sizeof(Mreq)) == 0); } bool BSDSocket::SetSendBufferSize(unsigned int Size) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_SNDBUF, (char*)&Size, sizeof(Size)) == 0); } bool BSDSocket::SetReceiveBufferSize(unsigned int Size) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_RCVBUF, (char*)&Size, sizeof(Size)) == 0); } bool BSDSocket::SetSendTimeout(unsigned int TimeoutMs) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_SNDTIMEO, (char*)&TimeoutMs, sizeof(TimeoutMs)) == 0); } bool BSDSocket::SetReceiveTimeout(unsigned int TimeoutMs) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_RCVTIMEO, (char*)&TimeoutMs, sizeof(TimeoutMs)) == 0); } bool BSDSocket::SetBroadcastsEnabled(bool Value) { return (setsockopt(SocketHandle, SOL_SOCKET, SO_BROADCAST, (char*)&Value, sizeof(Value)) == 0); } IP4EndPoint BSDSocket::GetAddress() { sockaddr_in Address; int Size = sizeof(Address); #if OS_WINDOWS if (getsockname(SocketHandle, (sockaddr*)&Address, &Size) == 0) #else if (getsockname(SocketHandle, (sockaddr*)&Address, (socklen_t*)&Size) == 0) #endif { return IP4EndPoint(ntohl(Address.sin_addr.s_addr), ntohs(Address.sin_port)); } return IP4EndPoint(); } IP4EndPoint BSDSocket::GetPeerAddress() { sockaddr_in Address; int Size = sizeof(Address); #if OS_WINDOWS if (getpeername(SocketHandle, (sockaddr*)&Address, &Size) == 0) #else if (getpeername(SocketHandle, (sockaddr*)&Address, (socklen_t*)&Size) == 0) #endif { return IP4EndPoint(ntohl(Address.sin_addr.s_addr), ntohs(Address.sin_port)); } return IP4EndPoint(); } bool BSDSocket::Configure() { int Value = 0; Value = 1; if ((Description.Protocol == SP_TCP) && (setsockopt(SocketHandle, IPPROTO_TCP, TCP_NODELAY, (char*)&Value, sizeof(Value)) != 0)) { Shutdown(); return false; } Value = 1; if ((Description.Protocol == SP_TCP) && (setsockopt(SocketHandle, SOL_SOCKET, SO_KEEPALIVE, (char*)&Value, sizeof(Value)) != 0)) { Shutdown(); return false; } Value = Description.ReuseAddress ? 1 : 0; if ((Description.Type == ST_Server) && (setsockopt(SocketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&Value, sizeof(Value)) != 0)) { Shutdown(); return false; } if (Description.Protocol == SP_TCP) { Value = 1; if (Description.LingerTimeMs > 0) { linger Linger; Linger.l_onoff = true; Linger.l_linger = Description.LingerTimeMs / 1000; if (setsockopt(SocketHandle, SOL_SOCKET, SO_LINGER, (char*)&Linger, sizeof(Linger)) != 0) { Shutdown(); return false; } } else { if (setsockopt(SocketHandle, SOL_SOCKET, ~SO_LINGER, (char*)&Value, sizeof(Value)) != 0) { Shutdown(); return false; } } } if (Description.Protocol == SP_IGMP) { // Disable Multicast Loopback Value = 1; if (setsockopt(SocketHandle, IPPROTO_IP, IP_MULTICAST_LOOP, (char*)&Value, sizeof(Value)) != 0) { Shutdown(); return false; } } return true; } } // namespace Red <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <unotools/syslocale.hxx> #include <unotools/syslocaleoptions.hxx> #include <comphelper/processfactory.hxx> #include <rtl/tencinfo.h> #include <rtl/locale.h> #include <osl/nlsupport.h> #include <vector> using namespace osl; using namespace com::sun::star; SvtSysLocale_Impl* SvtSysLocale::pImpl = NULL; sal_Int32 SvtSysLocale::nRefCount = 0; class SvtSysLocale_Impl : public utl::ConfigurationListener { public: SvtSysLocaleOptions aSysLocaleOptions; LocaleDataWrapper* pLocaleData; CharClass* pCharClass; SvtSysLocale_Impl(); virtual ~SvtSysLocale_Impl(); CharClass* GetCharClass(); virtual void ConfigurationChanged( utl::ConfigurationBroadcaster*, sal_uInt32 ); private: void setDateAcceptancePatternsConfig(); }; // ----------------------------------------------------------------------- SvtSysLocale_Impl::SvtSysLocale_Impl() : pCharClass(NULL) { pLocaleData = new LocaleDataWrapper( aSysLocaleOptions.GetRealLanguageTag() ); setDateAcceptancePatternsConfig(); // listen for further changes aSysLocaleOptions.AddListener( this ); } SvtSysLocale_Impl::~SvtSysLocale_Impl() { aSysLocaleOptions.RemoveListener( this ); delete pCharClass; delete pLocaleData; } CharClass* SvtSysLocale_Impl::GetCharClass() { if ( !pCharClass ) pCharClass = new CharClass( aSysLocaleOptions.GetRealLanguageTag() ); return pCharClass; } void SvtSysLocale_Impl::ConfigurationChanged( utl::ConfigurationBroadcaster*, sal_uInt32 nHint ) { MutexGuard aGuard( SvtSysLocale::GetMutex() ); if ( nHint & SYSLOCALEOPTIONS_HINT_LOCALE ) { const LanguageTag& rLanguageTag = aSysLocaleOptions.GetRealLanguageTag(); pLocaleData->setLanguageTag( rLanguageTag ); GetCharClass()->setLanguageTag( rLanguageTag ); } if ( nHint & SYSLOCALEOPTIONS_HINT_DATEPATTERNS ) { setDateAcceptancePatternsConfig(); } } void SvtSysLocale_Impl::setDateAcceptancePatternsConfig() { OUString aStr( aSysLocaleOptions.GetDatePatternsConfigString()); if (aStr.isEmpty()) pLocaleData->setDateAcceptancePatterns( uno::Sequence<OUString>()); // reset else { ::std::vector< OUString > aVec; for (sal_Int32 nIndex = 0; nIndex >= 0; /*nop*/) { OUString aTok( aStr.getToken( 0, ';', nIndex)); if (!aTok.isEmpty()) aVec.push_back( aTok); } uno::Sequence< OUString > aSeq( aVec.size()); for (sal_Int32 i=0; i < aSeq.getLength(); ++i) aSeq[i] = aVec[i]; pLocaleData->setDateAcceptancePatterns( aSeq); } } // ==================================================================== SvtSysLocale::SvtSysLocale() { MutexGuard aGuard( GetMutex() ); if ( !pImpl ) pImpl = new SvtSysLocale_Impl; ++nRefCount; } SvtSysLocale::~SvtSysLocale() { MutexGuard aGuard( GetMutex() ); if ( !--nRefCount ) { delete pImpl; pImpl = NULL; } } // static Mutex& SvtSysLocale::GetMutex() { static Mutex* pMutex = NULL; if( !pMutex ) { MutexGuard aGuard( Mutex::getGlobalMutex() ); if( !pMutex ) { // #i77768# Due to a static reference in the toolkit lib // we need a mutex that lives longer than the svl library. // Otherwise the dtor would use a destructed mutex!! pMutex = new Mutex; } } return *pMutex; } const LocaleDataWrapper& SvtSysLocale::GetLocaleData() const { return *(pImpl->pLocaleData); } const LocaleDataWrapper* SvtSysLocale::GetLocaleDataPtr() const { return pImpl->pLocaleData; } const CharClass& SvtSysLocale::GetCharClass() const { return *(pImpl->GetCharClass()); } const CharClass* SvtSysLocale::GetCharClassPtr() const { return pImpl->GetCharClass(); } SvtSysLocaleOptions& SvtSysLocale::GetOptions() const { return pImpl->aSysLocaleOptions; } const LanguageTag& SvtSysLocale::GetLanguageTag() const { return pImpl->aSysLocaleOptions.GetRealLanguageTag(); } const LanguageTag& SvtSysLocale::GetUILanguageTag() const { return pImpl->aSysLocaleOptions.GetRealUILanguageTag(); } //------------------------------------------------------------------------ // static rtl_TextEncoding SvtSysLocale::GetBestMimeEncoding() { const sal_Char* pCharSet = rtl_getBestMimeCharsetFromTextEncoding( osl_getThreadTextEncoding() ); if ( !pCharSet ) { // If the system locale is unknown to us, e.g. LC_ALL=xx, match the UI // language if possible. ::com::sun::star::lang::Locale aLocale( SvtSysLocale().GetUILanguageTag().getLocale() ); rtl_Locale * pLocale = rtl_locale_register( aLocale.Language.getStr(), aLocale.Country.getStr(), aLocale.Variant.getStr() ); rtl_TextEncoding nEnc = osl_getTextEncodingFromLocale( pLocale ); pCharSet = rtl_getBestMimeCharsetFromTextEncoding( nEnc ); } rtl_TextEncoding nRet; if ( pCharSet ) nRet = rtl_getTextEncodingFromMimeCharset( pCharSet ); else nRet = RTL_TEXTENCODING_UTF8; return nRet; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>do not use the raw locale for osl_getTextEncodingFromLocale()<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <unotools/syslocale.hxx> #include <unotools/syslocaleoptions.hxx> #include <comphelper/processfactory.hxx> #include <rtl/tencinfo.h> #include <rtl/locale.h> #include <osl/nlsupport.h> #include <vector> using namespace osl; using namespace com::sun::star; SvtSysLocale_Impl* SvtSysLocale::pImpl = NULL; sal_Int32 SvtSysLocale::nRefCount = 0; class SvtSysLocale_Impl : public utl::ConfigurationListener { public: SvtSysLocaleOptions aSysLocaleOptions; LocaleDataWrapper* pLocaleData; CharClass* pCharClass; SvtSysLocale_Impl(); virtual ~SvtSysLocale_Impl(); CharClass* GetCharClass(); virtual void ConfigurationChanged( utl::ConfigurationBroadcaster*, sal_uInt32 ); private: void setDateAcceptancePatternsConfig(); }; // ----------------------------------------------------------------------- SvtSysLocale_Impl::SvtSysLocale_Impl() : pCharClass(NULL) { pLocaleData = new LocaleDataWrapper( aSysLocaleOptions.GetRealLanguageTag() ); setDateAcceptancePatternsConfig(); // listen for further changes aSysLocaleOptions.AddListener( this ); } SvtSysLocale_Impl::~SvtSysLocale_Impl() { aSysLocaleOptions.RemoveListener( this ); delete pCharClass; delete pLocaleData; } CharClass* SvtSysLocale_Impl::GetCharClass() { if ( !pCharClass ) pCharClass = new CharClass( aSysLocaleOptions.GetRealLanguageTag() ); return pCharClass; } void SvtSysLocale_Impl::ConfigurationChanged( utl::ConfigurationBroadcaster*, sal_uInt32 nHint ) { MutexGuard aGuard( SvtSysLocale::GetMutex() ); if ( nHint & SYSLOCALEOPTIONS_HINT_LOCALE ) { const LanguageTag& rLanguageTag = aSysLocaleOptions.GetRealLanguageTag(); pLocaleData->setLanguageTag( rLanguageTag ); GetCharClass()->setLanguageTag( rLanguageTag ); } if ( nHint & SYSLOCALEOPTIONS_HINT_DATEPATTERNS ) { setDateAcceptancePatternsConfig(); } } void SvtSysLocale_Impl::setDateAcceptancePatternsConfig() { OUString aStr( aSysLocaleOptions.GetDatePatternsConfigString()); if (aStr.isEmpty()) pLocaleData->setDateAcceptancePatterns( uno::Sequence<OUString>()); // reset else { ::std::vector< OUString > aVec; for (sal_Int32 nIndex = 0; nIndex >= 0; /*nop*/) { OUString aTok( aStr.getToken( 0, ';', nIndex)); if (!aTok.isEmpty()) aVec.push_back( aTok); } uno::Sequence< OUString > aSeq( aVec.size()); for (sal_Int32 i=0; i < aSeq.getLength(); ++i) aSeq[i] = aVec[i]; pLocaleData->setDateAcceptancePatterns( aSeq); } } // ==================================================================== SvtSysLocale::SvtSysLocale() { MutexGuard aGuard( GetMutex() ); if ( !pImpl ) pImpl = new SvtSysLocale_Impl; ++nRefCount; } SvtSysLocale::~SvtSysLocale() { MutexGuard aGuard( GetMutex() ); if ( !--nRefCount ) { delete pImpl; pImpl = NULL; } } // static Mutex& SvtSysLocale::GetMutex() { static Mutex* pMutex = NULL; if( !pMutex ) { MutexGuard aGuard( Mutex::getGlobalMutex() ); if( !pMutex ) { // #i77768# Due to a static reference in the toolkit lib // we need a mutex that lives longer than the svl library. // Otherwise the dtor would use a destructed mutex!! pMutex = new Mutex; } } return *pMutex; } const LocaleDataWrapper& SvtSysLocale::GetLocaleData() const { return *(pImpl->pLocaleData); } const LocaleDataWrapper* SvtSysLocale::GetLocaleDataPtr() const { return pImpl->pLocaleData; } const CharClass& SvtSysLocale::GetCharClass() const { return *(pImpl->GetCharClass()); } const CharClass* SvtSysLocale::GetCharClassPtr() const { return pImpl->GetCharClass(); } SvtSysLocaleOptions& SvtSysLocale::GetOptions() const { return pImpl->aSysLocaleOptions; } const LanguageTag& SvtSysLocale::GetLanguageTag() const { return pImpl->aSysLocaleOptions.GetRealLanguageTag(); } const LanguageTag& SvtSysLocale::GetUILanguageTag() const { return pImpl->aSysLocaleOptions.GetRealUILanguageTag(); } //------------------------------------------------------------------------ // static rtl_TextEncoding SvtSysLocale::GetBestMimeEncoding() { const sal_Char* pCharSet = rtl_getBestMimeCharsetFromTextEncoding( osl_getThreadTextEncoding() ); if ( !pCharSet ) { // If the system locale is unknown to us, e.g. LC_ALL=xx, match the UI // language if possible. SvtSysLocale aSysLocale; const LanguageTag& rLanguageTag = aSysLocale.GetUILanguageTag(); // Converting blindly to Locale and then to rtl_Locale may feed the // 'qlt' to rtl_locale_register() and the underlying system locale // stuff, which doesn't know about it nor about BCP47 in the Variant // field. So use the real language and for non-pure ISO cases hope for // the best.. the fallback to UTF-8 should solve these cases nowadays. /* FIXME-BCP47: the script needs to go in here as well, so actually * we'd need some variant fiddling or glibc locale string and tweak * rtl_locale_register() to know about it! But then again the Windows * implementation still wouldn't know anything about it ... */ SAL_WARN_IF( !rLanguageTag.isIsoLocale(), "unotools.i18n", "SvtSysLocale::GetBestMimeEncoding - non-ISO UI locale"); rtl_Locale * pLocale = rtl_locale_register( rLanguageTag.getLanguage().getStr(), rLanguageTag.getCountry().getStr(), OUString().getStr() ); rtl_TextEncoding nEnc = osl_getTextEncodingFromLocale( pLocale ); pCharSet = rtl_getBestMimeCharsetFromTextEncoding( nEnc ); } rtl_TextEncoding nRet; if ( pCharSet ) nRet = rtl_getTextEncodingFromMimeCharset( pCharSet ); else nRet = RTL_TEXTENCODING_UTF8; return nRet; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright 2013, Durachenko Aleksey V. <durachenko.aleksey@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "qseselectionplot.h" #include "qsefunc.h" QseSelectionPlot::QseSelectionPlot(QObject *parent) : QseAbstractPlot(parent) { m_brush = Qt::blue; m_opacity = 0.5; } void QseSelectionPlot::setBrush(const QBrush &brush) { if (m_brush != brush) { m_brush = brush; emit changed(); } } void QseSelectionPlot::setOpacity(qreal opacity) { if (m_opacity != opacity) { m_opacity = opacity; emit changed(); } } void QseSelectionPlot::setSelection(QseSelection *selection) { if (m_selection) disconnect(m_selection, 0, this, 0); if (selection) { connect(selection, SIGNAL(changed()), this, SIGNAL(changed())); connect(selection, SIGNAL(destroyed(QObject*)), this, SLOT(selectionDestroyed(QObject*))); } m_selection = selection; } bool QseSelectionPlot::isVisible(const QRect &rect, const QseGeometry &geometry) { if (m_selection == 0) return false; if (m_selection->isNull()) return false; qint64 sl = QseFunc::mapSampleToWidget(m_selection->left(), geometry.x(), geometry.samplePerPixel()); qint64 sr = QseFunc::mapSampleToWidget(m_selection->right(), geometry.x(), geometry.samplePerPixel()); if ((sl < 0 && sr < 0) || (sl >= rect.width() && sr >= rect.width())) return false; return true; } void QseSelectionPlot::draw(QPainter *painter, const QRect &rect, const QseGeometry &geometry) { if (m_selection && !m_selection->isNull()) { qint64 sl = QseFunc::mapSampleToWidget(m_selection->left(), geometry.x(), geometry.samplePerPixel()); qint64 sr = QseFunc::mapSampleToWidget(m_selection->right(), geometry.x(), geometry.samplePerPixel()); if ((sl < 0 && sr < 0) || (sl >= rect.width() && sr >= rect.width())) return; if (sl < 0) sl = 0; if (sr > rect.width()) sr = rect.width(); painter->setOpacity(opacity()); painter->fillRect(sl, 0, sr-sl+1, rect.height(), brush()); } } void QseSelectionPlot::selectionDestroyed(QObject *obj) { if (obj == m_selection) m_selection = 0; } <commit_msg>fix incorrect pointer initialization<commit_after>// Copyright 2013, Durachenko Aleksey V. <durachenko.aleksey@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "qseselectionplot.h" #include "qsefunc.h" QseSelectionPlot::QseSelectionPlot(QObject *parent) : QseAbstractPlot(parent) { m_brush = Qt::blue; m_opacity = 0.5; m_selection = 0; } void QseSelectionPlot::setBrush(const QBrush &brush) { if (m_brush != brush) { m_brush = brush; emit changed(); } } void QseSelectionPlot::setOpacity(qreal opacity) { if (m_opacity != opacity) { m_opacity = opacity; emit changed(); } } void QseSelectionPlot::setSelection(QseSelection *selection) { if (m_selection) disconnect(m_selection, 0, this, 0); if (selection) { connect(selection, SIGNAL(changed()), this, SIGNAL(changed())); connect(selection, SIGNAL(destroyed(QObject*)), this, SLOT(selectionDestroyed(QObject*))); } m_selection = selection; } bool QseSelectionPlot::isVisible(const QRect &rect, const QseGeometry &geometry) { if (m_selection == 0) return false; if (m_selection->isNull()) return false; qint64 sl = QseFunc::mapSampleToWidget(m_selection->left(), geometry.x(), geometry.samplePerPixel()); qint64 sr = QseFunc::mapSampleToWidget(m_selection->right(), geometry.x(), geometry.samplePerPixel()); if ((sl < 0 && sr < 0) || (sl >= rect.width() && sr >= rect.width())) return false; return true; } void QseSelectionPlot::draw(QPainter *painter, const QRect &rect, const QseGeometry &geometry) { if (m_selection && !m_selection->isNull()) { qint64 sl = QseFunc::mapSampleToWidget(m_selection->left(), geometry.x(), geometry.samplePerPixel()); qint64 sr = QseFunc::mapSampleToWidget(m_selection->right(), geometry.x(), geometry.samplePerPixel()); if ((sl < 0 && sr < 0) || (sl >= rect.width() && sr >= rect.width())) return; if (sl < 0) sl = 0; if (sr > rect.width()) sr = rect.width(); painter->setOpacity(opacity()); painter->fillRect(sl, 0, sr-sl+1, rect.height(), brush()); } } void QseSelectionPlot::selectionDestroyed(QObject *obj) { if (obj == m_selection) m_selection = 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <iostream> #include <functional> #include <list> #include "object-store/realm_delegate.hpp" #include "error_handling.hpp" using namespace realm; namespace realm { namespace binding { class CSharpRealmDelegate: public RealmDelegate { public: // A token returned from add_notification that can be used to remove the // notification later struct token : private std::list<std::function<void()>>::iterator { token(std::list<std::function<void()>>::iterator it) : std::list<std::function<void()>>::iterator(it) { } friend class CSharpRealmDelegate; }; token add_notification(std::function<void()> func) { m_registered_notifications.push_back(std::move(func)); return token(std::prev(m_registered_notifications.end())); } void remove_notification(token entry) { m_registered_notifications.erase(entry); } // Override the did_change method to call each registered notification void did_change(std::vector<ObserverState> const&, std::vector<void*> const&) override { // Loop oddly so that unregistering a notification from within the // registered function works for (auto it = m_registered_notifications.begin(); it != m_registered_notifications.end(); ) { (*it++)(); } } private: std::list<std::function<void()>> m_registered_notifications; }; CSharpRealmDelegate* delegate_instance = new CSharpRealmDelegate(); void process_error(RealmError* error) { // Blah! } } } #ifdef DYNAMIC // clang complains when making a dylib if there is no main(). :-/ int main() { return 0; } #endif<commit_msg>Remove superfluous process_error<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <iostream> #include <functional> #include <list> #include "object-store/realm_delegate.hpp" #include "error_handling.hpp" using namespace realm; namespace realm { namespace binding { class CSharpRealmDelegate: public RealmDelegate { public: // A token returned from add_notification that can be used to remove the // notification later struct token : private std::list<std::function<void()>>::iterator { token(std::list<std::function<void()>>::iterator it) : std::list<std::function<void()>>::iterator(it) { } friend class CSharpRealmDelegate; }; token add_notification(std::function<void()> func) { m_registered_notifications.push_back(std::move(func)); return token(std::prev(m_registered_notifications.end())); } void remove_notification(token entry) { m_registered_notifications.erase(entry); } // Override the did_change method to call each registered notification void did_change(std::vector<ObserverState> const&, std::vector<void*> const&) override { // Loop oddly so that unregistering a notification from within the // registered function works for (auto it = m_registered_notifications.begin(); it != m_registered_notifications.end(); ) { (*it++)(); } } private: std::list<std::function<void()>> m_registered_notifications; }; CSharpRealmDelegate* delegate_instance = new CSharpRealmDelegate(); } } #ifdef DYNAMIC // clang complains when making a dylib if there is no main(). :-/ int main() { return 0; } #endif<|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH #define DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH #include <type_traits> #include <limits> #include <dune/stuff/common/disable_warnings.hh> #include <dune/common/dynmatrix.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/disable_warnings.hh> #include <dune/geometry/quadraturerules.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/functions/constant.hh> #include <dune/gdt/playground/spaces/raviartthomas/pdelab.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/localevaluation/swipdg.hh> namespace Dune { namespace GDT { namespace Operators { template <class GridViewType, class DiffusionFactorType, class DiffusionTensorType = void> class DiffusiveFluxReconstruction; /** * \todo Add more static checks that GridViewType and LocalizableFunctionType match. * \todo Derive from operator interfaces. */ template <class GridViewType, class LocalizableFunctionType> class DiffusiveFluxReconstruction<GridViewType, LocalizableFunctionType, void> { static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!"); static_assert(std::is_base_of<Stuff::IsLocalizableFunction, LocalizableFunctionType>::value, "LocalizableFunctionType has to be tagged as Stuff::IsLocalizableFunction!"); public: typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; typedef typename LocalizableFunctionType::RangeFieldType FieldType; typedef typename LocalizableFunctionType::DomainType DomainType; private: static_assert(dimDomain == 2, "Not implemented!"); public: DiffusiveFluxReconstruction(const GridViewType& grid_view, const LocalizableFunctionType& diffusion) : grid_view_(grid_view) , diffusion_(diffusion) { } template <class GV, class V> void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, 1>& source, DiscreteFunction<Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>, V>& range) const { const auto& rtn0_space = range.space(); auto& range_vector = range.vector(); const FieldType infinity = std::numeric_limits<FieldType>::infinity(); for (size_t ii = 0; ii < range_vector.size(); ++ii) range_vector[ii] = infinity; const LocalEvaluation::SWIPDG::Inner<LocalizableFunctionType> inner_evaluation(diffusion_); const LocalEvaluation::SWIPDG::BoundaryLHS<LocalizableFunctionType> boundary_evaluation(diffusion_); const Stuff::Functions::Constant<EntityType, DomainFieldType, dimDomain, FieldType, 1> constant_one(1); DomainType normal(0); DomainType xx_entity(0); DynamicMatrix<FieldType> tmp_matrix(1, 1, 0); DynamicMatrix<FieldType> tmp_matrix_en_en(1, 1, 0); DynamicMatrix<FieldType> tmp_matrix_en_ne(1, 1, 0); std::vector< typename Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>::BaseFunctionSetType::RangeType> basis_values( rtn0_space.mapper().maxNumDofs(), typename Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>::BaseFunctionSetType::RangeType( 0)); // walk the grid const auto entity_it_end = grid_view_.template end<0>(); for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity); const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity); assert(global_DoF_indices.size() == local_DoF_indices.size()); const auto local_diffusion = diffusion_.local_function(entity); const auto local_source = source.local_function(entity); const auto local_basis = rtn0_space.base_function_set(entity); const auto local_constant_one = constant_one.local_function(entity); // walk the intersections const auto intersection_it_end = grid_view_.iend(entity); for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; if (intersection.neighbor() && !intersection.boundary()) { const auto neighbor_ptr = intersection.outside(); const auto& neighbor = *neighbor_ptr; if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) { const auto local_diffusion_neighbor = diffusion_.local_function(neighbor); const auto local_source_neighbor = source.local_function(neighbor); const auto local_constant_one_neighbor = constant_one.local_function(neighbor); const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = inner_evaluation.order(*local_diffusion, *local_diffusion_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor); assert(integrand_order < std::numeric_limits<int>::max()); const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain - 1>::rule(intersection.type(), int(integrand_order)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto& xx_intersection = quadrature_it->position(); xx_entity = intersection.geometryInInside().global(xx_intersection); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; tmp_matrix_en_en *= 0.0; tmp_matrix_en_ne *= 0.0; inner_evaluation.evaluate(*local_diffusion, *local_diffusion_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor, intersection, xx_intersection, tmp_matrix_en_en, // <- we are interested in this one tmp_matrix, tmp_matrix_en_ne, // <- and this one tmp_matrix); // compute integrals assert(tmp_matrix_en_en.rows() >= 1); assert(tmp_matrix_en_en.cols() >= 1); assert(tmp_matrix_en_ne.rows() >= 1); assert(tmp_matrix_en_ne.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]); } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; // and make sure we are the first to do so assert(!(range_vector[global_DoF_index] < infinity)); range_vector[global_DoF_index] = rhs / lhs; } } else if (intersection.boundary() && !intersection.neighbor()) { const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = boundary_evaluation.order(*local_diffusion, *local_source, *local_constant_one); assert(integrand_order < std::numeric_limits<int>::max()); const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain - 1>::rule(intersection.type(), int(integrand_order)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx_intersection = quadrature_it->position(); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); xx_entity = intersection.geometryInInside().global(xx_intersection); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; boundary_evaluation.evaluate( *local_diffusion, *local_constant_one, *local_source, intersection, xx_intersection, tmp_matrix); // compute integrals assert(tmp_matrix.rows() >= 1); assert(tmp_matrix.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * tmp_matrix[0][0]; } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; assert(!(range_vector[global_DoF_index] < infinity)); // and make sure we are the first to do so range_vector[global_DoF_index] = rhs / lhs; } else DUNE_THROW(Stuff::Exceptions::internal_error, "Unknown intersection type!"); } // walk the intersections } // walk the grid } // ... apply(...) private: const GridViewType& grid_view_; const LocalizableFunctionType& diffusion_; }; // class DiffusiveFluxReconstruction } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH <commit_msg>[operators.fluxreconstruction] remove warning guards, refs #29<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH #define DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH #include <type_traits> #include <limits> #include <dune/common/dynmatrix.hh> #include <dune/geometry/quadraturerules.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/functions/constant.hh> #include <dune/gdt/playground/spaces/raviartthomas/pdelab.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/localevaluation/swipdg.hh> namespace Dune { namespace GDT { namespace Operators { template <class GridViewType, class DiffusionFactorType, class DiffusionTensorType = void> class DiffusiveFluxReconstruction; /** * \todo Add more static checks that GridViewType and LocalizableFunctionType match. * \todo Derive from operator interfaces. */ template <class GridViewType, class LocalizableFunctionType> class DiffusiveFluxReconstruction<GridViewType, LocalizableFunctionType, void> { static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!"); static_assert(std::is_base_of<Stuff::IsLocalizableFunction, LocalizableFunctionType>::value, "LocalizableFunctionType has to be tagged as Stuff::IsLocalizableFunction!"); public: typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; typedef typename LocalizableFunctionType::RangeFieldType FieldType; typedef typename LocalizableFunctionType::DomainType DomainType; private: static_assert(dimDomain == 2, "Not implemented!"); public: DiffusiveFluxReconstruction(const GridViewType& grid_view, const LocalizableFunctionType& diffusion) : grid_view_(grid_view) , diffusion_(diffusion) { } template <class GV, class V> void apply(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, FieldType, 1>& source, DiscreteFunction<Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>, V>& range) const { const auto& rtn0_space = range.space(); auto& range_vector = range.vector(); const FieldType infinity = std::numeric_limits<FieldType>::infinity(); for (size_t ii = 0; ii < range_vector.size(); ++ii) range_vector[ii] = infinity; const LocalEvaluation::SWIPDG::Inner<LocalizableFunctionType> inner_evaluation(diffusion_); const LocalEvaluation::SWIPDG::BoundaryLHS<LocalizableFunctionType> boundary_evaluation(diffusion_); const Stuff::Functions::Constant<EntityType, DomainFieldType, dimDomain, FieldType, 1> constant_one(1); DomainType normal(0); DomainType xx_entity(0); DynamicMatrix<FieldType> tmp_matrix(1, 1, 0); DynamicMatrix<FieldType> tmp_matrix_en_en(1, 1, 0); DynamicMatrix<FieldType> tmp_matrix_en_ne(1, 1, 0); std::vector< typename Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>::BaseFunctionSetType::RangeType> basis_values( rtn0_space.mapper().maxNumDofs(), typename Spaces::RaviartThomas::PdelabBased<GV, 0, FieldType, dimDomain>::BaseFunctionSetType::RangeType( 0)); // walk the grid const auto entity_it_end = grid_view_.template end<0>(); for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity); const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity); assert(global_DoF_indices.size() == local_DoF_indices.size()); const auto local_diffusion = diffusion_.local_function(entity); const auto local_source = source.local_function(entity); const auto local_basis = rtn0_space.base_function_set(entity); const auto local_constant_one = constant_one.local_function(entity); // walk the intersections const auto intersection_it_end = grid_view_.iend(entity); for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; if (intersection.neighbor() && !intersection.boundary()) { const auto neighbor_ptr = intersection.outside(); const auto& neighbor = *neighbor_ptr; if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) { const auto local_diffusion_neighbor = diffusion_.local_function(neighbor); const auto local_source_neighbor = source.local_function(neighbor); const auto local_constant_one_neighbor = constant_one.local_function(neighbor); const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = inner_evaluation.order(*local_diffusion, *local_diffusion_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor); assert(integrand_order < std::numeric_limits<int>::max()); const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain - 1>::rule(intersection.type(), int(integrand_order)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto& xx_intersection = quadrature_it->position(); xx_entity = intersection.geometryInInside().global(xx_intersection); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; tmp_matrix_en_en *= 0.0; tmp_matrix_en_ne *= 0.0; inner_evaluation.evaluate(*local_diffusion, *local_diffusion_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor, intersection, xx_intersection, tmp_matrix_en_en, // <- we are interested in this one tmp_matrix, tmp_matrix_en_ne, // <- and this one tmp_matrix); // compute integrals assert(tmp_matrix_en_en.rows() >= 1); assert(tmp_matrix_en_en.cols() >= 1); assert(tmp_matrix_en_ne.rows() >= 1); assert(tmp_matrix_en_ne.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]); } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; // and make sure we are the first to do so assert(!(range_vector[global_DoF_index] < infinity)); range_vector[global_DoF_index] = rhs / lhs; } } else if (intersection.boundary() && !intersection.neighbor()) { const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = boundary_evaluation.order(*local_diffusion, *local_source, *local_constant_one); assert(integrand_order < std::numeric_limits<int>::max()); const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain - 1>::rule(intersection.type(), int(integrand_order)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx_intersection = quadrature_it->position(); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); xx_entity = intersection.geometryInInside().global(xx_intersection); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; boundary_evaluation.evaluate( *local_diffusion, *local_constant_one, *local_source, intersection, xx_intersection, tmp_matrix); // compute integrals assert(tmp_matrix.rows() >= 1); assert(tmp_matrix.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * tmp_matrix[0][0]; } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; assert(!(range_vector[global_DoF_index] < infinity)); // and make sure we are the first to do so range_vector[global_DoF_index] = rhs / lhs; } else DUNE_THROW(Stuff::Exceptions::internal_error, "Unknown intersection type!"); } // walk the intersections } // walk the grid } // ... apply(...) private: const GridViewType& grid_view_; const LocalizableFunctionType& diffusion_; }; // class DiffusiveFluxReconstruction } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH <|endoftext|>
<commit_before>#include <ompl/base/ScopedState.h> #include <ompl/base/spaces/RealVectorBounds.h> #include <ompl/base/spaces/RealVectorStateSpace.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <ompl/base/State.h> #include <ompl/control/planners/syclop/Syclop.h> #include <ompl/control/planners/syclop/SyclopRRT.h> #include <ompl/control/planners/syclop/GridDecomposition.h> #include <ompl/control/spaces/RealVectorControlSpace.h> #include <ompl/util/RandomNumbers.h> #define BOOST_NO_HASH #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/adjacency_list.hpp> #include <cmath> #include <iostream> #include <vector> namespace ob = ompl::base; namespace oc = ompl::control; class TestDecomposition : public oc::GridDecomposition { public: TestDecomposition(const int length, ob::RealVectorBounds &bounds) : oc::GridDecomposition(length, 2, bounds) { } virtual ~TestDecomposition() { } virtual int locateRegion(const ob::State *s) { const ob::SE2StateSpace::StateType *ws = s->as<ob::SE2StateSpace::StateType>(); std::vector<double> coord(2); coord[0] = ws->getX(); coord[1] = ws->getY(); return oc::GridDecomposition::locateRegion(coord); } virtual void stateToCoord(const ob::State *s, std::vector<double>& coord) { const ob::SE2StateSpace::StateType *ws = s->as<ob::SE2StateSpace::StateType>(); coord.resize(2); coord[0] = ws->getX(); coord[1] = ws->getY(); } }; bool isStateValid(const ob::State *s) { const ob::SE2StateSpace::StateType *se = s->as<ob::SE2StateSpace::StateType>(); const double x = se->getX(); const double y = se->getY(); if (x < -0.5 && y < 0.5) return false; if (x > 0.5 && fabs(y) < 0.5) return false; return true; } void propagate(const ob::State *start, const oc::Control *control, const double duration, ob::State *result) { const ob::SE2StateSpace::StateType* location = start->as<ob::SE2StateSpace::StateType>(); const oc::RealVectorControlSpace::ControlType* ctrl = control->as<oc::RealVectorControlSpace::ControlType>(); const double x = location->getX(); const double y = location->getY(); const double angle = location->getYaw(); const double velocity = (*ctrl)[0]; const double steerVelocity = (*ctrl)[1]; ob::SE2StateSpace::StateType* newLocation = result->as<ob::SE2StateSpace::StateType>(); newLocation->setXY(x + velocity*duration*cos(angle), y + velocity*duration*sin(angle)); newLocation->setYaw(angle + duration*steerVelocity); } int main(void) { ompl::base::RealVectorBounds bounds(2); bounds.setLow(-1); bounds.setHigh(1); TestDecomposition grid(2, bounds); ob::RealVectorBounds cbounds(2); cbounds.setLow(-2); cbounds.setHigh(2); ob::StateSpacePtr manifold(new ob::SE2StateSpace()); manifold->as<ob::SE2StateSpace>()->setBounds(bounds); //controlSpace : forward acceleration & steer velocity oc::ControlSpacePtr controlSpace(new oc::RealVectorControlSpace(manifold, 2)); controlSpace->as<oc::RealVectorControlSpace>()->setBounds(cbounds); controlSpace->setPropagationFunction(boost::bind(&propagate, _1, _2, _3, _4)); ob::ScopedState<ob::SE2StateSpace> init(manifold); init->setX(-0.75); init->setY(0.8); init->setYaw(0); ob::ScopedState<ob::SE2StateSpace> goal(init); goal->setX(0.65); goal->setY(-0.7); oc::SpaceInformationPtr si(new oc::SpaceInformation(manifold, controlSpace)); si->setStateValidityChecker(boost::bind(&isStateValid, _1)); si->setup(); ob::ProblemDefinitionPtr pdef(new ob::ProblemDefinition(si)); pdef->setStartAndGoalStates(init, goal, 0.05); oc::SyclopRRT planner(si, grid); planner.setProblemDefinition(pdef); planner.setup(); if (planner.solve(1.0)) std::cout << "solved" << std::endl; else std::cout << "unsolved" << std::endl; return 0; } <commit_msg>changed syclop demo to have a finer grid<commit_after>#include <ompl/base/ScopedState.h> #include <ompl/base/spaces/RealVectorBounds.h> #include <ompl/base/spaces/RealVectorStateSpace.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <ompl/base/State.h> #include <ompl/control/planners/syclop/Syclop.h> #include <ompl/control/planners/syclop/SyclopRRT.h> #include <ompl/control/planners/syclop/GridDecomposition.h> #include <ompl/control/spaces/RealVectorControlSpace.h> #include <ompl/util/RandomNumbers.h> #define BOOST_NO_HASH #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/adjacency_list.hpp> #include <cmath> #include <iostream> #include <vector> namespace ob = ompl::base; namespace oc = ompl::control; class TestDecomposition : public oc::GridDecomposition { public: TestDecomposition(const int length, const ob::RealVectorBounds &bounds) : oc::GridDecomposition(length, 2, bounds) { } virtual ~TestDecomposition() { } virtual int locateRegion(const ob::State *s) { const ob::SE2StateSpace::StateType *ws = s->as<ob::SE2StateSpace::StateType>(); std::vector<double> coord(2); coord[0] = ws->getX(); coord[1] = ws->getY(); return oc::GridDecomposition::locateRegion(coord); } virtual void stateToCoord(const ob::State *s, std::vector<double>& coord) { const ob::SE2StateSpace::StateType *ws = s->as<ob::SE2StateSpace::StateType>(); coord.resize(2); coord[0] = ws->getX(); coord[1] = ws->getY(); } }; bool isStateValid(const oc::SpaceInformation* si, const ob::State *s) { const ob::SE2StateSpace::StateType *se = s->as<ob::SE2StateSpace::StateType>(); const double x = se->getX(); const double y = se->getY(); if (x < -2.0 && y < -2.0) return false; if (x > 0 && x < 1 && y > 0) return false; if (x > 2.5 && fabs(y) < 1.5) return false; return si->satisfiesBounds(s); } void propagate(const ob::State *start, const oc::Control *control, const double duration, ob::State *result) { const ob::SE2StateSpace::StateType* location = start->as<ob::SE2StateSpace::StateType>(); const oc::RealVectorControlSpace::ControlType* ctrl = control->as<oc::RealVectorControlSpace::ControlType>(); const double x = location->getX(); const double y = location->getY(); const double angle = location->getYaw(); const double velocity = (*ctrl)[0]; const double steerVelocity = (*ctrl)[1]; ob::SE2StateSpace::StateType* newLocation = result->as<ob::SE2StateSpace::StateType>(); newLocation->setXY(x + velocity*duration*cos(angle), y + velocity*duration*sin(angle)); newLocation->setYaw(angle + duration*steerVelocity); } int main(void) { ompl::base::RealVectorBounds bounds(2); bounds.setLow(-3); bounds.setHigh(3); TestDecomposition grid(3, bounds); ob::RealVectorBounds cbounds(2); cbounds.setLow(-2); cbounds.setHigh(2); ob::StateSpacePtr manifold(new ob::SE2StateSpace()); manifold->as<ob::SE2StateSpace>()->setBounds(bounds); //controlSpace : forward velocity & steer velocity oc::ControlSpacePtr controlSpace(new oc::RealVectorControlSpace(manifold, 2)); controlSpace->as<oc::RealVectorControlSpace>()->setBounds(cbounds); controlSpace->setPropagationFunction(boost::bind(&propagate, _1, _2, _3, _4)); ob::ScopedState<ob::SE2StateSpace> init(manifold); init->setX(-2.0); init->setY(2.0); init->setYaw(0); ob::ScopedState<ob::SE2StateSpace> goal(init); goal->setX(2.0); goal->setY(-2.0); oc::SpaceInformationPtr si(new oc::SpaceInformation(manifold, controlSpace)); si->setStateValidityChecker(boost::bind(&isStateValid, si.get(), _1)); si->setup(); ob::ProblemDefinitionPtr pdef(new ob::ProblemDefinition(si)); pdef->setStartAndGoalStates(init, goal, 0.05); oc::SyclopRRT planner(si, grid); planner.setProblemDefinition(pdef); planner.setup(); if (planner.solve(90.0)) std::cerr << "solved" << std::endl; else std::cerr << "unsolved" << std::endl; return 0; } <|endoftext|>
<commit_before>#include "Runtime/World/CScriptBeam.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/Particle/CWeaponDescription.hpp" #include "Runtime/Weapon/CPlasmaProjectile.hpp" #include "Runtime/World/CActorParameters.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { CScriptBeam::CScriptBeam(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, bool active, const TToken<CWeaponDescription>& weaponDesc, const CBeamInfo& bInfo, const CDamageInfo& dInfo) : CActor(uid, active, name, info, xf, CModelData::CModelDataNull(), CMaterialList(), CActorParameters::None(), kInvalidUniqueId) , xe8_weaponDescription(weaponDesc) , xf4_beamInfo(bInfo) , x138_damageInfo(dInfo) {} void CScriptBeam::Accept(IVisitor& visitor) { visitor.Visit(this); } void CScriptBeam::Think(float dt, CStateManager& mgr) { if (CPlasmaProjectile* proj = static_cast<CPlasmaProjectile*>(mgr.ObjectById(x154_projectileId))) { if (proj->GetActive()) proj->UpdateFx(x34_transform, dt, mgr); } else x154_projectileId = kInvalidUniqueId; } void CScriptBeam::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& mgr) { if (msg == EScriptObjectMessage::Increment) { if (CPlasmaProjectile* proj = static_cast<CPlasmaProjectile*>(mgr.ObjectById(x154_projectileId))) { proj->ResetBeam(mgr, true); proj->Fire(GetTransform(), mgr, false); } } else if (msg == EScriptObjectMessage::Decrement) { if (CPlasmaProjectile* proj = static_cast<CPlasmaProjectile*>(mgr.ObjectById(x154_projectileId))) { if (proj->GetActive()) { proj->ResetBeam(mgr, false); } } } else if (msg == EScriptObjectMessage::Registered) { x154_projectileId = mgr.AllocateUniqueId(); mgr.AddObject(new CPlasmaProjectile(xe8_weaponDescription, x10_name + "-Projectile", x138_damageInfo.GetWeaponMode().GetType(), xf4_beamInfo, x34_transform, EMaterialTypes::Projectile, x138_damageInfo, x154_projectileId, x4_areaId, GetUniqueId(), {}, false, EProjectileAttrib::PlasmaProjectile)); } else if (msg == EScriptObjectMessage::Deleted) { mgr.FreeScriptObject(x154_projectileId); } CActor::AcceptScriptMsg(msg, objId, mgr); } } // namespace urde <commit_msg>CScriptBeam: Brace statements where applicable<commit_after>#include "Runtime/World/CScriptBeam.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/Particle/CWeaponDescription.hpp" #include "Runtime/Weapon/CPlasmaProjectile.hpp" #include "Runtime/World/CActorParameters.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { CScriptBeam::CScriptBeam(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, bool active, const TToken<CWeaponDescription>& weaponDesc, const CBeamInfo& bInfo, const CDamageInfo& dInfo) : CActor(uid, active, name, info, xf, CModelData::CModelDataNull(), CMaterialList(), CActorParameters::None(), kInvalidUniqueId) , xe8_weaponDescription(weaponDesc) , xf4_beamInfo(bInfo) , x138_damageInfo(dInfo) {} void CScriptBeam::Accept(IVisitor& visitor) { visitor.Visit(this); } void CScriptBeam::Think(float dt, CStateManager& mgr) { if (CPlasmaProjectile* proj = static_cast<CPlasmaProjectile*>(mgr.ObjectById(x154_projectileId))) { if (proj->GetActive()) { proj->UpdateFx(x34_transform, dt, mgr); } } else { x154_projectileId = kInvalidUniqueId; } } void CScriptBeam::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& mgr) { if (msg == EScriptObjectMessage::Increment) { if (CPlasmaProjectile* proj = static_cast<CPlasmaProjectile*>(mgr.ObjectById(x154_projectileId))) { proj->ResetBeam(mgr, true); proj->Fire(GetTransform(), mgr, false); } } else if (msg == EScriptObjectMessage::Decrement) { if (CPlasmaProjectile* proj = static_cast<CPlasmaProjectile*>(mgr.ObjectById(x154_projectileId))) { if (proj->GetActive()) { proj->ResetBeam(mgr, false); } } } else if (msg == EScriptObjectMessage::Registered) { x154_projectileId = mgr.AllocateUniqueId(); mgr.AddObject(new CPlasmaProjectile(xe8_weaponDescription, x10_name + "-Projectile", x138_damageInfo.GetWeaponMode().GetType(), xf4_beamInfo, x34_transform, EMaterialTypes::Projectile, x138_damageInfo, x154_projectileId, x4_areaId, GetUniqueId(), {}, false, EProjectileAttrib::PlasmaProjectile)); } else if (msg == EScriptObjectMessage::Deleted) { mgr.FreeScriptObject(x154_projectileId); } CActor::AcceptScriptMsg(msg, objId, mgr); } } // namespace urde <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_PHYSICALFONTCOLLECTION_HXX #define INCLUDED_VCL_INC_PHYSICALFONTCOLLECTION_HXX #include <vcl/dllapi.h> #include "outfont.hxx" #include "PhysicalFontFamily.hxx" // - PhysicalFontCollection - // TODO: merge with ImplFontCache // TODO: rename to LogicalFontManager class VCL_PLUGIN_PUBLIC PhysicalFontCollection { private: friend class WinGlyphFallbackSubstititution; mutable bool mbMatchData; // true if matching attributes are initialized bool mbMapNames; // true if MapNames are available typedef std::unordered_map<const OUString, PhysicalFontFamily*,OUStringHash> PhysicalFontFamilies; PhysicalFontFamilies maPhysicalFontFamilies; ImplPreMatchFontSubstitution* mpPreMatchHook; // device specific prematch substitution ImplGlyphFallbackFontSubstitution* mpFallbackHook; // device specific glyh fallback substitution public: explicit PhysicalFontCollection(); virtual ~PhysicalFontCollection(); // fill the list with device fonts void Add( PhysicalFontFace* ); void Clear(); int Count() const { return maPhysicalFontFamilies.size(); } // find the device font PhysicalFontFamily* FindFontFamily( const OUString& rFontName ) const; PhysicalFontFamily* FindOrCreateFamily( const OUString &rFamilyName ); PhysicalFontFamily* ImplFindByFont( FontSelectPattern& ) const; PhysicalFontFamily* ImplFindBySearchName( const OUString& ) const; // suggest fonts for glyph fallback PhysicalFontFamily* GetGlyphFallbackFont( FontSelectPattern&, OUString& rMissingCodes, int nFallbackLevel ) const; // prepare platform specific font substitutions void SetPreMatchHook( ImplPreMatchFontSubstitution* ); void SetFallbackHook( ImplGlyphFallbackFontSubstitution* ); // misc utilities PhysicalFontCollection* Clone( bool bScalable, bool bEmbeddable ) const; ImplGetDevFontList* GetDevFontList() const; ImplGetDevSizeList* GetDevSizeList( const OUString& rFontName ) const; PhysicalFontFamily* ImplFindByTokenNames(const OUString& rTokenStr) const; protected: void InitMatchData() const; bool AreMapNamesAvailable() const { return mbMapNames; } PhysicalFontFamily* ImplFindByAliasName(const OUString& rSearchName, const OUString& rShortName) const; PhysicalFontFamily* ImplFindBySubstFontAttr( const utl::FontNameAttr& ) const; PhysicalFontFamily* ImplFindByAttributes(sal_uLong nSearchType, FontWeight, FontWidth, FontItalic, const OUString& rSearchFamily) const; PhysicalFontFamily* FindDefaultFont() const; private: void InitGenericGlyphFallback() const; mutable PhysicalFontFamily** mpFallbackList; mutable int mnFallbackCount; }; #endif // INCLUDED_VCL_INC_PHYSICALFONTCOLLECTION_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>can't have an unordered_map of const OUStrings with gcc 4.8.2<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_PHYSICALFONTCOLLECTION_HXX #define INCLUDED_VCL_INC_PHYSICALFONTCOLLECTION_HXX #include <vcl/dllapi.h> #include "outfont.hxx" #include "PhysicalFontFamily.hxx" // - PhysicalFontCollection - // TODO: merge with ImplFontCache // TODO: rename to LogicalFontManager class VCL_PLUGIN_PUBLIC PhysicalFontCollection { private: friend class WinGlyphFallbackSubstititution; mutable bool mbMatchData; // true if matching attributes are initialized bool mbMapNames; // true if MapNames are available typedef std::unordered_map<OUString, PhysicalFontFamily*,OUStringHash> PhysicalFontFamilies; PhysicalFontFamilies maPhysicalFontFamilies; ImplPreMatchFontSubstitution* mpPreMatchHook; // device specific prematch substitution ImplGlyphFallbackFontSubstitution* mpFallbackHook; // device specific glyh fallback substitution public: explicit PhysicalFontCollection(); virtual ~PhysicalFontCollection(); // fill the list with device fonts void Add( PhysicalFontFace* ); void Clear(); int Count() const { return maPhysicalFontFamilies.size(); } // find the device font PhysicalFontFamily* FindFontFamily( const OUString& rFontName ) const; PhysicalFontFamily* FindOrCreateFamily( const OUString &rFamilyName ); PhysicalFontFamily* ImplFindByFont( FontSelectPattern& ) const; PhysicalFontFamily* ImplFindBySearchName( const OUString& ) const; // suggest fonts for glyph fallback PhysicalFontFamily* GetGlyphFallbackFont( FontSelectPattern&, OUString& rMissingCodes, int nFallbackLevel ) const; // prepare platform specific font substitutions void SetPreMatchHook( ImplPreMatchFontSubstitution* ); void SetFallbackHook( ImplGlyphFallbackFontSubstitution* ); // misc utilities PhysicalFontCollection* Clone( bool bScalable, bool bEmbeddable ) const; ImplGetDevFontList* GetDevFontList() const; ImplGetDevSizeList* GetDevSizeList( const OUString& rFontName ) const; PhysicalFontFamily* ImplFindByTokenNames(const OUString& rTokenStr) const; protected: void InitMatchData() const; bool AreMapNamesAvailable() const { return mbMapNames; } PhysicalFontFamily* ImplFindByAliasName(const OUString& rSearchName, const OUString& rShortName) const; PhysicalFontFamily* ImplFindBySubstFontAttr( const utl::FontNameAttr& ) const; PhysicalFontFamily* ImplFindByAttributes(sal_uLong nSearchType, FontWeight, FontWidth, FontItalic, const OUString& rSearchFamily) const; PhysicalFontFamily* FindDefaultFont() const; private: void InitGenericGlyphFallback() const; mutable PhysicalFontFamily** mpFallbackList; mutable int mnFallbackCount; }; #endif // INCLUDED_VCL_INC_PHYSICALFONTCOLLECTION_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** * @file lltimectrl.cpp * @brief LLTimeCtrl base class * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "lltimectrl.h" #include "llui.h" #include "lluiconstants.h" #include "llbutton.h" #include "llfontgl.h" #include "lllineeditor.h" #include "llkeyboard.h" #include "llstring.h" #include "lltextbox.h" #include "lluictrlfactory.h" static LLDefaultChildRegistry::Register<LLTimeCtrl> time_r("time"); const U32 AMPM_LEN = 3; const U32 MINUTES_MIN = 0; const U32 MINUTES_MAX = 59; const U32 HOURS_MIN = 1; const U32 HOURS_MAX = 12; LLTimeCtrl::Params::Params() : label_width("label_width"), allow_text_entry("allow_text_entry", true), text_enabled_color("text_enabled_color"), text_disabled_color("text_disabled_color"), up_button("up_button"), down_button("down_button") {} LLTimeCtrl::LLTimeCtrl(const LLTimeCtrl::Params& p) : LLUICtrl(p), mLabelBox(NULL), mTextEnabledColor(p.text_enabled_color()), mTextDisabledColor(p.text_disabled_color()), mHours(HOURS_MIN), mMinutes(MINUTES_MIN) { static LLUICachedControl<S32> spinctrl_spacing ("UISpinctrlSpacing", 0); static LLUICachedControl<S32> spinctrl_btn_width ("UISpinctrlBtnWidth", 0); static LLUICachedControl<S32> spinctrl_btn_height ("UISpinctrlBtnHeight", 0); S32 centered_top = getRect().getHeight(); S32 centered_bottom = getRect().getHeight() - 2 * spinctrl_btn_height; S32 label_width = llclamp(p.label_width(), 0, llmax(0, getRect().getWidth() - 40)); S32 editor_left = label_width + spinctrl_spacing; //================= Label =================// if( !p.label().empty() ) { LLRect label_rect( 0, centered_top, label_width, centered_bottom ); LLTextBox::Params params; params.name("TimeCtrl Label"); params.rect(label_rect); params.initial_value(p.label()); if (p.font.isProvided()) { params.font(p.font); } mLabelBox = LLUICtrlFactory::create<LLTextBox> (params); addChild(mLabelBox); editor_left = label_rect.mRight + spinctrl_spacing; } S32 editor_right = getRect().getWidth() - spinctrl_btn_width - spinctrl_spacing; //================= Editor ================// LLRect editor_rect( editor_left, centered_top, editor_right, centered_bottom ); LLLineEditor::Params params; params.name("SpinCtrl Editor"); params.rect(editor_rect); if (p.font.isProvided()) { params.font(p.font); } params.follows.flags(FOLLOWS_LEFT | FOLLOWS_BOTTOM); params.max_length.chars(8); params.keystroke_callback(boost::bind(&LLTimeCtrl::onTextEntry, this, _1)); mEditor = LLUICtrlFactory::create<LLLineEditor> (params); mEditor->setPrevalidateInput(LLTextValidate::validateNonNegativeS32NoSpace); mEditor->setPrevalidate(boost::bind(&LLTimeCtrl::isTimeStringValid, this, _1)); mEditor->setText(LLStringExplicit("0:00 AM")); addChild(mEditor); //================= Spin Buttons ==========// LLButton::Params up_button_params(p.up_button); up_button_params.rect = LLRect(editor_right + 1, getRect().getHeight(), editor_right + spinctrl_btn_width, getRect().getHeight() - spinctrl_btn_height); up_button_params.click_callback.function(boost::bind(&LLTimeCtrl::onUpBtn, this)); up_button_params.mouse_held_callback.function(boost::bind(&LLTimeCtrl::onUpBtn, this)); mUpBtn = LLUICtrlFactory::create<LLButton>(up_button_params); addChild(mUpBtn); LLButton::Params down_button_params(p.down_button); down_button_params.rect = LLRect(editor_right + 1, getRect().getHeight() - spinctrl_btn_height, editor_right + spinctrl_btn_width, getRect().getHeight() - 2 * spinctrl_btn_height); down_button_params.click_callback.function(boost::bind(&LLTimeCtrl::onDownBtn, this)); down_button_params.mouse_held_callback.function(boost::bind(&LLTimeCtrl::onDownBtn, this)); mDownBtn = LLUICtrlFactory::create<LLButton>(down_button_params); addChild(mDownBtn); setUseBoundingRect( TRUE ); } BOOL LLTimeCtrl::handleKeyHere(KEY key, MASK mask) { if (mEditor->hasFocus()) { if(key == KEY_UP) { onUpBtn(); return TRUE; } if(key == KEY_DOWN) { onDownBtn(); return TRUE; } } return FALSE; } void LLTimeCtrl::onUpBtn() { switch(getEditingPart()) { case HOURS: increaseHours(); break; case MINUTES: increaseMinutes(); break; case DAYPART: switchDayPeriod(); break; default: break; } buildTimeString(); mEditor->setText(mTimeString); } void LLTimeCtrl::onDownBtn() { switch(getEditingPart()) { case HOURS: decreaseHours(); break; case MINUTES: decreaseMinutes(); break; case DAYPART: switchDayPeriod(); break; default: break; } buildTimeString(); mEditor->setText(mTimeString); } void LLTimeCtrl::onFocusLost() { buildTimeString(); mEditor->setText(mTimeString); LLUICtrl::onFocusLost(); } void LLTimeCtrl::onTextEntry(LLLineEditor* line_editor) { LLWString time_str = line_editor->getWText(); switch(getEditingPart()) { case HOURS: validateHours(getHoursWString(time_str)); break; case MINUTES: validateMinutes(getMinutesWString(time_str)); break; default: break; } } bool LLTimeCtrl::isTimeStringValid(const LLWString &wstr) { if (!isHoursStringValid(getHoursWString(wstr)) || !isMinutesStringValid(getMinutesWString(wstr)) || !isPMAMStringValid(wstr)) return false; return true; } bool LLTimeCtrl::isHoursStringValid(const LLWString& wstr) { U32 hours; if ((!LLWStringUtil::convertToU32(wstr, hours) || (hours <= HOURS_MAX)) && wstr.length() < 3) return true; return false; } bool LLTimeCtrl::isMinutesStringValid(const LLWString& wstr) { U32 minutes; if (!LLWStringUtil::convertToU32(wstr, minutes) || (minutes <= MINUTES_MAX) && wstr.length() < 3) return true; return false; } void LLTimeCtrl::validateHours(const LLWString& wstr) { U32 hours; if (LLWStringUtil::convertToU32(wstr, hours) && (hours >= HOURS_MIN) && (hours <= HOURS_MAX)) { mHours = hours; } else { mHours = HOURS_MIN; } } void LLTimeCtrl::validateMinutes(const LLWString& wstr) { U32 minutes; if (LLWStringUtil::convertToU32(wstr, minutes) && (minutes >= MINUTES_MIN) && (minutes <= MINUTES_MAX)) { mMinutes = minutes; } else { mMinutes = MINUTES_MIN; } } bool LLTimeCtrl::isPMAMStringValid(const LLWString &wstr) { S32 len = wstr.length(); bool valid = (wstr[--len] == 'M') && (wstr[--len] == 'P' || wstr[len] == 'A'); return valid; } LLWString LLTimeCtrl::getHoursWString(const LLWString& wstr) { size_t colon_index = wstr.find_first_of(':'); LLWString hours_str = wstr.substr(0, colon_index); return hours_str; } LLWString LLTimeCtrl::getMinutesWString(const LLWString& wstr) { size_t colon_index = wstr.find_first_of(':'); ++colon_index; int minutes_len = wstr.length() - colon_index - AMPM_LEN; LLWString minutes_str = wstr.substr(colon_index, minutes_len); return minutes_str; } void LLTimeCtrl::increaseMinutes() { if (++mMinutes > MINUTES_MAX) { mMinutes = MINUTES_MIN; } } void LLTimeCtrl::increaseHours() { if (++mHours > HOURS_MAX) { mHours = HOURS_MIN; } } void LLTimeCtrl::decreaseMinutes() { if (mMinutes-- == MINUTES_MIN) { mMinutes = MINUTES_MAX; } } void LLTimeCtrl::decreaseHours() { if (mHours-- == HOURS_MIN) { mHours = HOURS_MAX; switchDayPeriod(); } } void LLTimeCtrl::switchDayPeriod() { switch (mCurrentDayPeriod) { case AM: mCurrentDayPeriod = PM; break; case PM: mCurrentDayPeriod = AM; break; } } void LLTimeCtrl::buildTimeString() { std::stringstream time_buf; time_buf << mHours << ":"; if (mMinutes < 10) { time_buf << "0"; } time_buf << mMinutes; time_buf << " "; switch (mCurrentDayPeriod) { case AM: time_buf << "AM"; break; case PM: time_buf << "PM"; break; } mTimeString = time_buf.str(); } LLTimeCtrl::EEditingPart LLTimeCtrl::getEditingPart() { S32 cur_pos = mEditor->getCursor(); LLWString time_str = mEditor->getWText(); size_t colon_index = time_str.find_first_of(':'); if (cur_pos <= colon_index) { return HOURS; } else if (cur_pos > colon_index && cur_pos <= (time_str.length() - AMPM_LEN)) { return MINUTES; } else if (cur_pos > (time_str.length() - AMPM_LEN)) { return DAYPART; } return NONE; } <commit_msg>STORM-1202 ADDITIONAL_FIX Fixing Windows build.<commit_after>/** * @file lltimectrl.cpp * @brief LLTimeCtrl base class * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "lltimectrl.h" #include "llui.h" #include "lluiconstants.h" #include "llbutton.h" #include "llfontgl.h" #include "lllineeditor.h" #include "llkeyboard.h" #include "llstring.h" #include "lltextbox.h" #include "lluictrlfactory.h" static LLDefaultChildRegistry::Register<LLTimeCtrl> time_r("time"); const U32 AMPM_LEN = 3; const U32 MINUTES_MIN = 0; const U32 MINUTES_MAX = 59; const U32 HOURS_MIN = 1; const U32 HOURS_MAX = 12; LLTimeCtrl::Params::Params() : label_width("label_width"), allow_text_entry("allow_text_entry", true), text_enabled_color("text_enabled_color"), text_disabled_color("text_disabled_color"), up_button("up_button"), down_button("down_button") {} LLTimeCtrl::LLTimeCtrl(const LLTimeCtrl::Params& p) : LLUICtrl(p), mLabelBox(NULL), mTextEnabledColor(p.text_enabled_color()), mTextDisabledColor(p.text_disabled_color()), mHours(HOURS_MIN), mMinutes(MINUTES_MIN) { static LLUICachedControl<S32> spinctrl_spacing ("UISpinctrlSpacing", 0); static LLUICachedControl<S32> spinctrl_btn_width ("UISpinctrlBtnWidth", 0); static LLUICachedControl<S32> spinctrl_btn_height ("UISpinctrlBtnHeight", 0); S32 centered_top = getRect().getHeight(); S32 centered_bottom = getRect().getHeight() - 2 * spinctrl_btn_height; S32 label_width = llclamp(p.label_width(), 0, llmax(0, getRect().getWidth() - 40)); S32 editor_left = label_width + spinctrl_spacing; //================= Label =================// if( !p.label().empty() ) { LLRect label_rect( 0, centered_top, label_width, centered_bottom ); LLTextBox::Params params; params.name("TimeCtrl Label"); params.rect(label_rect); params.initial_value(p.label()); if (p.font.isProvided()) { params.font(p.font); } mLabelBox = LLUICtrlFactory::create<LLTextBox> (params); addChild(mLabelBox); editor_left = label_rect.mRight + spinctrl_spacing; } S32 editor_right = getRect().getWidth() - spinctrl_btn_width - spinctrl_spacing; //================= Editor ================// LLRect editor_rect( editor_left, centered_top, editor_right, centered_bottom ); LLLineEditor::Params params; params.name("SpinCtrl Editor"); params.rect(editor_rect); if (p.font.isProvided()) { params.font(p.font); } params.follows.flags(FOLLOWS_LEFT | FOLLOWS_BOTTOM); params.max_length.chars(8); params.keystroke_callback(boost::bind(&LLTimeCtrl::onTextEntry, this, _1)); mEditor = LLUICtrlFactory::create<LLLineEditor> (params); mEditor->setPrevalidateInput(LLTextValidate::validateNonNegativeS32NoSpace); mEditor->setPrevalidate(boost::bind(&LLTimeCtrl::isTimeStringValid, this, _1)); mEditor->setText(LLStringExplicit("0:00 AM")); addChild(mEditor); //================= Spin Buttons ==========// LLButton::Params up_button_params(p.up_button); up_button_params.rect = LLRect(editor_right + 1, getRect().getHeight(), editor_right + spinctrl_btn_width, getRect().getHeight() - spinctrl_btn_height); up_button_params.click_callback.function(boost::bind(&LLTimeCtrl::onUpBtn, this)); up_button_params.mouse_held_callback.function(boost::bind(&LLTimeCtrl::onUpBtn, this)); mUpBtn = LLUICtrlFactory::create<LLButton>(up_button_params); addChild(mUpBtn); LLButton::Params down_button_params(p.down_button); down_button_params.rect = LLRect(editor_right + 1, getRect().getHeight() - spinctrl_btn_height, editor_right + spinctrl_btn_width, getRect().getHeight() - 2 * spinctrl_btn_height); down_button_params.click_callback.function(boost::bind(&LLTimeCtrl::onDownBtn, this)); down_button_params.mouse_held_callback.function(boost::bind(&LLTimeCtrl::onDownBtn, this)); mDownBtn = LLUICtrlFactory::create<LLButton>(down_button_params); addChild(mDownBtn); setUseBoundingRect( TRUE ); } BOOL LLTimeCtrl::handleKeyHere(KEY key, MASK mask) { if (mEditor->hasFocus()) { if(key == KEY_UP) { onUpBtn(); return TRUE; } if(key == KEY_DOWN) { onDownBtn(); return TRUE; } } return FALSE; } void LLTimeCtrl::onUpBtn() { switch(getEditingPart()) { case HOURS: increaseHours(); break; case MINUTES: increaseMinutes(); break; case DAYPART: switchDayPeriod(); break; default: break; } buildTimeString(); mEditor->setText(mTimeString); } void LLTimeCtrl::onDownBtn() { switch(getEditingPart()) { case HOURS: decreaseHours(); break; case MINUTES: decreaseMinutes(); break; case DAYPART: switchDayPeriod(); break; default: break; } buildTimeString(); mEditor->setText(mTimeString); } void LLTimeCtrl::onFocusLost() { buildTimeString(); mEditor->setText(mTimeString); LLUICtrl::onFocusLost(); } void LLTimeCtrl::onTextEntry(LLLineEditor* line_editor) { LLWString time_str = line_editor->getWText(); switch(getEditingPart()) { case HOURS: validateHours(getHoursWString(time_str)); break; case MINUTES: validateMinutes(getMinutesWString(time_str)); break; default: break; } } bool LLTimeCtrl::isTimeStringValid(const LLWString &wstr) { if (!isHoursStringValid(getHoursWString(wstr)) || !isMinutesStringValid(getMinutesWString(wstr)) || !isPMAMStringValid(wstr)) return false; return true; } bool LLTimeCtrl::isHoursStringValid(const LLWString& wstr) { U32 hours; if ((!LLWStringUtil::convertToU32(wstr, hours) || (hours <= HOURS_MAX)) && wstr.length() < 3) return true; return false; } bool LLTimeCtrl::isMinutesStringValid(const LLWString& wstr) { U32 minutes; if (!LLWStringUtil::convertToU32(wstr, minutes) || (minutes <= MINUTES_MAX) && wstr.length() < 3) return true; return false; } void LLTimeCtrl::validateHours(const LLWString& wstr) { U32 hours; if (LLWStringUtil::convertToU32(wstr, hours) && (hours >= HOURS_MIN) && (hours <= HOURS_MAX)) { mHours = hours; } else { mHours = HOURS_MIN; } } void LLTimeCtrl::validateMinutes(const LLWString& wstr) { U32 minutes; if (LLWStringUtil::convertToU32(wstr, minutes) && (minutes >= MINUTES_MIN) && (minutes <= MINUTES_MAX)) { mMinutes = minutes; } else { mMinutes = MINUTES_MIN; } } bool LLTimeCtrl::isPMAMStringValid(const LLWString &wstr) { S32 len = wstr.length(); bool valid = (wstr[--len] == 'M') && (wstr[--len] == 'P' || wstr[len] == 'A'); return valid; } LLWString LLTimeCtrl::getHoursWString(const LLWString& wstr) { size_t colon_index = wstr.find_first_of(':'); LLWString hours_str = wstr.substr(0, colon_index); return hours_str; } LLWString LLTimeCtrl::getMinutesWString(const LLWString& wstr) { size_t colon_index = wstr.find_first_of(':'); ++colon_index; int minutes_len = wstr.length() - colon_index - AMPM_LEN; LLWString minutes_str = wstr.substr(colon_index, minutes_len); return minutes_str; } void LLTimeCtrl::increaseMinutes() { if (++mMinutes > MINUTES_MAX) { mMinutes = MINUTES_MIN; } } void LLTimeCtrl::increaseHours() { if (++mHours > HOURS_MAX) { mHours = HOURS_MIN; } } void LLTimeCtrl::decreaseMinutes() { if (mMinutes-- == MINUTES_MIN) { mMinutes = MINUTES_MAX; } } void LLTimeCtrl::decreaseHours() { if (mHours-- == HOURS_MIN) { mHours = HOURS_MAX; switchDayPeriod(); } } void LLTimeCtrl::switchDayPeriod() { switch (mCurrentDayPeriod) { case AM: mCurrentDayPeriod = PM; break; case PM: mCurrentDayPeriod = AM; break; } } void LLTimeCtrl::buildTimeString() { std::stringstream time_buf; time_buf << mHours << ":"; if (mMinutes < 10) { time_buf << "0"; } time_buf << mMinutes; time_buf << " "; switch (mCurrentDayPeriod) { case AM: time_buf << "AM"; break; case PM: time_buf << "PM"; break; } mTimeString = time_buf.str(); } LLTimeCtrl::EEditingPart LLTimeCtrl::getEditingPart() { S32 cur_pos = mEditor->getCursor(); LLWString time_str = mEditor->getWText(); S32 colon_index = time_str.find_first_of(':'); if (cur_pos <= colon_index) { return HOURS; } else if (cur_pos > colon_index && cur_pos <= (S32)(time_str.length() - AMPM_LEN)) { return MINUTES; } else if (cur_pos > (S32)(time_str.length() - AMPM_LEN)) { return DAYPART; } return NONE; } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH #define DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH #include <type_traits> #include <limits> #include <boost/numeric/conversion/cast.hpp> #include <dune/common/dynmatrix.hh> #include <dune/geometry/quadraturerules.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/functions/constant.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/localevaluation/swipdg.hh> #include <dune/gdt/spaces/rt/pdelab.hh> namespace Dune { namespace GDT { namespace Operators { template< class GridViewType, class DiffusionFactorType, class DiffusionTensorType = void > class DiffusiveFluxReconstruction; /** * \todo Add more static checks that GridViewType and LocalizableFunctionType match. * \todo Derive from operator interfaces. */ template< class GridViewType, class LocalizableFunctionType > class DiffusiveFluxReconstruction< GridViewType, LocalizableFunctionType, void > { static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!"); static_assert(std::is_base_of< Stuff::IsLocalizableFunction, LocalizableFunctionType >::value, "LocalizableFunctionType has to be tagged as Stuff::IsLocalizableFunction!"); public: typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; typedef typename LocalizableFunctionType::RangeFieldType FieldType; typedef typename LocalizableFunctionType::DomainType DomainType; private: static_assert(dimDomain == 2, "Not implemented!"); public: DiffusiveFluxReconstruction(const GridViewType& grid_view, const LocalizableFunctionType& diffusion, const size_t over_integrate = 0) : grid_view_(grid_view) , diffusion_(diffusion) , over_integrate_(over_integrate) {} template< class GV, class V > void apply(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1 >& source, DiscreteFunction< Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >, V >& range) const { const auto& rtn0_space = range.space(); auto& range_vector = range.vector(); const FieldType infinity = std::numeric_limits< FieldType >::infinity(); for (size_t ii = 0; ii < range_vector.size(); ++ii) range_vector[ii] = infinity; const LocalEvaluation::SWIPDG::Inner< LocalizableFunctionType > inner_evaluation(diffusion_); const LocalEvaluation::SWIPDG::BoundaryLHS< LocalizableFunctionType > boundary_evaluation(diffusion_); const Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, FieldType, 1 > constant_one(1); DomainType normal(0); DomainType xx_entity(0); DynamicMatrix< FieldType > tmp_matrix(1, 1, 0); DynamicMatrix< FieldType > tmp_matrix_en_en(1, 1, 0); DynamicMatrix< FieldType > tmp_matrix_en_ne(1, 1, 0); std::vector< typename Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType > basis_values(rtn0_space.mapper().maxNumDofs(), typename Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType(0)); // walk the grid const auto entity_it_end = grid_view_.template end< 0 >(); for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity); const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity); assert(global_DoF_indices.size() == local_DoF_indices.size()); const auto local_diffusion = diffusion_.local_function(entity); const auto local_source = source.local_function(entity); const auto local_basis = rtn0_space.base_function_set(entity); const auto local_constant_one = constant_one.local_function(entity); // walk the intersections const auto intersection_it_end = grid_view_.iend(entity); for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; if (intersection.neighbor() && !intersection.boundary()) { const auto neighbor_ptr = intersection.outside(); const auto& neighbor = *neighbor_ptr; if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) { const auto local_diffusion_neighbor = diffusion_.local_function(neighbor); const auto local_source_neighbor = source.local_function(neighbor); const auto local_constant_one_neighbor = constant_one.local_function(neighbor); const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = inner_evaluation.order(*local_diffusion, *local_diffusion_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule( intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto& xx_intersection = quadrature_it->position(); xx_entity = intersection.geometryInInside().global(xx_intersection); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; tmp_matrix_en_en *= 0.0; tmp_matrix_en_ne *= 0.0; inner_evaluation.evaluate(*local_diffusion, *local_diffusion_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor, intersection, xx_intersection, tmp_matrix_en_en, // <- we are interested in this one tmp_matrix, tmp_matrix_en_ne, // <- and this one tmp_matrix); // compute integrals assert(tmp_matrix_en_en.rows() >= 1); assert(tmp_matrix_en_en.cols() >= 1); assert(tmp_matrix_en_ne.rows() >= 1); assert(tmp_matrix_en_ne.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]); } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; // and make sure we are the first to do so assert(!(range_vector[global_DoF_index] < infinity)); range_vector[global_DoF_index] = rhs / lhs; } } else if (intersection.boundary() && !intersection.neighbor()) { const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = boundary_evaluation.order(*local_diffusion, *local_source, *local_constant_one); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule( intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx_intersection = quadrature_it->position(); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); xx_entity = intersection.geometryInInside().global(xx_intersection); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; boundary_evaluation.evaluate(*local_diffusion, *local_constant_one, *local_source, intersection, xx_intersection, tmp_matrix); // compute integrals assert(tmp_matrix.rows() >= 1); assert(tmp_matrix.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * tmp_matrix[0][0]; } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; assert(!(range_vector[global_DoF_index] < infinity)); // and make sure we are the first to do so range_vector[global_DoF_index] = rhs / lhs; } else DUNE_THROW(Stuff::Exceptions::internal_error, "Unknown intersection type!"); } // walk the intersections } // walk the grid } // ... apply(...) private: const GridViewType& grid_view_; const LocalizableFunctionType& diffusion_; const size_t over_integrate_; }; // class DiffusiveFluxReconstruction } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH <commit_msg>[operators.fluxreconstruction] modernize<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH #define DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH #include <type_traits> #include <limits> #include <boost/numeric/conversion/cast.hpp> #include <dune/common/dynmatrix.hh> #include <dune/geometry/quadraturerules.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/functions/constant.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/localevaluation/swipdg.hh> #include <dune/gdt/spaces/rt/pdelab.hh> namespace Dune { namespace GDT { namespace Operators { template< class GridViewType, class DiffusionFactorType, class DiffusionTensorType = void > class DiffusiveFluxReconstruction; /** * \todo Add more static checks that GridViewType and LocalizableFunctionType match. * \todo Derive from operator interfaces. */ template< class GridViewType, class LocalizableFunctionType > class DiffusiveFluxReconstruction< GridViewType, LocalizableFunctionType, void > { static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!"); static_assert(Stuff::is_localizable_function< LocalizableFunctionType >::value, "LocalizableFunctionType has to be tagged as Stuff::IsLocalizableFunction!"); public: typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; typedef typename LocalizableFunctionType::RangeFieldType FieldType; typedef typename LocalizableFunctionType::DomainType DomainType; private: static_assert(dimDomain == 2, "Not implemented!"); public: DiffusiveFluxReconstruction(const GridViewType& grid_view, const LocalizableFunctionType& diffusion, const size_t over_integrate = 0) : grid_view_(grid_view) , diffusion_(diffusion) , over_integrate_(over_integrate) {} template< class GV, class V > void apply(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1 >& source, DiscreteFunction< Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >, V >& range) const { const auto& rtn0_space = range.space(); auto& range_vector = range.vector(); const FieldType infinity = std::numeric_limits< FieldType >::infinity(); for (size_t ii = 0; ii < range_vector.size(); ++ii) range_vector[ii] = infinity; const LocalEvaluation::SWIPDG::Inner< LocalizableFunctionType > inner_evaluation(diffusion_); const LocalEvaluation::SWIPDG::BoundaryLHS< LocalizableFunctionType > boundary_evaluation(diffusion_); const Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, FieldType, 1 > constant_one(1); DomainType normal(0); DomainType xx_entity(0); DynamicMatrix< FieldType > tmp_matrix(1, 1, 0); DynamicMatrix< FieldType > tmp_matrix_en_en(1, 1, 0); DynamicMatrix< FieldType > tmp_matrix_en_ne(1, 1, 0); std::vector< typename Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType > basis_values(rtn0_space.mapper().maxNumDofs(), typename Spaces::RT::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType(0)); // walk the grid const auto entity_it_end = grid_view_.template end< 0 >(); for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity); const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity); assert(global_DoF_indices.size() == local_DoF_indices.size()); const auto local_diffusion = diffusion_.local_function(entity); const auto local_source = source.local_function(entity); const auto local_basis = rtn0_space.base_function_set(entity); const auto local_constant_one = constant_one.local_function(entity); // walk the intersections const auto intersection_it_end = grid_view_.iend(entity); for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; if (intersection.neighbor() && !intersection.boundary()) { const auto neighbor_ptr = intersection.outside(); const auto& neighbor = *neighbor_ptr; if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) { const auto local_diffusion_neighbor = diffusion_.local_function(neighbor); const auto local_source_neighbor = source.local_function(neighbor); const auto local_constant_one_neighbor = constant_one.local_function(neighbor); const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = inner_evaluation.order(*local_diffusion, *local_diffusion_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule( intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto& xx_intersection = quadrature_it->position(); xx_entity = intersection.geometryInInside().global(xx_intersection); normal = intersection.unitOuterNormal(xx_intersection); const auto integration_factor = intersection.geometry().integrationElement(xx_intersection); const auto weigth = quadrature_it->weight(); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; tmp_matrix_en_en *= 0.0; tmp_matrix_en_ne *= 0.0; inner_evaluation.evaluate(*local_diffusion, *local_diffusion_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor, intersection, xx_intersection, tmp_matrix_en_en, // <- we are interested in this one tmp_matrix, tmp_matrix_en_ne, // <- and this one tmp_matrix); // compute integrals assert(tmp_matrix_en_en.rows() >= 1); assert(tmp_matrix_en_en.cols() >= 1); assert(tmp_matrix_en_ne.rows() >= 1); assert(tmp_matrix_en_ne.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]); } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; // and make sure we are the first to do so assert(!(range_vector[global_DoF_index] < infinity)); range_vector[global_DoF_index] = rhs / lhs; } } else if (intersection.boundary() && !intersection.neighbor()) { const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = boundary_evaluation.order(*local_diffusion, *local_source, *local_constant_one); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule( intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx_intersection = quadrature_it->position(); normal = intersection.unitOuterNormal(xx_intersection); const auto integration_factor = intersection.geometry().integrationElement(xx_intersection); const auto weigth = quadrature_it->weight(); xx_entity = intersection.geometryInInside().global(xx_intersection); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; boundary_evaluation.evaluate(*local_diffusion, *local_constant_one, *local_source, intersection, xx_intersection, tmp_matrix); // compute integrals assert(tmp_matrix.rows() >= 1); assert(tmp_matrix.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * tmp_matrix[0][0]; } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; assert(!(range_vector[global_DoF_index] < infinity)); // and make sure we are the first to do so range_vector[global_DoF_index] = rhs / lhs; } else DUNE_THROW(Stuff::Exceptions::internal_error, "Unknown intersection type!"); } // walk the intersections } // walk the grid } // ... apply(...) private: const GridViewType& grid_view_; const LocalizableFunctionType& diffusion_; const size_t over_integrate_; }; // class DiffusiveFluxReconstruction } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH <|endoftext|>
<commit_before>#include <ompl/base/ScopedState.h> #include <ompl/base/spaces/RealVectorBounds.h> #include <ompl/base/spaces/RealVectorStateSpace.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <ompl/base/State.h> #include <ompl/control/planners/syclop/Syclop.h> #include <ompl/control/planners/syclop/SyclopRRT.h> #include <ompl/control/planners/syclop/GridDecomposition.h> #include <ompl/control/spaces/RealVectorControlSpace.h> #include <ompl/util/RandomNumbers.h> #define BOOST_NO_HASH #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/adjacency_list.hpp> #include <cmath> #include <iostream> #include <vector> namespace ob = ompl::base; namespace oc = ompl::control; class TestDecomposition : public oc::GridDecomposition { public: TestDecomposition(const int length, ob::RealVectorBounds &bounds) : oc::GridDecomposition(length, 2, bounds) { } virtual ~TestDecomposition() { } virtual int locateRegion(const ob::State *s) { const ob::CompoundState *cs = s->as<ob::CompoundState>(); const ob::SE2StateSpace::StateType *ws = cs->as<ob::SE2StateSpace::StateType>(0); std::vector<double> coord(2); coord[0] = ws->getX(); coord[1] = ws->getY(); return oc::GridDecomposition::locateRegion(coord); } virtual void stateToCoord(const ob::State *s, std::vector<double>& coord) { const ob::CompoundState *cs = s->as<ob::CompoundState>(); const ob::SE2StateSpace::StateType *ws = cs->as<ob::SE2StateSpace::StateType>(0); coord.resize(2); coord[0] = ws->getX(); coord[1] = ws->getY(); } }; bool isStateValid(const ob::State *s) { const ob::CompoundStateSpace::StateType *cs = s->as<ob::CompoundStateSpace::StateType>(); const ob::SE2StateSpace::StateType *se = cs->as<ob::SE2StateSpace::StateType>(0); const double x = se->getX(); const double y = se->getY(); if (x < -0.5 && y < 0.5) return false; if (x > 0.5 && fabs(y) < 0.5) return false; return true; } int main(void) { ompl::base::RealVectorBounds bounds(2); bounds.setLow(-1); bounds.setHigh(1); TestDecomposition grid(2, bounds); ob::RealVectorBounds cbounds(1); cbounds.setLow(-1); cbounds.setHigh(1); ob::StateSpacePtr manifold(new ob::CompoundStateSpace()); ob::StateSpacePtr locSpace(new ob::SE2StateSpace()); locSpace->as<ob::SE2StateSpace>()->setBounds(bounds); ob::StateSpacePtr velSpace(new ob::RealVectorStateSpace(1)); velSpace->as<ob::RealVectorStateSpace>()->setBounds(cbounds); manifold->as<ob::CompoundStateSpace>()->addSubSpace(locSpace, 0.8); manifold->as<ob::CompoundStateSpace>()->addSubSpace(velSpace, 0.2); oc::ControlSpacePtr controlSpace(new oc::RealVectorControlSpace(manifold, 1)); controlSpace->as<oc::RealVectorControlSpace>()->setBounds(cbounds); ob::ScopedState<ob::CompoundStateSpace> init(manifold); ob::SE2StateSpace::StateType *se = init->as<ob::SE2StateSpace::StateType>(0); se->setX(-0.75); se->setY(0.8); se->setYaw(0); init->as<ob::RealVectorStateSpace::StateType>(1)->values[0] = 0; ob::ScopedState<ob::CompoundStateSpace> goal(init); se = goal->as<ob::SE2StateSpace::StateType>(0); se->setX(0.65); se->setY(-0.7); oc::SpaceInformationPtr si(new oc::SpaceInformation(manifold, controlSpace)); si->setStateValidityChecker(boost::bind(&isStateValid, _1)); si->setup(); ob::ProblemDefinitionPtr pdef(new ob::ProblemDefinition(si)); pdef->setStartAndGoalStates(init, goal, 0.05); oc::SyclopRRT planner(si, grid); planner.setProblemDefinition(pdef); planner.setup(); planner.solve(1.0); return 0; } <commit_msg>updated demo to plan with controls, for initial syclop test<commit_after>#include <ompl/base/ScopedState.h> #include <ompl/base/spaces/RealVectorBounds.h> #include <ompl/base/spaces/RealVectorStateSpace.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <ompl/base/State.h> #include <ompl/control/planners/syclop/Syclop.h> #include <ompl/control/planners/syclop/SyclopRRT.h> #include <ompl/control/planners/syclop/GridDecomposition.h> #include <ompl/control/spaces/RealVectorControlSpace.h> #include <ompl/util/RandomNumbers.h> #define BOOST_NO_HASH #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/adjacency_list.hpp> #include <cmath> #include <iostream> #include <vector> namespace ob = ompl::base; namespace oc = ompl::control; class TestDecomposition : public oc::GridDecomposition { public: TestDecomposition(const int length, ob::RealVectorBounds &bounds) : oc::GridDecomposition(length, 2, bounds) { } virtual ~TestDecomposition() { } virtual int locateRegion(const ob::State *s) { const ob::CompoundState *cs = s->as<ob::CompoundState>(); const ob::SE2StateSpace::StateType *ws = cs->as<ob::SE2StateSpace::StateType>(0); std::vector<double> coord(2); coord[0] = ws->getX(); coord[1] = ws->getY(); return oc::GridDecomposition::locateRegion(coord); } virtual void stateToCoord(const ob::State *s, std::vector<double>& coord) { const ob::CompoundState *cs = s->as<ob::CompoundState>(); const ob::SE2StateSpace::StateType *ws = cs->as<ob::SE2StateSpace::StateType>(0); coord.resize(2); coord[0] = ws->getX(); coord[1] = ws->getY(); } }; bool isStateValid(const ob::State *s) { const ob::CompoundStateSpace::StateType *cs = s->as<ob::CompoundStateSpace::StateType>(); const ob::SE2StateSpace::StateType *se = cs->as<ob::SE2StateSpace::StateType>(0); const double x = se->getX(); const double y = se->getY(); if (x < -0.5 && y < 0.5) return false; if (x > 0.5 && fabs(y) < 0.5) return false; return true; } void propagate(const ob::State *start, const oc::Control *control, const double duration, ob::State *result) { const ob::SE2StateSpace::StateType* location = start->as<ob::SE2StateSpace::StateType>(); const oc::RealVectorControlSpace::ControlType* ctrl = control->as<oc::RealVectorControlSpace::ControlType>(); const double x = location->getX(); const double y = location->getY(); const double angle = location->getYaw(); const double velocity = (*ctrl)[0]; const double steerVelocity = (*ctrl)[1]; ob::SE2StateSpace::StateType* newLocation = result->as<ob::SE2StateSpace::StateType>(); newLocation->setXY(x + velocity*duration*cos(angle), y + velocity*duration*sin(angle)); newLocation->setYaw(angle + duration*steerVelocity); } int main(void) { ompl::base::RealVectorBounds bounds(2); bounds.setLow(-1); bounds.setHigh(1); TestDecomposition grid(2, bounds); ob::RealVectorBounds cbounds(2); cbounds.setLow(-2); cbounds.setHigh(2); ob::StateSpacePtr manifold(new ob::SE2StateSpace()); manifold->as<ob::SE2StateSpace>()->setBounds(bounds); //controlSpace : forward acceleration & steer velocity oc::ControlSpacePtr controlSpace(new oc::RealVectorControlSpace(manifold, 2)); controlSpace->as<oc::RealVectorControlSpace>()->setBounds(cbounds); controlSpace->setPropagationFunction(boost::bind(&propagate, _1, _2, _3, _4)); ob::ScopedState<ob::SE2StateSpace> init(manifold); init->setX(-0.75); init->setY(0.8); init->setYaw(0); ob::ScopedState<ob::SE2StateSpace> goal(init); goal->setX(0.65); goal->setY(-0.7); oc::SpaceInformationPtr si(new oc::SpaceInformation(manifold, controlSpace)); si->setStateValidityChecker(boost::bind(&isStateValid, _1)); si->setup(); ob::ProblemDefinitionPtr pdef(new ob::ProblemDefinition(si)); pdef->setStartAndGoalStates(init, goal, 0.05); oc::SyclopRRT planner(si, grid); planner.setProblemDefinition(pdef); planner.setup(); planner.solve(1.0); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: taskpanelist.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ssa $ $Date: 2002-03-22 13:08:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _RCID_H #include <rcid.h> #endif #ifndef _SV_DOCKWIN_HXX #include <dockwin.hxx> #endif #include <taskpanelist.hxx> #include <functional> #include <algorithm> // can't have static linkage because SUNPRO 5.2 complains Point ImplTaskPaneListGetPos( const Window *w ) { Point pos; if( w->ImplIsDockingWindow() ) { pos = ((DockingWindow*)w)->GetPosPixel(); Window *pF = ((DockingWindow*)w)->GetFloatingWindow(); if( pF ) pos = pF->OutputToAbsoluteScreenPixel( pF->ScreenToOutputPixel( pos ) ); else pos = w->OutputToAbsoluteScreenPixel( pos ); } else pos = w->OutputToAbsoluteScreenPixel( w->GetPosPixel() ); return pos; } // compares window pos left-to-right struct LTRSort : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w1, const Window* w2 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; struct LTRSortBackward : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w2, const Window* w1 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; // -------------------------------------------------- TaskPaneList::TaskPaneList() { } TaskPaneList::~TaskPaneList() { } // -------------------------------------------------- void TaskPaneList::AddWindow( Window *pWindow ) { bool bDockingWindow=false; bool bToolbox=false; bool bDialog=false; bool bUnknown=false; if( pWindow ) { if( pWindow->GetType() == RSC_DOCKINGWINDOW ) bDockingWindow = true; else if( pWindow->GetType() == RSC_TOOLBOX ) bToolbox = true; else if( pWindow->IsDialog() ) bDialog = true; else bUnknown = true; ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); // avoid duplicates if( p == mTaskPanes.end() ) // not found mTaskPanes.push_back( pWindow ); } } // -------------------------------------------------- void TaskPaneList::RemoveWindow( Window *pWindow ) { ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); if( p != mTaskPanes.end() ) mTaskPanes.erase( p ); } // -------------------------------------------------- BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent ) { // F6 cycles through everything and works always // Ctrl-TAB cycles through Menubar, Toolbars and Floatingwindows only and is // only active if one of those items has the focus BOOL bF6 = FALSE; BOOL bFocusInList = FALSE; KeyCode aKeyCode = aKeyEvent.GetKeyCode(); BOOL bForward = !aKeyCode.IsShift(); if( ( aKeyCode.IsMod1() && aKeyCode.GetCode() == KEY_TAB ) // Ctrl-TAB || ( bF6 = ( aKeyCode.GetCode()) == KEY_F6 ) // F6 ) { // is the focus in the list ? BOOL bHasFocus = FALSE; ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { Window *pWin = *p; if( (*p)->HasChildPathFocus( TRUE ) ) { bFocusInList = TRUE; // Ctrl-TAB works not in Dialogs if( !bF6 && (*p)->IsDialog() ) return FALSE; // activate next task pane Window *pNextWin = bF6 ? FindNextFloat( *p, bForward ) : FindNextPane( *p, bForward ); if( pNextWin != pWin ) { ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE; pNextWin->GrabFocus(); ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE; } else { // we did not find another taskpane, so // put focus back into document: use frame win of topmost parent while( pWin ) { if( !pWin->GetParent() ) { pWin->ImplGetFrameWindow()->GetWindow( WINDOW_CLIENT )->GrabFocus(); break; } pWin = pWin->GetParent(); } } return TRUE; } else p++; } // the focus is not in the list: activate first float if F6 was pressed if( !bFocusInList && bF6 ) { Window *pWin = FindNextFloat( NULL, bForward ); if( pWin ) { pWin->GrabFocus(); return TRUE; } } } return FALSE; } // -------------------------------------------------- // returns next valid pane Window* TaskPaneList::FindNextPane( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( ++p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->IsVisible() && !(*p)->IsDialog() ) return *p; } break; } else ++p; } return pWindow; // nothing found } // -------------------------------------------------- // returns first valid item (regardless of type) if pWindow==0, otherwise returns next valid float Window* TaskPaneList::FindNextFloat( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( !pWindow || *p == pWindow ) { while( p != mTaskPanes.end() ) { if( pWindow ) // increment before test ++p; if( p == mTaskPanes.end() ) return pWindow; // do not wrap, send focus back to document at end of list if( (*p)->IsVisible() /*&& ( (*p)->GetType() == RSC_DOCKINGWINDOW || (*p)->IsDialog() )*/ ) return *p; if( !pWindow ) // increment after test, otherwise first element is skipped ++p; } break; } else ++p; } return pWindow; // nothing found } // -------------------------------------------------- <commit_msg>#96972# set focus in child window for floating windows<commit_after>/************************************************************************* * * $RCSfile: taskpanelist.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: ssa $ $Date: 2002-04-15 12:46:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _RCID_H #include <rcid.h> #endif #ifndef _SV_DOCKWIN_HXX #include <dockwin.hxx> #endif #include <taskpanelist.hxx> #include <functional> #include <algorithm> // can't have static linkage because SUNPRO 5.2 complains Point ImplTaskPaneListGetPos( const Window *w ) { Point pos; if( w->ImplIsDockingWindow() ) { pos = ((DockingWindow*)w)->GetPosPixel(); Window *pF = ((DockingWindow*)w)->GetFloatingWindow(); if( pF ) pos = pF->OutputToAbsoluteScreenPixel( pF->ScreenToOutputPixel( pos ) ); else pos = w->OutputToAbsoluteScreenPixel( pos ); } else pos = w->OutputToAbsoluteScreenPixel( w->GetPosPixel() ); return pos; } // compares window pos left-to-right struct LTRSort : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w1, const Window* w2 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; struct LTRSortBackward : public ::std::binary_function< const Window*, const Window*, bool > { bool operator()( const Window* w2, const Window* w1 ) const { Point pos1(ImplTaskPaneListGetPos( w1 )); Point pos2(ImplTaskPaneListGetPos( w2 )); if( pos1.X() == pos2.X() ) return ( pos1.Y() < pos2.Y() ); else return ( pos1.X() < pos2.X() ); } }; // -------------------------------------------------- static void ImplTaskPaneListGrabFocus( Window *pWindow ) { // put focus in child of floating windows which is typically a toolbar // that can deal with the focus if( pWindow->ImplIsFloatingWindow() && pWindow->GetWindow( WINDOW_FIRSTCHILD ) ) pWindow = pWindow->GetWindow( WINDOW_FIRSTCHILD ); pWindow->GrabFocus(); } // -------------------------------------------------- TaskPaneList::TaskPaneList() { } TaskPaneList::~TaskPaneList() { } // -------------------------------------------------- void TaskPaneList::AddWindow( Window *pWindow ) { bool bDockingWindow=false; bool bToolbox=false; bool bDialog=false; bool bUnknown=false; if( pWindow ) { if( pWindow->GetType() == RSC_DOCKINGWINDOW ) bDockingWindow = true; else if( pWindow->GetType() == RSC_TOOLBOX ) bToolbox = true; else if( pWindow->IsDialog() ) bDialog = true; else bUnknown = true; ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); // avoid duplicates if( p == mTaskPanes.end() ) // not found mTaskPanes.push_back( pWindow ); } } // -------------------------------------------------- void TaskPaneList::RemoveWindow( Window *pWindow ) { ::std::vector< Window* >::iterator p; p = ::std::find( mTaskPanes.begin(), mTaskPanes.end(), pWindow ); if( p != mTaskPanes.end() ) mTaskPanes.erase( p ); } // -------------------------------------------------- BOOL TaskPaneList::HandleKeyEvent( KeyEvent aKeyEvent ) { // F6 cycles through everything and works always // Ctrl-TAB cycles through Menubar, Toolbars and Floatingwindows only and is // only active if one of those items has the focus BOOL bF6 = FALSE; BOOL bFocusInList = FALSE; KeyCode aKeyCode = aKeyEvent.GetKeyCode(); BOOL bForward = !aKeyCode.IsShift(); if( ( (aKeyCode.IsMod1() || aKeyCode.IsMod2()) && aKeyCode.GetCode() == KEY_TAB ) // Ctrl-TAB or Alt-TAB || ( bF6 = ( aKeyCode.GetCode()) == KEY_F6 ) // F6 ) { // is the focus in the list ? BOOL bHasFocus = FALSE; ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { Window *pWin = *p; if( (*p)->HasChildPathFocus( TRUE ) ) { bFocusInList = TRUE; // Ctrl-TAB works not in Dialogs if( !bF6 && (*p)->IsDialog() ) return FALSE; // activate next task pane Window *pNextWin = bF6 ? FindNextFloat( *p, bForward ) : FindNextPane( *p, bForward ); if( pNextWin != pWin ) { ImplGetSVData()->maWinData.mbNoSaveFocus = TRUE; ImplTaskPaneListGrabFocus( pNextWin ); ImplGetSVData()->maWinData.mbNoSaveFocus = FALSE; } else { // we did not find another taskpane, so // put focus back into document: use frame win of topmost parent while( pWin ) { if( !pWin->GetParent() ) { pWin->ImplGetFrameWindow()->GetWindow( WINDOW_CLIENT )->GrabFocus(); break; } pWin = pWin->GetParent(); } } return TRUE; } else p++; } // the focus is not in the list: activate first float if F6 was pressed if( !bFocusInList && bF6 ) { Window *pWin = FindNextFloat( NULL, bForward ); if( pWin ) { ImplTaskPaneListGrabFocus( pWin ); return TRUE; } } } return FALSE; } // -------------------------------------------------- // returns next valid pane Window* TaskPaneList::FindNextPane( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( *p == pWindow ) { unsigned n = mTaskPanes.size(); while( --n ) { if( ++p == mTaskPanes.end() ) p = mTaskPanes.begin(); if( (*p)->IsVisible() && !(*p)->IsDialog() ) { pWindow = *p; break; } } break; } else ++p; } return pWindow; } // -------------------------------------------------- // returns first valid item (regardless of type) if pWindow==0, otherwise returns next valid float Window* TaskPaneList::FindNextFloat( Window *pWindow, BOOL bForward ) { if( bForward ) ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSort() ); else ::std::stable_sort( mTaskPanes.begin(), mTaskPanes.end(), LTRSortBackward() ); ::std::vector< Window* >::iterator p = mTaskPanes.begin(); while( p != mTaskPanes.end() ) { if( !pWindow || *p == pWindow ) { while( p != mTaskPanes.end() ) { if( pWindow ) // increment before test ++p; if( p == mTaskPanes.end() ) break; // do not wrap, send focus back to document at end of list if( (*p)->IsVisible() /*&& ( (*p)->GetType() == RSC_DOCKINGWINDOW || (*p)->IsDialog() )*/ ) { pWindow = *p; break; } if( !pWindow ) // increment after test, otherwise first element is skipped ++p; } break; } else ++p; } return pWindow; } // -------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //------------------------------------------------------------------------- // Implementation of the V0 vertexer class // reads tracks writes out V0 vertices // fills the ESD with the V0s // Origin: Iouri Belikov, IPHC, Strasbourg, Jouri.Belikov@cern.ch //------------------------------------------------------------------------- #include "AliESDEvent.h" #include "AliESDv0.h" #include "AliV0vertexer.h" ClassImp(AliV0vertexer) //A set of very loose cuts Double_t AliV0vertexer::fgChi2max=33.; //max chi2 Double_t AliV0vertexer::fgDNmin=0.05; //min imp parameter for the 1st daughter Double_t AliV0vertexer::fgDPmin=0.05; //min imp parameter for the 2nd daughter Double_t AliV0vertexer::fgDCAmax=1.5; //max DCA between the daughter tracks Double_t AliV0vertexer::fgCPAmin=0.9; //min cosine of V0's pointing angle Double_t AliV0vertexer::fgRmin=0.2; //min radius of the fiducial volume Double_t AliV0vertexer::fgRmax=200.; //max radius of the fiducial volume Int_t AliV0vertexer::Tracks2V0vertices(AliESDEvent *event) { //-------------------------------------------------------------------- //This function reconstructs V0 vertices //-------------------------------------------------------------------- const AliESDVertex *vtxT3D=event->GetPrimaryVertex(); Double_t xPrimaryVertex=vtxT3D->GetXv(); Double_t yPrimaryVertex=vtxT3D->GetYv(); Double_t zPrimaryVertex=vtxT3D->GetZv(); Int_t nentr=event->GetNumberOfTracks(); Double_t b=event->GetMagneticField(); if (nentr<2) return 0; TArrayI neg(nentr); TArrayI pos(nentr); Int_t nneg=0, npos=0, nvtx=0; Int_t i; for (i=0; i<nentr; i++) { AliESDtrack *esdTrack=event->GetTrack(i); ULong_t status=esdTrack->GetStatus(); //if ((status&AliESDtrack::kITSrefit)==0)//not to accept the ITS SA tracks if ((status&AliESDtrack::kTPCrefit)==0) continue; Double_t d=esdTrack->GetD(xPrimaryVertex,yPrimaryVertex,b); if (TMath::Abs(d)<fDPmin) continue; if (TMath::Abs(d)>fRmax) continue; if (esdTrack->GetSign() < 0.) neg[nneg++]=i; else pos[npos++]=i; } for (i=0; i<nneg; i++) { Int_t nidx=neg[i]; AliESDtrack *ntrk=event->GetTrack(nidx); for (Int_t k=0; k<npos; k++) { Int_t pidx=pos[k]; AliESDtrack *ptrk=event->GetTrack(pidx); if (TMath::Abs(ntrk->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDNmin) if (TMath::Abs(ptrk->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDNmin) continue; Double_t xn, xp, dca=ntrk->GetDCA(ptrk,b,xn,xp); if (dca > fDCAmax) continue; if ((xn+xp) > 2*fRmax) continue; if ((xn+xp) < 2*fRmin) continue; AliExternalTrackParam nt(*ntrk), pt(*ptrk); Bool_t corrected=kFALSE; if ((nt.GetX() > 3.) && (xn < 3.)) { //correct for the beam pipe material corrected=kTRUE; } if ((pt.GetX() > 3.) && (xp < 3.)) { //correct for the beam pipe material corrected=kTRUE; } if (corrected) { dca=nt.GetDCA(&pt,b,xn,xp); if (dca > fDCAmax) continue; if ((xn+xp) > 2*fRmax) continue; if ((xn+xp) < 2*fRmin) continue; } nt.PropagateTo(xn,b); pt.PropagateTo(xp,b); AliESDv0 vertex(nt,nidx,pt,pidx); if (vertex.GetChi2V0() > fChi2max) continue; Double_t x=vertex.Xv(), y=vertex.Yv(); Double_t r2=x*x + y*y; if (r2 < fRmin*fRmin) continue; if (r2 > fRmax*fRmax) continue; Float_t cpa=vertex.GetV0CosineOfPointingAngle(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex); const Double_t pThr=1.5; Double_t pv0=vertex.P(); if (pv0<pThr) { //Below the threshold "pThr", try a momentum dependent cos(PA) cut const Double_t bend=0.03; // approximate Xi bending angle const Double_t qt=0.211; // max Lambda pT in Omega decay const Double_t cpaThr=TMath::Cos(TMath::ASin(qt/pThr) + bend); Double_t cpaCut=(fCPAmin/cpaThr)*TMath::Cos(TMath::ASin(qt/pv0) + bend); if (cpa < cpaCut) continue; } else if (cpa < fCPAmin) continue; vertex.SetDcaV0Daughters(dca); vertex.SetV0CosineOfPointingAngle(cpa); vertex.ChangeMassHypothesis(kK0Short); event->AddV0(&vertex); nvtx++; } } Info("Tracks2V0vertices","Number of reconstructed V0 vertices: %d",nvtx); return nvtx; } <commit_msg>Changing ASin -> ATan (Karel)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //------------------------------------------------------------------------- // Implementation of the V0 vertexer class // reads tracks writes out V0 vertices // fills the ESD with the V0s // Origin: Iouri Belikov, IPHC, Strasbourg, Jouri.Belikov@cern.ch //------------------------------------------------------------------------- #include "AliESDEvent.h" #include "AliESDv0.h" #include "AliV0vertexer.h" ClassImp(AliV0vertexer) //A set of very loose cuts Double_t AliV0vertexer::fgChi2max=33.; //max chi2 Double_t AliV0vertexer::fgDNmin=0.05; //min imp parameter for the 1st daughter Double_t AliV0vertexer::fgDPmin=0.05; //min imp parameter for the 2nd daughter Double_t AliV0vertexer::fgDCAmax=1.5; //max DCA between the daughter tracks Double_t AliV0vertexer::fgCPAmin=0.9; //min cosine of V0's pointing angle Double_t AliV0vertexer::fgRmin=0.2; //min radius of the fiducial volume Double_t AliV0vertexer::fgRmax=200.; //max radius of the fiducial volume Int_t AliV0vertexer::Tracks2V0vertices(AliESDEvent *event) { //-------------------------------------------------------------------- //This function reconstructs V0 vertices //-------------------------------------------------------------------- const AliESDVertex *vtxT3D=event->GetPrimaryVertex(); Double_t xPrimaryVertex=vtxT3D->GetXv(); Double_t yPrimaryVertex=vtxT3D->GetYv(); Double_t zPrimaryVertex=vtxT3D->GetZv(); Int_t nentr=event->GetNumberOfTracks(); Double_t b=event->GetMagneticField(); if (nentr<2) return 0; TArrayI neg(nentr); TArrayI pos(nentr); Int_t nneg=0, npos=0, nvtx=0; Int_t i; for (i=0; i<nentr; i++) { AliESDtrack *esdTrack=event->GetTrack(i); ULong_t status=esdTrack->GetStatus(); //if ((status&AliESDtrack::kITSrefit)==0)//not to accept the ITS SA tracks if ((status&AliESDtrack::kTPCrefit)==0) continue; Double_t d=esdTrack->GetD(xPrimaryVertex,yPrimaryVertex,b); if (TMath::Abs(d)<fDPmin) continue; if (TMath::Abs(d)>fRmax) continue; if (esdTrack->GetSign() < 0.) neg[nneg++]=i; else pos[npos++]=i; } for (i=0; i<nneg; i++) { Int_t nidx=neg[i]; AliESDtrack *ntrk=event->GetTrack(nidx); for (Int_t k=0; k<npos; k++) { Int_t pidx=pos[k]; AliESDtrack *ptrk=event->GetTrack(pidx); if (TMath::Abs(ntrk->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDNmin) if (TMath::Abs(ptrk->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDNmin) continue; Double_t xn, xp, dca=ntrk->GetDCA(ptrk,b,xn,xp); if (dca > fDCAmax) continue; if ((xn+xp) > 2*fRmax) continue; if ((xn+xp) < 2*fRmin) continue; AliExternalTrackParam nt(*ntrk), pt(*ptrk); Bool_t corrected=kFALSE; if ((nt.GetX() > 3.) && (xn < 3.)) { //correct for the beam pipe material corrected=kTRUE; } if ((pt.GetX() > 3.) && (xp < 3.)) { //correct for the beam pipe material corrected=kTRUE; } if (corrected) { dca=nt.GetDCA(&pt,b,xn,xp); if (dca > fDCAmax) continue; if ((xn+xp) > 2*fRmax) continue; if ((xn+xp) < 2*fRmin) continue; } nt.PropagateTo(xn,b); pt.PropagateTo(xp,b); AliESDv0 vertex(nt,nidx,pt,pidx); if (vertex.GetChi2V0() > fChi2max) continue; Double_t x=vertex.Xv(), y=vertex.Yv(); Double_t r2=x*x + y*y; if (r2 < fRmin*fRmin) continue; if (r2 > fRmax*fRmax) continue; Float_t cpa=vertex.GetV0CosineOfPointingAngle(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex); const Double_t pThr=1.5; Double_t pv0=vertex.P(); if (pv0<pThr) { //Below the threshold "pThr", try a momentum dependent cos(PA) cut const Double_t bend=0.03; // approximate Xi bending angle const Double_t qt=0.211; // max Lambda pT in Omega decay const Double_t cpaThr=TMath::Cos(TMath::ATan(qt/pThr) + bend); Double_t cpaCut=(fCPAmin/cpaThr)*TMath::Cos(TMath::ATan(qt/pv0) + bend); if (cpa < cpaCut) continue; } else if (cpa < fCPAmin) continue; vertex.SetDcaV0Daughters(dca); vertex.SetV0CosineOfPointingAngle(cpa); vertex.ChangeMassHypothesis(kK0Short); event->AddV0(&vertex); nvtx++; } } Info("Tracks2V0vertices","Number of reconstructed V0 vertices: %d",nvtx); return nvtx; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/animation/bounds_animator.h" #include "app/slide_animation.h" #include "base/scoped_ptr.h" #include "views/view.h" // Duration in milliseconds for animations. static const int kAnimationDuration = 200; namespace views { BoundsAnimator::BoundsAnimator(View* parent) : parent_(parent), observer_(NULL), container_(new AnimationContainer()) { container_->set_observer(this); } BoundsAnimator::~BoundsAnimator() { // Reset the delegate so that we don't attempt to notify our observer from // the destructor. container_->set_observer(NULL); // Delete all the animations, but don't remove any child views. We assume the // view owns us and is going to be deleted anyway. for (ViewToDataMap::iterator i = data_.begin(); i != data_.end(); ++i) delete i->second.animation; } void BoundsAnimator::AnimateViewTo(View* view, const gfx::Rect& target, bool delete_when_done) { DCHECK_EQ(view->GetParent(), parent_); scoped_ptr<Animation> current_animation; if (data_.find(view) != data_.end()) { // Currently animating this view, blow away the current animation and // we'll create another animation below. // We delay deleting the view until the end so that we don't prematurely // send out notification that we're done. current_animation.reset(ResetAnimationForView(view)); } // NOTE: we don't check if the view is already at the target location. Doing // so leads to odd cases where no animations may be present after invoking // AnimateViewTo. AnimationProgressed does nothing when the bounds of the // view don't change. Data& data = data_[view]; data.start_bounds = view->bounds(); data.target_bounds = target; data.animation = CreateAnimation(); data.delete_when_done = delete_when_done; animation_to_view_[data.animation] = view; data.animation->Show(); } void BoundsAnimator::SetAnimationForView(View* view, SlideAnimation* animation) { scoped_ptr<SlideAnimation> animation_wrapper(animation); if (data_.find(view) == data_.end()) return; // We delay deleting the animation until the end so that we don't prematurely // send out notification that we're done. scoped_ptr<Animation> old_animation(ResetAnimationForView(view)); data_[view].animation = animation_wrapper.release(); animation_to_view_[animation] = view; animation->set_delegate(this); animation->SetContainer(container_.get()); animation->Show(); } const SlideAnimation* BoundsAnimator::GetAnimationForView(View* view) { return data_.find(view) == data_.end() ? NULL : data_[view].animation; } void BoundsAnimator::SetAnimationDelegate(View* view, AnimationDelegate* delegate, bool delete_when_done) { DCHECK(IsAnimating(view)); data_[view].delegate = delegate; data_[view].delete_delegate_when_done = delete_when_done; } void BoundsAnimator::StopAnimatingView(View* view) { if (data_.find(view) == data_.end()) return; data_[view].animation->Stop(); } bool BoundsAnimator::IsAnimating(View* view) const { return data_.find(view) != data_.end(); } bool BoundsAnimator::IsAnimating() const { return !data_.empty(); } void BoundsAnimator::Cancel() { if (data_.empty()) return; while (!data_.empty()) data_.begin()->second.animation->Stop(); // Invoke AnimationContainerProgressed to force a repaint and notify delegate. AnimationContainerProgressed(container_.get()); } SlideAnimation* BoundsAnimator::CreateAnimation() { SlideAnimation* animation = new SlideAnimation(this); animation->SetContainer(container_.get()); animation->SetSlideDuration(kAnimationDuration); animation->SetTweenType(SlideAnimation::EASE_OUT); return animation; } void BoundsAnimator::RemoveFromMapsAndDelete(View* view) { DCHECK(data_.count(view) > 0); Data& data = data_[view]; animation_to_view_.erase(data.animation); if (data.delete_when_done) delete view; data_.erase(view); } void BoundsAnimator::CleanupData(Data* data) { if (data->delete_delegate_when_done) { delete static_cast<OwnedAnimationDelegate*>(data->delegate); data->delegate = NULL; } delete data->animation; data->animation = NULL; } Animation* BoundsAnimator::ResetAnimationForView(View* view) { if (data_.find(view) == data_.end()) return NULL; Animation* old_animation = data_[view].animation; animation_to_view_.erase(old_animation); data_[view].animation = NULL; // Reset the delegate so that we don't attempt any processing when the // animation calls us back. old_animation->set_delegate(NULL); return old_animation; } void BoundsAnimator::AnimationProgressed(const Animation* animation) { DCHECK(animation_to_view_.find(animation) != animation_to_view_.end()); View* view = animation_to_view_[animation]; const Data& data = data_[view]; gfx::Rect new_bounds = animation->CurrentValueBetween(data.start_bounds, data.target_bounds); if (new_bounds != view->bounds()) { gfx::Rect total_bounds = new_bounds.Union(view->bounds()); // Build up the region to repaint in repaint_bounds_. We'll do the repaint // when all animations complete (in AnimationContainerProgressed). if (repaint_bounds_.IsEmpty()) repaint_bounds_ = total_bounds; else repaint_bounds_ = repaint_bounds_.Union(total_bounds); view->SetBounds(new_bounds); } if (data_[view].delegate) data_[view].delegate->AnimationProgressed(animation); } void BoundsAnimator::AnimationEnded(const Animation* animation) { View* view = animation_to_view_[animation]; AnimationDelegate* delegate = data_[view].delegate; // Make a copy of the data as Remove empties out the maps. Data data = data_[view]; RemoveFromMapsAndDelete(view); if (delegate) delegate->AnimationEnded(animation); CleanupData(&data); } void BoundsAnimator::AnimationCanceled(const Animation* animation) { View* view = animation_to_view_[animation]; AnimationDelegate* delegate = data_[view].delegate; // Make a copy of the data as Remove empties out the maps. Data data = data_[view]; RemoveFromMapsAndDelete(view); if (delegate) delegate->AnimationCanceled(animation); CleanupData(&data); } void BoundsAnimator::AnimationContainerProgressed( AnimationContainer* container) { if (!repaint_bounds_.IsEmpty()) { parent_->SchedulePaint(repaint_bounds_, false); repaint_bounds_.SetRect(0, 0, 0, 0); } if (observer_ && !IsAnimating()) { // Notify here rather than from AnimationXXX to avoid deleting the animation // while the animaion is calling us. observer_->OnBoundsAnimatorDone(this); } } void BoundsAnimator::AnimationContainerEmpty(AnimationContainer* container) { } } // namespace views <commit_msg>Fixes leak in boundsanimator.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/animation/bounds_animator.h" #include "app/slide_animation.h" #include "base/scoped_ptr.h" #include "views/view.h" // Duration in milliseconds for animations. static const int kAnimationDuration = 200; namespace views { BoundsAnimator::BoundsAnimator(View* parent) : parent_(parent), observer_(NULL), container_(new AnimationContainer()) { container_->set_observer(this); } BoundsAnimator::~BoundsAnimator() { // Reset the delegate so that we don't attempt to notify our observer from // the destructor. container_->set_observer(NULL); // Delete all the animations, but don't remove any child views. We assume the // view owns us and is going to be deleted anyway. for (ViewToDataMap::iterator i = data_.begin(); i != data_.end(); ++i) CleanupData(&(i->second)); } void BoundsAnimator::AnimateViewTo(View* view, const gfx::Rect& target, bool delete_when_done) { DCHECK_EQ(view->GetParent(), parent_); scoped_ptr<Animation> current_animation; if (data_.find(view) != data_.end()) { // Currently animating this view, blow away the current animation and // we'll create another animation below. // We delay deleting the view until the end so that we don't prematurely // send out notification that we're done. current_animation.reset(ResetAnimationForView(view)); } // NOTE: we don't check if the view is already at the target location. Doing // so leads to odd cases where no animations may be present after invoking // AnimateViewTo. AnimationProgressed does nothing when the bounds of the // view don't change. Data& data = data_[view]; data.start_bounds = view->bounds(); data.target_bounds = target; data.animation = CreateAnimation(); data.delete_when_done = delete_when_done; animation_to_view_[data.animation] = view; data.animation->Show(); } void BoundsAnimator::SetAnimationForView(View* view, SlideAnimation* animation) { scoped_ptr<SlideAnimation> animation_wrapper(animation); if (data_.find(view) == data_.end()) return; // We delay deleting the animation until the end so that we don't prematurely // send out notification that we're done. scoped_ptr<Animation> old_animation(ResetAnimationForView(view)); data_[view].animation = animation_wrapper.release(); animation_to_view_[animation] = view; animation->set_delegate(this); animation->SetContainer(container_.get()); animation->Show(); } const SlideAnimation* BoundsAnimator::GetAnimationForView(View* view) { return data_.find(view) == data_.end() ? NULL : data_[view].animation; } void BoundsAnimator::SetAnimationDelegate(View* view, AnimationDelegate* delegate, bool delete_when_done) { DCHECK(IsAnimating(view)); data_[view].delegate = delegate; data_[view].delete_delegate_when_done = delete_when_done; } void BoundsAnimator::StopAnimatingView(View* view) { if (data_.find(view) == data_.end()) return; data_[view].animation->Stop(); } bool BoundsAnimator::IsAnimating(View* view) const { return data_.find(view) != data_.end(); } bool BoundsAnimator::IsAnimating() const { return !data_.empty(); } void BoundsAnimator::Cancel() { if (data_.empty()) return; while (!data_.empty()) data_.begin()->second.animation->Stop(); // Invoke AnimationContainerProgressed to force a repaint and notify delegate. AnimationContainerProgressed(container_.get()); } SlideAnimation* BoundsAnimator::CreateAnimation() { SlideAnimation* animation = new SlideAnimation(this); animation->SetContainer(container_.get()); animation->SetSlideDuration(kAnimationDuration); animation->SetTweenType(SlideAnimation::EASE_OUT); return animation; } void BoundsAnimator::RemoveFromMapsAndDelete(View* view) { DCHECK(data_.count(view) > 0); Data& data = data_[view]; animation_to_view_.erase(data.animation); if (data.delete_when_done) delete view; data_.erase(view); } void BoundsAnimator::CleanupData(Data* data) { if (data->delete_delegate_when_done) { delete static_cast<OwnedAnimationDelegate*>(data->delegate); data->delegate = NULL; } delete data->animation; data->animation = NULL; } Animation* BoundsAnimator::ResetAnimationForView(View* view) { if (data_.find(view) == data_.end()) return NULL; Animation* old_animation = data_[view].animation; animation_to_view_.erase(old_animation); data_[view].animation = NULL; // Reset the delegate so that we don't attempt any processing when the // animation calls us back. old_animation->set_delegate(NULL); return old_animation; } void BoundsAnimator::AnimationProgressed(const Animation* animation) { DCHECK(animation_to_view_.find(animation) != animation_to_view_.end()); View* view = animation_to_view_[animation]; const Data& data = data_[view]; gfx::Rect new_bounds = animation->CurrentValueBetween(data.start_bounds, data.target_bounds); if (new_bounds != view->bounds()) { gfx::Rect total_bounds = new_bounds.Union(view->bounds()); // Build up the region to repaint in repaint_bounds_. We'll do the repaint // when all animations complete (in AnimationContainerProgressed). if (repaint_bounds_.IsEmpty()) repaint_bounds_ = total_bounds; else repaint_bounds_ = repaint_bounds_.Union(total_bounds); view->SetBounds(new_bounds); } if (data_[view].delegate) data_[view].delegate->AnimationProgressed(animation); } void BoundsAnimator::AnimationEnded(const Animation* animation) { View* view = animation_to_view_[animation]; AnimationDelegate* delegate = data_[view].delegate; // Make a copy of the data as Remove empties out the maps. Data data = data_[view]; RemoveFromMapsAndDelete(view); if (delegate) delegate->AnimationEnded(animation); CleanupData(&data); } void BoundsAnimator::AnimationCanceled(const Animation* animation) { View* view = animation_to_view_[animation]; AnimationDelegate* delegate = data_[view].delegate; // Make a copy of the data as Remove empties out the maps. Data data = data_[view]; RemoveFromMapsAndDelete(view); if (delegate) delegate->AnimationCanceled(animation); CleanupData(&data); } void BoundsAnimator::AnimationContainerProgressed( AnimationContainer* container) { if (!repaint_bounds_.IsEmpty()) { parent_->SchedulePaint(repaint_bounds_, false); repaint_bounds_.SetRect(0, 0, 0, 0); } if (observer_ && !IsAnimating()) { // Notify here rather than from AnimationXXX to avoid deleting the animation // while the animaion is calling us. observer_->OnBoundsAnimatorDone(this); } } void BoundsAnimator::AnimationContainerEmpty(AnimationContainer* container) { } } // namespace views <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Suat Gedikli (gedikli@willowgarage.com) */ #include <pcl/visualization/image_viewer.h> #include <pcl/visualization/common/float_image_utils.h> #include <vtkImageImport.h> #include <vtkImageViewer.h> #include <vtkRenderWindowInteractor.h> #include <vtkImageReslice.h> #include <vtkTransform.h> #include <vtkImageChangeInformation.h> #include <vtkCallbackCommand.h> #include <vtkObject.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkImageCanvasSource2D.h> #include <vtkImageBlend.h> #include <pcl/visualization/keyboard_event.h> #include <pcl/visualization/mouse_event.h> #include <pcl/common/time.h> ///////////////////////////////////////////////////////////////////////////////////////////// pcl::visualization::ImageViewer::ImageViewer (const std::string& window_title) : interactor_ (vtkSmartPointer<vtkRenderWindowInteractor>::New ()), mouse_command_ (vtkCallbackCommand::New ()), keyboard_command_ (vtkCallbackCommand::New ()), image_viewer_ (vtkImageViewer::New ()), data_size_ (0) { // Set the mouse/keyboard callbacks mouse_command_->SetClientData (this); mouse_command_->SetCallback (ImageViewer::MouseCallback); keyboard_command_->SetClientData (this); keyboard_command_->SetCallback (ImageViewer::KeyboardCallback); // Create our own interactor and set the window title image_viewer_->SetupInteractor (interactor_); image_viewer_->GetRenderWindow ()->SetWindowName (window_title.c_str ()); // Initialize and create timer interactor_->Initialize (); timer_id_ = interactor_->CreateRepeatingTimer (0); // Set the exit callbacks exit_main_loop_timer_callback_ = vtkSmartPointer<ExitMainLoopTimerCallback>::New (); exit_main_loop_timer_callback_->window = this; exit_main_loop_timer_callback_->right_timer_id = -1; interactor_->AddObserver (vtkCommand::TimerEvent, exit_main_loop_timer_callback_); exit_callback_ = vtkSmartPointer<ExitCallback>::New (); exit_callback_->window = this; interactor_->AddObserver (vtkCommand::ExitEvent, exit_callback_); resetStoppedFlag (); } ///////////////////////////////////////////////////////////////////////////////////////////// pcl::visualization::ImageViewer::~ImageViewer () { interactor_->DestroyTimer (timer_id_); // interactor_->DestroyTimer (interactor_->timer_id_); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::showRGBImage (const unsigned char* rgb_data, unsigned width, unsigned height) { vtkImageImport* importer = vtkImageImport::New (); importer->SetNumberOfScalarComponents (3); importer->SetWholeExtent (0, width - 1, 0, height - 1, 0, 0); importer->SetDataScalarTypeToUnsignedChar (); importer->SetDataExtentToWholeExtent (); void* data = const_cast<void*> ((const void*)rgb_data); importer->SetImportVoidPointer (data, 1); importer->Update (); vtkSmartPointer<vtkMatrix4x4> transform = vtkSmartPointer<vtkMatrix4x4>::New (); transform->Identity (); transform->SetElement (1,1, -1.0); transform->SetElement (1,3, height); vtkSmartPointer<vtkTransform> imageTransform = vtkSmartPointer<vtkTransform>::New (); imageTransform->SetMatrix (transform); // Now create filter and set previously created transformation vtkSmartPointer<vtkImageReslice> algo = vtkSmartPointer<vtkImageReslice>::New (); algo->SetInput (importer->GetOutput ()); algo->SetInformationInput (importer->GetOutput ()); algo->SetResliceTransform (imageTransform); algo->SetInterpolationModeToCubic (); algo->Update (); image_viewer_->SetInput (algo->GetOutput ()); image_viewer_->SetColorLevel (127.5); image_viewer_->SetColorWindow (255); image_viewer_->SetSize (width, height); image_viewer_->Render (); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::showRGBImage (const pcl::PointCloud<pcl::PointXYZRGB> &cloud) { if (data_size_ < cloud.width * cloud.height) { data_size_ = cloud.width * cloud.height * 3; data_.reset (new unsigned char[data_size_]); } for (size_t i = 0; i < cloud.points.size (); ++i) memcpy (&data_[i * 3], (char*)&cloud.points[i].rgb, sizeof (char) * 3); return (showRGBImage (data_.get (), cloud.width, cloud.height)); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::showFloatImage (const float* float_image, unsigned int width, unsigned int height, float min_value, float max_value, bool grayscale) { unsigned char* rgb_image = FloatImageUtils::getVisualImage (float_image, width, height, min_value, max_value, grayscale); showRGBImage (rgb_image, width, height); delete[] rgb_image; } void pcl::visualization::ImageViewer::showAngleImage (const float* angle_image, unsigned int width, unsigned int height) { unsigned char* rgb_image = FloatImageUtils::getVisualAngleImage (angle_image, width, height); showRGBImage (rgb_image, width, height); delete[] rgb_image; } void pcl::visualization::ImageViewer::showHalfAngleImage (const float* angle_image, unsigned int width, unsigned int height) { unsigned char* rgb_image = FloatImageUtils::getVisualHalfAngleImage (angle_image, width, height); showRGBImage (rgb_image, width, height); delete[] rgb_image; } void pcl::visualization::ImageViewer::showShortImage (const unsigned short* short_image, unsigned int width, unsigned int height, unsigned short min_value, unsigned short max_value, bool grayscale) { unsigned char* rgb_image = FloatImageUtils::getVisualImage (short_image, width, height, min_value, max_value, grayscale); showRGBImage (rgb_image, width, height); delete[] rgb_image; } void pcl::visualization::ImageViewer::markPoint(size_t u, size_t v, Vector3ub fg_color, Vector3ub bg_color, float radius) { vtkSmartPointer<vtkImageCanvasSource2D> drawing = vtkSmartPointer<vtkImageCanvasSource2D>::New (); drawing->SetNumberOfScalarComponents (3); drawing->SetScalarTypeToUnsignedChar (); vtkImageData* image_data = image_viewer_->GetInput (); drawing->SetExtent (image_data->GetExtent ()); drawing->SetDrawColor (fg_color[0], fg_color[1], fg_color[2]); drawing->DrawPoint (u, v); drawing->SetDrawColor (bg_color[0], bg_color[1], bg_color[2]); drawing->DrawCircle (u, v, radius); vtkSmartPointer<vtkImageBlend> blend = vtkSmartPointer<vtkImageBlend>::New(); blend->AddInput (image_data); blend->AddInput (drawing->GetOutput ()); blend->SetOpacity (0, 0.6); blend->SetOpacity (1, 0.4); image_viewer_->SetInput (blend->GetOutput ()); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::spin () { resetStoppedFlag (); // Render the window before we start the interactor interactor_->Render (); interactor_->Start (); } /////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::spinOnce (int time, bool force_redraw) { resetStoppedFlag (); if (time <= 0) time = 1; DO_EVERY (1.0 / interactor_->GetDesiredUpdateRate (), interactor_->Render (); exit_main_loop_timer_callback_->right_timer_id = interactor_->CreateRepeatingTimer (time); interactor_->Start (); interactor_->DestroyTimer (exit_main_loop_timer_callback_->right_timer_id); ); } ///////////////////////////////////////////////////////////////////////////////////////////// boost::signals2::connection pcl::visualization::ImageViewer::registerMouseCallback ( boost::function<void (const pcl::visualization::MouseEvent&)> callback) { // just add observer at first time when a callback is registered if (mouse_signal_.empty ()) { interactor_->AddObserver (vtkCommand::MouseMoveEvent, mouse_command_); interactor_->AddObserver (vtkCommand::MiddleButtonPressEvent, mouse_command_); interactor_->AddObserver (vtkCommand::MiddleButtonReleaseEvent, mouse_command_); interactor_->AddObserver (vtkCommand::MouseWheelBackwardEvent, mouse_command_); interactor_->AddObserver (vtkCommand::MouseWheelForwardEvent, mouse_command_); interactor_->AddObserver (vtkCommand::LeftButtonPressEvent, mouse_command_); interactor_->AddObserver (vtkCommand::LeftButtonReleaseEvent, mouse_command_); interactor_->AddObserver (vtkCommand::RightButtonPressEvent, mouse_command_); interactor_->AddObserver (vtkCommand::RightButtonReleaseEvent, mouse_command_); } return (mouse_signal_.connect (callback)); } ///////////////////////////////////////////////////////////////////////////////////////////// boost::signals2::connection pcl::visualization::ImageViewer::registerKeyboardCallback ( boost::function<void (const pcl::visualization::KeyboardEvent&)> callback) { // just add observer at first time when a callback is registered if (keyboard_signal_.empty ()) { interactor_->AddObserver (vtkCommand::KeyPressEvent, keyboard_command_); interactor_->AddObserver (vtkCommand::KeyReleaseEvent, keyboard_command_); } return (keyboard_signal_.connect (callback)); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::emitMouseEvent (unsigned long event_id) { int x,y; interactor_->GetMousePosition (&x, &y); MouseEvent event (MouseEvent::MouseMove, MouseEvent::NoButton, x, y, interactor_->GetAltKey (), interactor_->GetControlKey (), interactor_->GetShiftKey ()); bool repeat = false; switch (event_id) { case vtkCommand::MouseMoveEvent : event.setType(MouseEvent::MouseMove); break; case vtkCommand::LeftButtonPressEvent : event.setButton(MouseEvent::LeftButton); if (interactor_->GetRepeatCount () == 0) event.setType(MouseEvent::MouseButtonPress); else event.setType(MouseEvent::MouseDblClick); break; case vtkCommand::LeftButtonReleaseEvent : event.setButton(MouseEvent::LeftButton); event.setType(MouseEvent::MouseButtonRelease); break; case vtkCommand::RightButtonPressEvent : event.setButton(MouseEvent::RightButton); if (interactor_->GetRepeatCount () == 0) event.setType(MouseEvent::MouseButtonPress); else event.setType(MouseEvent::MouseDblClick); break; case vtkCommand::RightButtonReleaseEvent : event.setButton(MouseEvent::RightButton); event.setType(MouseEvent::MouseButtonRelease); break; case vtkCommand::MiddleButtonPressEvent : event.setButton(MouseEvent::MiddleButton); if (interactor_->GetRepeatCount () == 0) event.setType(MouseEvent::MouseButtonPress); else event.setType(MouseEvent::MouseDblClick); break; case vtkCommand::MiddleButtonReleaseEvent : event.setButton(MouseEvent::MiddleButton); event.setType(MouseEvent::MouseButtonRelease); break; case vtkCommand::MouseWheelBackwardEvent : event.setButton(MouseEvent::VScroll); event.setType(MouseEvent::MouseScrollDown); if (interactor_->GetRepeatCount () != 0) repeat = true; break; case vtkCommand::MouseWheelForwardEvent : event.setButton(MouseEvent::VScroll); event.setType(MouseEvent::MouseScrollUp); if (interactor_->GetRepeatCount () != 0) repeat = true; break; default: return; } mouse_signal_ (event); if (repeat) mouse_signal_ (event); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::emitKeyboardEvent (unsigned long event_id) { KeyboardEvent event (bool(event_id == vtkCommand::KeyPressEvent), interactor_->GetKeySym (), interactor_->GetKeyCode (), interactor_->GetAltKey (), interactor_->GetControlKey (), interactor_->GetShiftKey ()); keyboard_signal_ (event); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::MouseCallback (vtkObject*, unsigned long eid, void* clientdata, void* calldata) { ImageViewer* window = reinterpret_cast<ImageViewer*> (clientdata); window->emitMouseEvent (eid); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::KeyboardCallback (vtkObject*, unsigned long eid, void* clientdata, void* calldata) { ImageViewer* window = reinterpret_cast<ImageViewer*> (clientdata); window->emitKeyboardEvent (eid); } <commit_msg>Fixed an BGR/RGB issue in image_viewer<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Suat Gedikli (gedikli@willowgarage.com) */ #include <pcl/visualization/image_viewer.h> #include <pcl/visualization/common/float_image_utils.h> #include <vtkImageImport.h> #include <vtkImageViewer.h> #include <vtkRenderWindowInteractor.h> #include <vtkImageReslice.h> #include <vtkTransform.h> #include <vtkImageChangeInformation.h> #include <vtkCallbackCommand.h> #include <vtkObject.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkImageCanvasSource2D.h> #include <vtkImageBlend.h> #include <pcl/visualization/keyboard_event.h> #include <pcl/visualization/mouse_event.h> #include <pcl/common/time.h> ///////////////////////////////////////////////////////////////////////////////////////////// pcl::visualization::ImageViewer::ImageViewer (const std::string& window_title) : interactor_ (vtkSmartPointer<vtkRenderWindowInteractor>::New ()), mouse_command_ (vtkCallbackCommand::New ()), keyboard_command_ (vtkCallbackCommand::New ()), image_viewer_ (vtkImageViewer::New ()), data_size_ (0) { // Set the mouse/keyboard callbacks mouse_command_->SetClientData (this); mouse_command_->SetCallback (ImageViewer::MouseCallback); keyboard_command_->SetClientData (this); keyboard_command_->SetCallback (ImageViewer::KeyboardCallback); // Create our own interactor and set the window title image_viewer_->SetupInteractor (interactor_); image_viewer_->GetRenderWindow ()->SetWindowName (window_title.c_str ()); // Initialize and create timer interactor_->Initialize (); timer_id_ = interactor_->CreateRepeatingTimer (0); // Set the exit callbacks exit_main_loop_timer_callback_ = vtkSmartPointer<ExitMainLoopTimerCallback>::New (); exit_main_loop_timer_callback_->window = this; exit_main_loop_timer_callback_->right_timer_id = -1; interactor_->AddObserver (vtkCommand::TimerEvent, exit_main_loop_timer_callback_); exit_callback_ = vtkSmartPointer<ExitCallback>::New (); exit_callback_->window = this; interactor_->AddObserver (vtkCommand::ExitEvent, exit_callback_); resetStoppedFlag (); } ///////////////////////////////////////////////////////////////////////////////////////////// pcl::visualization::ImageViewer::~ImageViewer () { interactor_->DestroyTimer (timer_id_); // interactor_->DestroyTimer (interactor_->timer_id_); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::showRGBImage (const unsigned char* rgb_data, unsigned width, unsigned height) { vtkImageImport* importer = vtkImageImport::New (); importer->SetNumberOfScalarComponents (3); importer->SetWholeExtent (0, width - 1, 0, height - 1, 0, 0); importer->SetDataScalarTypeToUnsignedChar (); importer->SetDataExtentToWholeExtent (); void* data = const_cast<void*> ((const void*)rgb_data); importer->SetImportVoidPointer (data, 1); importer->Update (); vtkSmartPointer<vtkMatrix4x4> transform = vtkSmartPointer<vtkMatrix4x4>::New (); transform->Identity (); transform->SetElement (1,1, -1.0); transform->SetElement (1,3, height); vtkSmartPointer<vtkTransform> imageTransform = vtkSmartPointer<vtkTransform>::New (); imageTransform->SetMatrix (transform); // Now create filter and set previously created transformation vtkSmartPointer<vtkImageReslice> algo = vtkSmartPointer<vtkImageReslice>::New (); algo->SetInput (importer->GetOutput ()); algo->SetInformationInput (importer->GetOutput ()); algo->SetResliceTransform (imageTransform); algo->SetInterpolationModeToCubic (); algo->Update (); image_viewer_->SetInput (algo->GetOutput ()); image_viewer_->SetColorLevel (127.5); image_viewer_->SetColorWindow (255); image_viewer_->SetSize (width, height); image_viewer_->Render (); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::showRGBImage (const pcl::PointCloud<pcl::PointXYZRGB> &cloud) { if (data_size_ < cloud.width * cloud.height) { data_size_ = cloud.width * cloud.height * 3; data_.reset (new unsigned char[data_size_]); } for (size_t i = 0; i < cloud.points.size (); ++i) { memcpy (&data_[i * 3], (unsigned char*)&cloud.points[i].rgb, sizeof (unsigned char) * 3); /// Convert from BGR to RGB unsigned char aux = data_[i*3]; data_[i*3] = data_[i*3+2]; data_[i*3+2] = aux; } return (showRGBImage (data_.get (), cloud.width, cloud.height)); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::showFloatImage (const float* float_image, unsigned int width, unsigned int height, float min_value, float max_value, bool grayscale) { unsigned char* rgb_image = FloatImageUtils::getVisualImage (float_image, width, height, min_value, max_value, grayscale); showRGBImage (rgb_image, width, height); delete[] rgb_image; } void pcl::visualization::ImageViewer::showAngleImage (const float* angle_image, unsigned int width, unsigned int height) { unsigned char* rgb_image = FloatImageUtils::getVisualAngleImage (angle_image, width, height); showRGBImage (rgb_image, width, height); delete[] rgb_image; } void pcl::visualization::ImageViewer::showHalfAngleImage (const float* angle_image, unsigned int width, unsigned int height) { unsigned char* rgb_image = FloatImageUtils::getVisualHalfAngleImage (angle_image, width, height); showRGBImage (rgb_image, width, height); delete[] rgb_image; } void pcl::visualization::ImageViewer::showShortImage (const unsigned short* short_image, unsigned int width, unsigned int height, unsigned short min_value, unsigned short max_value, bool grayscale) { unsigned char* rgb_image = FloatImageUtils::getVisualImage (short_image, width, height, min_value, max_value, grayscale); showRGBImage (rgb_image, width, height); delete[] rgb_image; } void pcl::visualization::ImageViewer::markPoint(size_t u, size_t v, Vector3ub fg_color, Vector3ub bg_color, float radius) { vtkSmartPointer<vtkImageCanvasSource2D> drawing = vtkSmartPointer<vtkImageCanvasSource2D>::New (); drawing->SetNumberOfScalarComponents (3); drawing->SetScalarTypeToUnsignedChar (); vtkImageData* image_data = image_viewer_->GetInput (); drawing->SetExtent (image_data->GetExtent ()); drawing->SetDrawColor (fg_color[0], fg_color[1], fg_color[2]); drawing->DrawPoint (u, v); drawing->SetDrawColor (bg_color[0], bg_color[1], bg_color[2]); drawing->DrawCircle (u, v, radius); vtkSmartPointer<vtkImageBlend> blend = vtkSmartPointer<vtkImageBlend>::New(); blend->AddInput (image_data); blend->AddInput (drawing->GetOutput ()); blend->SetOpacity (0, 0.6); blend->SetOpacity (1, 0.4); image_viewer_->SetInput (blend->GetOutput ()); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::spin () { resetStoppedFlag (); // Render the window before we start the interactor interactor_->Render (); interactor_->Start (); } /////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::spinOnce (int time, bool force_redraw) { resetStoppedFlag (); if (time <= 0) time = 1; DO_EVERY (1.0 / interactor_->GetDesiredUpdateRate (), interactor_->Render (); exit_main_loop_timer_callback_->right_timer_id = interactor_->CreateRepeatingTimer (time); interactor_->Start (); interactor_->DestroyTimer (exit_main_loop_timer_callback_->right_timer_id); ); } ///////////////////////////////////////////////////////////////////////////////////////////// boost::signals2::connection pcl::visualization::ImageViewer::registerMouseCallback ( boost::function<void (const pcl::visualization::MouseEvent&)> callback) { // just add observer at first time when a callback is registered if (mouse_signal_.empty ()) { interactor_->AddObserver (vtkCommand::MouseMoveEvent, mouse_command_); interactor_->AddObserver (vtkCommand::MiddleButtonPressEvent, mouse_command_); interactor_->AddObserver (vtkCommand::MiddleButtonReleaseEvent, mouse_command_); interactor_->AddObserver (vtkCommand::MouseWheelBackwardEvent, mouse_command_); interactor_->AddObserver (vtkCommand::MouseWheelForwardEvent, mouse_command_); interactor_->AddObserver (vtkCommand::LeftButtonPressEvent, mouse_command_); interactor_->AddObserver (vtkCommand::LeftButtonReleaseEvent, mouse_command_); interactor_->AddObserver (vtkCommand::RightButtonPressEvent, mouse_command_); interactor_->AddObserver (vtkCommand::RightButtonReleaseEvent, mouse_command_); } return (mouse_signal_.connect (callback)); } ///////////////////////////////////////////////////////////////////////////////////////////// boost::signals2::connection pcl::visualization::ImageViewer::registerKeyboardCallback ( boost::function<void (const pcl::visualization::KeyboardEvent&)> callback) { // just add observer at first time when a callback is registered if (keyboard_signal_.empty ()) { interactor_->AddObserver (vtkCommand::KeyPressEvent, keyboard_command_); interactor_->AddObserver (vtkCommand::KeyReleaseEvent, keyboard_command_); } return (keyboard_signal_.connect (callback)); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::emitMouseEvent (unsigned long event_id) { int x,y; interactor_->GetMousePosition (&x, &y); MouseEvent event (MouseEvent::MouseMove, MouseEvent::NoButton, x, y, interactor_->GetAltKey (), interactor_->GetControlKey (), interactor_->GetShiftKey ()); bool repeat = false; switch (event_id) { case vtkCommand::MouseMoveEvent : event.setType(MouseEvent::MouseMove); break; case vtkCommand::LeftButtonPressEvent : event.setButton(MouseEvent::LeftButton); if (interactor_->GetRepeatCount () == 0) event.setType(MouseEvent::MouseButtonPress); else event.setType(MouseEvent::MouseDblClick); break; case vtkCommand::LeftButtonReleaseEvent : event.setButton(MouseEvent::LeftButton); event.setType(MouseEvent::MouseButtonRelease); break; case vtkCommand::RightButtonPressEvent : event.setButton(MouseEvent::RightButton); if (interactor_->GetRepeatCount () == 0) event.setType(MouseEvent::MouseButtonPress); else event.setType(MouseEvent::MouseDblClick); break; case vtkCommand::RightButtonReleaseEvent : event.setButton(MouseEvent::RightButton); event.setType(MouseEvent::MouseButtonRelease); break; case vtkCommand::MiddleButtonPressEvent : event.setButton(MouseEvent::MiddleButton); if (interactor_->GetRepeatCount () == 0) event.setType(MouseEvent::MouseButtonPress); else event.setType(MouseEvent::MouseDblClick); break; case vtkCommand::MiddleButtonReleaseEvent : event.setButton(MouseEvent::MiddleButton); event.setType(MouseEvent::MouseButtonRelease); break; case vtkCommand::MouseWheelBackwardEvent : event.setButton(MouseEvent::VScroll); event.setType(MouseEvent::MouseScrollDown); if (interactor_->GetRepeatCount () != 0) repeat = true; break; case vtkCommand::MouseWheelForwardEvent : event.setButton(MouseEvent::VScroll); event.setType(MouseEvent::MouseScrollUp); if (interactor_->GetRepeatCount () != 0) repeat = true; break; default: return; } mouse_signal_ (event); if (repeat) mouse_signal_ (event); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::emitKeyboardEvent (unsigned long event_id) { KeyboardEvent event (bool(event_id == vtkCommand::KeyPressEvent), interactor_->GetKeySym (), interactor_->GetKeyCode (), interactor_->GetAltKey (), interactor_->GetControlKey (), interactor_->GetShiftKey ()); keyboard_signal_ (event); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::MouseCallback (vtkObject*, unsigned long eid, void* clientdata, void* calldata) { ImageViewer* window = reinterpret_cast<ImageViewer*> (clientdata); window->emitMouseEvent (eid); } ///////////////////////////////////////////////////////////////////////////////////////////// void pcl::visualization::ImageViewer::KeyboardCallback (vtkObject*, unsigned long eid, void* clientdata, void* calldata) { ImageViewer* window = reinterpret_cast<ImageViewer*> (clientdata); window->emitKeyboardEvent (eid); } <|endoftext|>
<commit_before>// // Name: app.cpp // Purpose: Example GLUT/vtlib application. // // Copyright (c) 2001 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "SDL.h" #ifdef __FreeBSD__ # include <ieeefp.h> #endif #include "vtlib/vtlib.h" #include "vtlib/core/Terrain.h" #include "vtlib/core/TerrainScene.h" #include "vtlib/core/NavEngines.h" class App { public: bool CreateScene(); void videosettings(bool same_video_mode, bool fullscreen); void display(); void run(); int main(); void process_mouse_button(const SDL_Event &event); void process_mouse_motion(const SDL_Event &event); void process_event(const SDL_Event &event); void process_events(); }; // // Initialize the SDL display. This code originated from another project, // so i am not sure of the details, but it should work well on each // platform. // void App::videosettings(bool same_video_mode, bool fullscreen) { int width, height; if ( ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) == -1 ) ) { std::cerr << "Could not initialize SDL: " << SDL_GetError() << std::endl; exit( -1 ); } atexit( SDL_Quit ); SDL_VideoInfo const * info = SDL_GetVideoInfo(); if( !info ) { std::cerr << "Video query failed: " << SDL_GetError( ) << std::endl; exit( -1 ); } int num_modes; SDL_Rect ** modes = SDL_ListModes(NULL, SDL_FULLSCREEN); if ( (modes != NULL) && (modes != (SDL_Rect **)-1) ) { for (num_modes = 0; modes[num_modes]; num_modes++); if ( same_video_mode ) { // EEERRR should get the surface and use its parameters width = modes[0]->w; height = modes[0]->h; } else { for ( int i=num_modes-1; i >= 0; i-- ) { width = modes[i]->w; height = modes[i]->h; if ( (modes[i]->w >= 1024) && (modes[i]->h >= 768) ) { break; } } } } else { std::cerr << "Video list modes failed: " << SDL_GetError( ) << std::endl; exit( -1 ); } std::cerr << width << " " << height << std::endl; SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); int flags = SDL_OPENGL | SDL_DOUBLEBUF; if (fullscreen) flags |= SDL_FULLSCREEN; if ( info->hw_available ) flags |= SDL_HWSURFACE; else flags |= SDL_SWSURFACE; if ( info->blit_hw ) flags |= SDL_HWACCEL; if( SDL_SetVideoMode( width, height, 16, flags ) == 0 ) { std::cerr << "Video mode set failed: " << SDL_GetError( ) << std::endl; exit( -1 ); } // Tell the SDL output size to vtlib vtGetScene()->SetWindowSize(width, height); } //-------------------------------------------------------------------------- // // Create the 3d scene: call vtlib to load the terrain and prepare for // user interaction. // bool App::CreateScene() { // Get a handle to the vtScene - one is already created for you vtScene *pScene = vtGetScene(); pScene->Init(); // Set the global data path vtTerrain::SetDataPath("Data/"); // Look up the camera vtCamera *pCamera = pScene->GetCamera(); pCamera->SetHither(20 * WORLD_SCALE); // 20 meters // Create a new terrain scene. This will contain all the terrain // that are created. vtTerrainScene *ts = new vtTerrainScene(); vtRoot *pTopGroup = ts->BeginTerrainScene(false); // Tell the scene graph to point to this terrain scene pScene->SetRoot(pTopGroup); // Create a new vtTerrain, read its paramters from a file vtTerrain *pTerr = new vtTerrain(); pTerr->SetParamFile("Data/Simple.ini"); // Add the terrain to the scene, and contruct it ts->AppendTerrain(pTerr); int iError; if (!pTerr->CreateScene(false, iError)) { printf("Terrain creation failed."); return false; } ts->Finish("Data/"); ts->SetTerrain(pTerr); // Create a navigation engine to move around on the terrain // Flight speed is 400 m/frame // Height over terrain is 100 m vtTerrainFlyer *pFlyer = new vtTerrainFlyer(400*WORLD_SCALE, 100*WORLD_SCALE, true); pFlyer->SetTarget(pCamera); pFlyer->SetHeightField(pTerr->GetHeightField()); pScene->AddEngine(pFlyer); return true; } void App::display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); vtGetScene()->DoUpdate(); glFinish(); SDL_GL_SwapBuffers(); } void App::process_mouse_button(const SDL_Event &sdle) { // turn SDL mouse button event into a VT mouse event vtMouseEvent event; event.type = (sdle.button.type == SDL_MOUSEBUTTONDOWN) ? VT_DOWN : VT_UP; if (sdle.button.button == 1) event.button = VT_LEFT; else if (sdle.button.button == 2) event.button = VT_MIDDLE; else if (sdle.button.button == 3) event.button = VT_RIGHT; event.flags = 0; event.pos.Set(sdle.button.x, sdle.button.y); vtGetScene()->OnMouse(event); } void App::process_mouse_motion(const SDL_Event &sdle) { // turn SDL mouse move event into a VT mouse event vtMouseEvent event; event.type = VT_MOVE; event.button = VT_NONE; event.flags = 0; event.pos.Set(sdle.motion.x, sdle.motion.y); vtGetScene()->OnMouse(event); } void App::process_event(const SDL_Event &event) { int key; switch( event.type ) { case SDL_QUIT: exit(0); case SDL_KEYDOWN: break; case SDL_KEYUP: // turn SDL key event into a VT mouse event key = event.key.keysym.sym; if ( key == 27 /* ESC */ || key == 'q' || key == 'Q' ) exit(0); vtGetScene()->OnKey(key, 0); break; case SDL_MOUSEMOTION: process_mouse_motion(event); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: process_mouse_button(event); break; case SDL_VIDEORESIZE: // Tell vtlib vtGetScene()->SetWindowSize(event.resize.w, event.resize.h); break; } } void App::process_events() { SDL_Event event; while ( SDL_PollEvent( &event ) ) process_event(event); } void App::run() { while ( true ) { display(); // draw scene process_events(); // handle user events } } /* The works. */ int App::main() { #ifdef __FreeBSD__ /* FreeBSD is more stringent with FP ops by default, and OSG is */ /* doing silly things sqrt(Inf) (computing lengths of MAXFLOAT */ /* and NaN Vec3's). This turns off FP bug core dumps, ignoring */ /* the error like most platforms do by default. */ fpsetmask(0); #endif printf("Initializing SDL..\n"); videosettings(true, false); printf("Creating the terrain..\n"); if (!CreateScene()) return 0; printf("Running..\n"); run(); return 0; } int main(int, char ** ) { App app; return app.main(); } <commit_msg>added support for multiple data paths<commit_after>// // Name: app.cpp // Purpose: Example GLUT/vtlib application. // // Copyright (c) 2001 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "SDL.h" #ifdef __FreeBSD__ # include <ieeefp.h> #endif #include "vtlib/vtlib.h" #include "vtlib/core/Terrain.h" #include "vtlib/core/TerrainScene.h" #include "vtlib/core/NavEngines.h" class App { public: bool CreateScene(); void videosettings(bool same_video_mode, bool fullscreen); void display(); void run(); int main(); void process_mouse_button(const SDL_Event &event); void process_mouse_motion(const SDL_Event &event); void process_event(const SDL_Event &event); void process_events(); }; // // Initialize the SDL display. This code originated from another project, // so i am not sure of the details, but it should work well on each // platform. // void App::videosettings(bool same_video_mode, bool fullscreen) { int width, height; if ( ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) == -1 ) ) { std::cerr << "Could not initialize SDL: " << SDL_GetError() << std::endl; exit( -1 ); } atexit( SDL_Quit ); SDL_VideoInfo const * info = SDL_GetVideoInfo(); if( !info ) { std::cerr << "Video query failed: " << SDL_GetError( ) << std::endl; exit( -1 ); } int num_modes; SDL_Rect ** modes = SDL_ListModes(NULL, SDL_FULLSCREEN); if ( (modes != NULL) && (modes != (SDL_Rect **)-1) ) { for (num_modes = 0; modes[num_modes]; num_modes++); if ( same_video_mode ) { // EEERRR should get the surface and use its parameters width = modes[0]->w; height = modes[0]->h; } else { for ( int i=num_modes-1; i >= 0; i-- ) { width = modes[i]->w; height = modes[i]->h; if ( (modes[i]->w >= 1024) && (modes[i]->h >= 768) ) { break; } } } } else { std::cerr << "Video list modes failed: " << SDL_GetError( ) << std::endl; exit( -1 ); } std::cerr << width << " " << height << std::endl; SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); int flags = SDL_OPENGL | SDL_DOUBLEBUF; if (fullscreen) flags |= SDL_FULLSCREEN; if ( info->hw_available ) flags |= SDL_HWSURFACE; else flags |= SDL_SWSURFACE; if ( info->blit_hw ) flags |= SDL_HWACCEL; if( SDL_SetVideoMode( width, height, 16, flags ) == 0 ) { std::cerr << "Video mode set failed: " << SDL_GetError( ) << std::endl; exit( -1 ); } // Tell the SDL output size to vtlib vtGetScene()->SetWindowSize(width, height); } //-------------------------------------------------------------------------- // // Create the 3d scene: call vtlib to load the terrain and prepare for // user interaction. // bool App::CreateScene() { // Get a handle to the vtScene - one is already created for you vtScene *pScene = vtGetScene(); pScene->Init(); // Set the global data path StringArray paths; paths.Append(new vtString("Data/")); vtTerrain::SetDataPath(paths); // Look up the camera vtCamera *pCamera = pScene->GetCamera(); pCamera->SetHither(20 * WORLD_SCALE); // 20 meters // Create a new terrain scene. This will contain all the terrain // that are created. vtTerrainScene *ts = new vtTerrainScene(); vtRoot *pTopGroup = ts->BeginTerrainScene(false); // Tell the scene graph to point to this terrain scene pScene->SetRoot(pTopGroup); // Create a new vtTerrain, read its paramters from a file vtTerrain *pTerr = new vtTerrain(); pTerr->SetParamFile("Data/Simple.ini"); // Add the terrain to the scene, and contruct it ts->AppendTerrain(pTerr); int iError; if (!pTerr->CreateScene(false, iError)) { printf("Terrain creation failed."); return false; } ts->Finish(paths); ts->SetTerrain(pTerr); // Create a navigation engine to move around on the terrain // Flight speed is 400 m/frame // Height over terrain is 100 m vtTerrainFlyer *pFlyer = new vtTerrainFlyer(400*WORLD_SCALE, 100*WORLD_SCALE, true); pFlyer->SetTarget(pCamera); pFlyer->SetHeightField(pTerr->GetHeightField()); pScene->AddEngine(pFlyer); return true; } void App::display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); vtGetScene()->DoUpdate(); glFinish(); SDL_GL_SwapBuffers(); } void App::process_mouse_button(const SDL_Event &sdle) { // turn SDL mouse button event into a VT mouse event vtMouseEvent event; event.type = (sdle.button.type == SDL_MOUSEBUTTONDOWN) ? VT_DOWN : VT_UP; if (sdle.button.button == 1) event.button = VT_LEFT; else if (sdle.button.button == 2) event.button = VT_MIDDLE; else if (sdle.button.button == 3) event.button = VT_RIGHT; event.flags = 0; event.pos.Set(sdle.button.x, sdle.button.y); vtGetScene()->OnMouse(event); } void App::process_mouse_motion(const SDL_Event &sdle) { // turn SDL mouse move event into a VT mouse event vtMouseEvent event; event.type = VT_MOVE; event.button = VT_NONE; event.flags = 0; event.pos.Set(sdle.motion.x, sdle.motion.y); vtGetScene()->OnMouse(event); } void App::process_event(const SDL_Event &event) { int key; switch( event.type ) { case SDL_QUIT: exit(0); case SDL_KEYDOWN: break; case SDL_KEYUP: // turn SDL key event into a VT mouse event key = event.key.keysym.sym; if ( key == 27 /* ESC */ || key == 'q' || key == 'Q' ) exit(0); vtGetScene()->OnKey(key, 0); break; case SDL_MOUSEMOTION: process_mouse_motion(event); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: process_mouse_button(event); break; case SDL_VIDEORESIZE: // Tell vtlib vtGetScene()->SetWindowSize(event.resize.w, event.resize.h); break; } } void App::process_events() { SDL_Event event; while ( SDL_PollEvent( &event ) ) process_event(event); } void App::run() { while ( true ) { display(); // draw scene process_events(); // handle user events } } /* The works. */ int App::main() { #ifdef __FreeBSD__ /* FreeBSD is more stringent with FP ops by default, and OSG is */ /* doing silly things sqrt(Inf) (computing lengths of MAXFLOAT */ /* and NaN Vec3's). This turns off FP bug core dumps, ignoring */ /* the error like most platforms do by default. */ fpsetmask(0); #endif printf("Initializing SDL..\n"); videosettings(true, false); printf("Creating the terrain..\n"); if (!CreateScene()) return 0; printf("Running..\n"); run(); return 0; } int main(int, char ** ) { App app; return app.main(); } <|endoftext|>
<commit_before>#include <sitkImageFileReader.h> #include <sitkImageFileWriter.h> #include <sitkHashImageFilter.h> #include <sitkCastImageFilter.h> #include <sitkSubtractImageFilter.h> #include <sitkStatisticsImageFilter.h> #include <sitkExtractImageFilter.h> #include <memory> #include "ImageCompare.h" #include "itkExceptionObject.h" ImageCompare::ImageCompare() { mTolerance = 0.0; mMessage = ""; } bool ImageCompare::compare ( itk::simple::Image* image, std::string inTestCase, std::string inTag ) { std::auto_ptr<itk::simple::Image> centerSlice; std::string testCase = inTestCase; std::string tag = inTag; std::string testName = ::testing::UnitTest::GetInstance()->current_test_info()->name(); if ( testCase == "" ) { testCase = ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name(); } std::cout << "Starting image compare on " << testCase << "_" << testName << "_" << tag << std::endl; if ( image == NULL ) { mMessage = "ImageCompare: image is null"; return false; } // Does the baseline exist? std::string extension = ".nrrd"; std::string OutputDir = dataFinder.GetOutputDirectory(); std::string name = testCase .append( "_" ) .append(testName) .append("_") .append ( tag ); // Extract the center slice of our image if ( image->GetDimension() == 3 ) { size_t centerIdx = (int)( image->GetDepth() / 2.0 ); centerSlice.reset ( itk::simple::ExtractImageFilter().Execute ( image, centerIdx, 2 ) ); } else { centerSlice.reset ( itk::simple::Cast ( image, image->GetPixelIDValue() ) ); } std::string baselineFileName = dataFinder.GetSourceDirectory() + "/Testing/Data/Baseline/" + name + extension; if ( !itksys::SystemTools::FileExists ( baselineFileName.c_str() ) ) { // Baseline does not exist, write out what we've been given std::string newBaselineDir = OutputDir + "/Newbaseline/"; itksys::SystemTools::MakeDirectory ( newBaselineDir.c_str() ); std::cout << "Making directory " << newBaselineDir << std::endl; std::string newBaseline = newBaselineDir + name + extension; itk::simple::ImageFileWriter().SetFileName ( newBaseline ).Execute ( centerSlice.get() ); mMessage = "Baseline does not exist, wrote " + newBaseline + "\ncp " + newBaseline + " " + baselineFileName; return false; } std::auto_ptr<itk::simple::Image> baseline; std::cout << "Loading baseline " << baselineFileName << std::endl; try { baseline.reset ( itk::simple::ImageFileReader().SetFileName ( baselineFileName ).Execute() ); } catch ( itk::ExceptionObject& e ) { mMessage = "ImageCompare: Failed to load image " + baselineFileName + " because: " + e.what(); return false; } // Do the diff itk::simple::HashImageFilter hasher; if ( hasher.Execute ( baseline.get() ) == hasher.Execute ( centerSlice.get() ) ) { // Nothing else to do return true; } if ( baseline->GetHeight() != centerSlice->GetHeight() || baseline->GetWidth() != centerSlice->GetWidth() || baseline->GetDepth() != centerSlice->GetDepth() ) { mMessage = "ImageCompare: Image dimensions are different"; return false; } // Get the center slices std::auto_ptr<itk::simple::Image> diff; try { diff.reset ( itk::simple::SubtractImageFilter().Execute ( centerSlice.get(), baseline.get() ) ); } catch ( itk::ExceptionObject& e ) { mMessage = "ImageCompare: Failed to subtract image " + baselineFileName + " because: " + e.what(); return false; } itk::simple::StatisticsImageFilter stats; stats.Execute ( diff.get() ); double dValue = sqrt ( stats.GetMean() ); if ( fabs ( dValue ) > fabs ( mTolerance ) ) { std::ostringstream msg; msg << "ImageCompare: image Root Mean Square (RMS) difference was " << dValue << " which exceeds the tolerance of " << mTolerance; msg << "\n"; mMessage = msg.str(); std::cout << "<DartMeasurement name=\"RMSeDifference\" type=\"numeric/float\">" << dValue << "</DartMeasurement>" << std::endl; std::cout << "<DartMeasurement name=\"Tolerance\" type=\"numeric/float\">" << mTolerance << "</DartMeasurement>" << std::endl; std::string volumeName = OutputDir + "/" + name + ".nrrd"; itk::simple::ImageFileWriter().SetFileName ( volumeName ).Execute ( centerSlice.get() ); return false; } return true; } <commit_msg>STYLE: cleaning up whitespace in ImageCompare.cxx<commit_after>#include <sitkImageFileReader.h> #include <sitkImageFileWriter.h> #include <sitkHashImageFilter.h> #include <sitkCastImageFilter.h> #include <sitkSubtractImageFilter.h> #include <sitkStatisticsImageFilter.h> #include <sitkExtractImageFilter.h> #include <memory> #include "ImageCompare.h" #include "itkExceptionObject.h" ImageCompare::ImageCompare() { mTolerance = 0.0; mMessage = ""; } bool ImageCompare::compare ( itk::simple::Image* image, std::string inTestCase, std::string inTag ) { std::auto_ptr<itk::simple::Image> centerSlice; std::string testCase = inTestCase; std::string tag = inTag; std::string testName = ::testing::UnitTest::GetInstance()->current_test_info()->name(); if ( testCase == "" ) { testCase = ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name(); } std::cout << "Starting image compare on " << testCase << "_" << testName << "_" << tag << std::endl; if ( image == NULL ) { mMessage = "ImageCompare: image is null"; return false; } // Does the baseline exist? std::string extension = ".nrrd"; std::string OutputDir = dataFinder.GetOutputDirectory(); std::string name = testCase .append( "_" ) .append(testName) .append("_") .append ( tag ); // Extract the center slice of our image if ( image->GetDimension() == 3 ) { size_t centerIdx = (int)( image->GetDepth() / 2.0 ); centerSlice.reset ( itk::simple::ExtractImageFilter().Execute ( image, centerIdx, 2 ) ); } else { centerSlice.reset ( itk::simple::Cast ( image, image->GetPixelIDValue() ) ); } std::string baselineFileName = dataFinder.GetSourceDirectory() + "/Testing/Data/Baseline/" + name + extension; if ( !itksys::SystemTools::FileExists ( baselineFileName.c_str() ) ) { // Baseline does not exist, write out what we've been given std::string newBaselineDir = OutputDir + "/Newbaseline/"; itksys::SystemTools::MakeDirectory ( newBaselineDir.c_str() ); std::cout << "Making directory " << newBaselineDir << std::endl; std::string newBaseline = newBaselineDir + name + extension; itk::simple::ImageFileWriter().SetFileName ( newBaseline ).Execute ( centerSlice.get() ); mMessage = "Baseline does not exist, wrote " + newBaseline + "\ncp " + newBaseline + " " + baselineFileName; return false; } std::auto_ptr<itk::simple::Image> baseline; std::cout << "Loading baseline " << baselineFileName << std::endl; try { baseline.reset ( itk::simple::ImageFileReader().SetFileName ( baselineFileName ).Execute() ); } catch ( itk::ExceptionObject& e ) { mMessage = "ImageCompare: Failed to load image " + baselineFileName + " because: " + e.what(); return false; } // Do the diff itk::simple::HashImageFilter hasher; if ( hasher.Execute ( baseline.get() ) == hasher.Execute ( centerSlice.get() ) ) { // Nothing else to do return true; } if ( baseline->GetHeight() != centerSlice->GetHeight() || baseline->GetWidth() != centerSlice->GetWidth() || baseline->GetDepth() != centerSlice->GetDepth() ) { mMessage = "ImageCompare: Image dimensions are different"; return false; } // Get the center slices std::auto_ptr<itk::simple::Image> diff; try { diff.reset ( itk::simple::SubtractImageFilter().Execute ( centerSlice.get(), baseline.get() ) ); } catch ( itk::ExceptionObject& e ) { mMessage = "ImageCompare: Failed to subtract image " + baselineFileName + " because: " + e.what(); return false; } itk::simple::StatisticsImageFilter stats; stats.Execute ( diff.get() ); double dValue = sqrt ( stats.GetMean() ); if ( fabs ( dValue ) > fabs ( mTolerance ) ) { std::ostringstream msg; msg << "ImageCompare: image Root Mean Square (RMS) difference was " << dValue << " which exceeds the tolerance of " << mTolerance; msg << "\n"; mMessage = msg.str(); std::cout << "<DartMeasurement name=\"RMSeDifference\" type=\"numeric/float\">" << dValue << "</DartMeasurement>" << std::endl; std::cout << "<DartMeasurement name=\"Tolerance\" type=\"numeric/float\">" << mTolerance << "</DartMeasurement>" << std::endl; std::string volumeName = OutputDir + "/" + name + ".nrrd"; itk::simple::ImageFileWriter().SetFileName ( volumeName ).Execute ( centerSlice.get() ); return false; } return true; } <|endoftext|>
<commit_before>#include "point.h" #include <assert.h> #include "coord.h" #include "isnan.h" //temporary fix for isnan() #include "matrix.h" #include <float.h> // for DBL_MAX namespace Geom { /** Scales this vector to make it a unit vector (within rounding error). * * The current version tries to handle infinite coordinates gracefully, * but it's not clear that any callers need that. * * \pre \f$this \neq (0, 0)\f$ * \pre Neither component is NaN. * \post \f$-\epsilon<\left|this\right|-1<\epsilon\f$ */ void Point::normalize() { double len = hypot(_pt[0], _pt[1]); if(len == 0) return; if(isNaN(len)) return; static double const inf = DBL_MAX; if(len != inf) { *this /= len; } else { unsigned n_inf_coords = 0; /* Delay updating pt in case neither coord is infinite. */ Point tmp; for ( unsigned i = 0 ; i < 2 ; ++i ) { if ( _pt[i] == inf ) { ++n_inf_coords; tmp[i] = 1.0; } else if ( _pt[i] == -inf ) { ++n_inf_coords; tmp[i] = -1.0; } else { tmp[i] = 0.0; } } switch (n_inf_coords) { case 0: /* Can happen if both coords are near +/-DBL_MAX. */ *this /= 4.0; len = hypot(_pt[0], _pt[1]); assert(len != inf); *this /= len; break; case 1: *this = tmp; break; case 2: *this = sqrt(0.5) * tmp; break; } } } /** Compute the L1 norm, or manhattan distance, of \a p. */ Coord L1(Point const &p) { Coord d = 0; for ( int i = 0 ; i < 2 ; i++ ) { d += fabs(p[i]); } return d; } /** Compute the L infinity, or maximum, norm of \a p. */ Coord LInfty(Point const &p) { Coord const a(fabs(p[0])); Coord const b(fabs(p[1])); return ( a < b || isNaN(b) ? b : a ); } /** Returns true iff p is a zero vector, i.e.\ Point(0, 0). * * (NaN is considered non-zero.) */ bool is_zero(Point const &p) { return ( p[0] == 0 && p[1] == 0 ); } bool is_unit_vector(Point const &p) { return fabs(1.0 - L2(p)) <= 1e-4; /* The tolerance of 1e-4 is somewhat arbitrary. Point::normalize is believed to return points well within this tolerance. I'm not aware of any callers that want a small tolerance; most callers would be ok with a tolerance of 0.25. */ } Coord atan2(Point const p) { return std::atan2(p[Y], p[X]); } /** compute the angle turning from a to b. This should give \f$\pi/2\f$ for angle_between(a, rot90(a)); * This works by projecting b onto the basis defined by a, rot90(a) */ Coord angle_between(Point const a, Point const b) { return std::atan2(cross(b,a), dot(b,a)); } /** Returns a version of \a a scaled to be a unit vector (within rounding error). * * The current version tries to handle infinite coordinates gracefully, * but it's not clear that any callers need that. * * \pre a != Point(0, 0). * \pre Neither coordinate is NaN. * \post L2(ret) very near 1.0. */ Point unit_vector(Point const &a) { Point ret(a); ret.normalize(); return ret; } Coord cross(Point const &a, Point const &b) { Coord ret = 0; ret -= a[0] * b[1]; ret += a[1] * b[0]; return ret; } Point abs(Point const &b) { Point ret; for ( int i = 0 ; i < 2 ; i++ ) { ret[i] = fabs(b[i]); } return ret; } Point operator*(Point const &v, Matrix const &m) { Point ret; for(int i = 0; i < 2; i++) { ret[i] = v[X] * m[i] + v[Y] * m[i + 2] + m[i + 4]; } return ret; } Point operator/(Point const &p, Matrix const &m) { return p * m.inverse(); } Point &Point::operator*=(Matrix const &m) { *this = *this * m; return *this; } } //Namespace Geom /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : <commit_msg>add stub documentation to quiet compile warning<commit_after>#include "point.h" #include <assert.h> #include "coord.h" #include "isnan.h" //temporary fix for isnan() #include "matrix.h" #include <float.h> // for DBL_MAX namespace Geom { /** Scales this vector to make it a unit vector (within rounding error). * * The current version tries to handle infinite coordinates gracefully, * but it's not clear that any callers need that. * * \pre zero,zero \f$this \neq (0, 0)\f$ * \pre Neither component is NaN. * \post comparison \f$-\epsilon<\left|this\right|-1<\epsilon\f$ */ void Point::normalize() { double len = hypot(_pt[0], _pt[1]); if(len == 0) return; if(isNaN(len)) return; static double const inf = DBL_MAX; if(len != inf) { *this /= len; } else { unsigned n_inf_coords = 0; /* Delay updating pt in case neither coord is infinite. */ Point tmp; for ( unsigned i = 0 ; i < 2 ; ++i ) { if ( _pt[i] == inf ) { ++n_inf_coords; tmp[i] = 1.0; } else if ( _pt[i] == -inf ) { ++n_inf_coords; tmp[i] = -1.0; } else { tmp[i] = 0.0; } } switch (n_inf_coords) { case 0: /* Can happen if both coords are near +/-DBL_MAX. */ *this /= 4.0; len = hypot(_pt[0], _pt[1]); assert(len != inf); *this /= len; break; case 1: *this = tmp; break; case 2: *this = sqrt(0.5) * tmp; break; } } } /** Compute the L1 norm, or manhattan distance, of \a p. */ Coord L1(Point const &p) { Coord d = 0; for ( int i = 0 ; i < 2 ; i++ ) { d += fabs(p[i]); } return d; } /** Compute the L infinity, or maximum, norm of \a p. */ Coord LInfty(Point const &p) { Coord const a(fabs(p[0])); Coord const b(fabs(p[1])); return ( a < b || isNaN(b) ? b : a ); } /** Returns true iff p is a zero vector, i.e.\ Point(0, 0). * * (NaN is considered non-zero.) */ bool is_zero(Point const &p) { return ( p[0] == 0 && p[1] == 0 ); } bool is_unit_vector(Point const &p) { return fabs(1.0 - L2(p)) <= 1e-4; /* The tolerance of 1e-4 is somewhat arbitrary. Point::normalize is believed to return points well within this tolerance. I'm not aware of any callers that want a small tolerance; most callers would be ok with a tolerance of 0.25. */ } Coord atan2(Point const p) { return std::atan2(p[Y], p[X]); } /** compute the angle turning from a to b. This should give \f$\pi/2\f$ for angle_between(a, rot90(a)); * This works by projecting b onto the basis defined by a, rot90(a) */ Coord angle_between(Point const a, Point const b) { return std::atan2(cross(b,a), dot(b,a)); } /** Returns a version of \a a scaled to be a unit vector (within rounding error). * * The current version tries to handle infinite coordinates gracefully, * but it's not clear that any callers need that. * * \pre a != Point(0, 0). * \pre Neither coordinate is NaN. * \post L2(ret) very near 1.0. */ Point unit_vector(Point const &a) { Point ret(a); ret.normalize(); return ret; } Coord cross(Point const &a, Point const &b) { Coord ret = 0; ret -= a[0] * b[1]; ret += a[1] * b[0]; return ret; } Point abs(Point const &b) { Point ret; for ( int i = 0 ; i < 2 ; i++ ) { ret[i] = fabs(b[i]); } return ret; } Point operator*(Point const &v, Matrix const &m) { Point ret; for(int i = 0; i < 2; i++) { ret[i] = v[X] * m[i] + v[Y] * m[i + 2] + m[i + 4]; } return ret; } Point operator/(Point const &p, Matrix const &m) { return p * m.inverse(); } Point &Point::operator*=(Matrix const &m) { *this = *this * m; return *this; } } //Namespace Geom /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : <|endoftext|>
<commit_before> // MCADefrag.cpp // Implements the main app entrypoint and the cMCADefrag class representing the entire app #include "Globals.h" #include "MCADefrag.h" #include "Logger.h" #include "LoggerListeners.h" #include "zlib/zlib.h" // An array of 4096 zero bytes, used for writing the padding static const Byte g_Zeroes[4096] = {0}; int main(int argc, char ** argv) { cLogger::cListener * consoleLogListener = MakeConsoleListener(); cLogger::cListener * fileLogListener = new cFileListener(); cLogger::GetInstance().AttachListener(consoleLogListener); cLogger::GetInstance().AttachListener(fileLogListener); cLogger::InitiateMultithreading(); cMCADefrag Defrag; if (!Defrag.Init(argc, argv)) { return 1; } Defrag.Run(); cLogger::GetInstance().DetachListener(consoleLogListener); delete consoleLogListener; cLogger::GetInstance().DetachListener(fileLogListener); delete fileLogListener; return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cMCADefrag: cMCADefrag::cMCADefrag(void) : m_NumThreads(4), m_ShouldRecompress(true) { } bool cMCADefrag::Init(int argc, char ** argv) { // Nothing needed yet return true; } void cMCADefrag::Run(void) { // Fill the queue with MCA files m_Queue = cFile::GetFolderContents("."); // Start the processing threads: for (int i = 0; i < m_NumThreads; i++) { StartThread(); } // Wait for all the threads to finish: while (!m_Threads.empty()) { m_Threads.front()->Wait(); delete m_Threads.front(); m_Threads.pop_front(); } } void cMCADefrag::StartThread(void) { cThread * Thread = new cThread(*this); m_Threads.push_back(Thread); Thread->Start(); } AString cMCADefrag::GetNextFileName(void) { cCSLock Lock(m_CS); if (m_Queue.empty()) { return AString(); } AString res = m_Queue.back(); m_Queue.pop_back(); return res; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cMCADefrag::cThread: cMCADefrag::cThread::cThread(cMCADefrag & a_Parent) : super("MCADefrag thread"), m_Parent(a_Parent), m_IsChunkUncompressed(false) { } void cMCADefrag::cThread::Execute(void) { for (;;) { AString FileName = m_Parent.GetNextFileName(); if (FileName.empty()) { return; } ProcessFile(FileName); } } void cMCADefrag::cThread::ProcessFile(const AString & a_FileName) { // Filter out non-MCA files: if ((a_FileName.length() < 4) || (a_FileName.substr(a_FileName.length() - 4, 4) != ".mca")) { return; } LOGINFO("%s", a_FileName.c_str()); // Open input and output files: AString OutFileName = a_FileName + ".new"; cFile In, Out; if (!In.Open(a_FileName, cFile::fmRead)) { LOGWARNING("Cannot open file %s for reading, skipping file.", a_FileName.c_str()); return; } if (!Out.Open(OutFileName.c_str(), cFile::fmWrite)) { LOGWARNING("Cannot open file %s for writing, skipping file.", OutFileName.c_str()); return; } // Read the Locations and Timestamps from the input file: Byte Locations[4096]; UInt32 Timestamps[1024]; if (In.Read(Locations, sizeof(Locations)) != sizeof(Locations)) { LOGWARNING("Cannot read Locations in file %s, skipping file.", a_FileName.c_str()); return; } if (In.Read(Timestamps, sizeof(Timestamps)) != sizeof(Timestamps)) { LOGWARNING("Cannot read Timestamps in file %s, skipping file.", a_FileName.c_str()); return; } // Write dummy Locations to the Out file (will be overwritten once the correct ones are known) if (Out.Write(Locations, sizeof(Locations)) != sizeof(Locations)) { LOGWARNING("Cannot write Locations to file %s, skipping file.", OutFileName.c_str()); return; } m_CurrentSectorOut = 2; // Write a copy of the Timestamps into the Out file: if (Out.Write(Timestamps, sizeof(Timestamps)) != sizeof(Timestamps)) { LOGWARNING("Cannot write Timestamps to file %s, skipping file.", OutFileName.c_str()); return; } // Process each chunk: for (size_t i = 0; i < 1024; i++) { size_t idx = i * 4; if ( (Locations[idx] == 0) && (Locations[idx + 1] == 0) && (Locations[idx + 2] == 0) && (Locations[idx + 3] == 0) ) { // Chunk not present continue; } m_IsChunkUncompressed = false; if (!ReadChunk(In, Locations + idx)) { LOGWARNING("Cannot read chunk #%d from file %s. Skipping file.", i, a_FileName.c_str()); return; } if (!WriteChunk(Out, Locations + idx)) { LOGWARNING("Cannot write chunk #%d to file %s. Skipping file.", i, OutFileName.c_str()); return; } } // Write the new Locations into the MCA header: Out.Seek(0); if (Out.Write(Locations, sizeof(Locations)) != sizeof(Locations)) { LOGWARNING("Cannot write updated Locations to file %s, skipping file.", OutFileName.c_str()); return; } // Close the files, delete orig, rename new: In.Close(); Out.Close(); cFile::Delete(a_FileName); cFile::Rename(OutFileName, a_FileName); } bool cMCADefrag::cThread::ReadChunk(cFile & a_File, const Byte * a_LocationRaw) { int SectorNum = (a_LocationRaw[0] << 16) | (a_LocationRaw[1] << 8) | a_LocationRaw[2]; int SizeInSectors = a_LocationRaw[3] * (4 KiB); if (a_File.Seek(SectorNum * (4 KiB)) < 0) { LOGWARNING("Failed to seek to chunk data - file pos %llu (%d KiB, %.02f MiB)!", (Int64)SectorNum * (4 KiB), SectorNum * 4, ((double)SectorNum) / 256); return false; } // Read the exact size: Byte Buf[4]; if (a_File.Read(Buf, 4) != 4) { LOGWARNING("Failed to read chunk data length"); return false; } m_CompressedChunkDataSize = (Buf[0] << 24) | (Buf[1] << 16) | (Buf[2] << 8) | Buf[3]; if (m_CompressedChunkDataSize > SizeInSectors) { LOGWARNING("Invalid chunk data - SizeInSectors (%d) smaller that RealSize (%d)", SizeInSectors, m_CompressedChunkDataSize); return false; } // Read the data: if (a_File.Read(m_CompressedChunkData, m_CompressedChunkDataSize) != m_CompressedChunkDataSize) { LOGWARNING("Failed to read chunk data!"); return false; } // Uncompress the data if recompression is active if (m_Parent.m_ShouldRecompress) { m_IsChunkUncompressed = UncompressChunk(); if (!m_IsChunkUncompressed) { LOGINFO("Chunk failed to uncompress, will be copied verbatim instead."); } } return true; } bool cMCADefrag::cThread::WriteChunk(cFile & a_File, Byte * a_LocationRaw) { // Recompress the data if recompression is active: if (m_Parent.m_ShouldRecompress) { if (!CompressChunk()) { LOGINFO("Chunk failed to recompress, will be coped verbatim instead."); } } // Update the Location: a_LocationRaw[0] = m_CurrentSectorOut >> 16; a_LocationRaw[1] = (m_CurrentSectorOut >> 8) & 0xff; a_LocationRaw[2] = m_CurrentSectorOut & 0xff; a_LocationRaw[3] = (m_CompressedChunkDataSize + (4 KiB) + 3) / (4 KiB); // +3 because the m_CompressedChunkDataSize doesn't include the exact-length m_CurrentSectorOut += a_LocationRaw[3]; // Write the data length: Byte Buf[4]; Buf[0] = m_CompressedChunkDataSize >> 24; Buf[1] = (m_CompressedChunkDataSize >> 16) & 0xff; Buf[2] = (m_CompressedChunkDataSize >> 8) & 0xff; Buf[3] = m_CompressedChunkDataSize & 0xff; if (a_File.Write(Buf, 4) != 4) { LOGWARNING("Failed to write chunk length!"); return false; } // Write the data: if (a_File.Write(m_CompressedChunkData, m_CompressedChunkDataSize) != m_CompressedChunkDataSize) { LOGWARNING("Failed to write chunk data!"); return false; } // Pad onto the next sector: int NumPadding = a_LocationRaw[3] * 4096 - (m_CompressedChunkDataSize + 4); ASSERT(NumPadding >= 0); if ((NumPadding > 0) && (a_File.Write(g_Zeroes, NumPadding) != NumPadding)) { LOGWARNING("Failed to write padding"); return false; } return true; } bool cMCADefrag::cThread::UncompressChunk(void) { switch (m_CompressedChunkData[0]) { case COMPRESSION_GZIP: return UncompressChunkGzip(); case COMPRESSION_ZLIB: return UncompressChunkZlib(); } LOGINFO("Chunk is compressed with in an unknown algorithm"); return false; } bool cMCADefrag::cThread::UncompressChunkGzip(void) { // TODO // This format is not used in practice return false; } bool cMCADefrag::cThread::UncompressChunkZlib(void) { // Uncompress the data: z_stream strm; strm.zalloc = (alloc_func)NULL; strm.zfree = (free_func)NULL; strm.opaque = NULL; inflateInit(&strm); strm.next_out = m_RawChunkData; strm.avail_out = sizeof(m_RawChunkData); strm.next_in = m_CompressedChunkData + 1; // The first byte is the compression method, skip it strm.avail_in = m_CompressedChunkDataSize; int res = inflate(&strm, Z_FINISH); inflateEnd(&strm); if (res != Z_STREAM_END) { LOGWARNING("Failed to uncompress chunk data: %s", strm.msg); return false; } m_RawChunkDataSize = strm.total_out; return true; } bool cMCADefrag::cThread::CompressChunk(void) { // Check that the compressed data can fit: uLongf CompressedSize = compressBound(m_RawChunkDataSize); if (CompressedSize > sizeof(m_CompressedChunkData)) { LOGINFO("Too much data for the internal compression buffer!"); return false; } // Compress the data using the highest compression factor: int errorcode = compress2(m_CompressedChunkData + 1, &CompressedSize, m_RawChunkData, m_RawChunkDataSize, Z_BEST_COMPRESSION); if (errorcode != Z_OK) { LOGINFO("Recompression failed: %d", errorcode); return false; } m_CompressedChunkData[0] = COMPRESSION_ZLIB; m_CompressedChunkDataSize = CompressedSize + 1; return true; } <commit_msg>MCADefrag: Added a sanity check for chunk size.<commit_after> // MCADefrag.cpp // Implements the main app entrypoint and the cMCADefrag class representing the entire app #include "Globals.h" #include "MCADefrag.h" #include "Logger.h" #include "LoggerListeners.h" #include "zlib/zlib.h" // An array of 4096 zero bytes, used for writing the padding static const Byte g_Zeroes[4096] = {0}; int main(int argc, char ** argv) { cLogger::cListener * consoleLogListener = MakeConsoleListener(); cLogger::cListener * fileLogListener = new cFileListener(); cLogger::GetInstance().AttachListener(consoleLogListener); cLogger::GetInstance().AttachListener(fileLogListener); cLogger::InitiateMultithreading(); cMCADefrag Defrag; if (!Defrag.Init(argc, argv)) { return 1; } Defrag.Run(); cLogger::GetInstance().DetachListener(consoleLogListener); delete consoleLogListener; cLogger::GetInstance().DetachListener(fileLogListener); delete fileLogListener; return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cMCADefrag: cMCADefrag::cMCADefrag(void) : m_NumThreads(4), m_ShouldRecompress(true) { } bool cMCADefrag::Init(int argc, char ** argv) { // Nothing needed yet return true; } void cMCADefrag::Run(void) { // Fill the queue with MCA files m_Queue = cFile::GetFolderContents("."); // Start the processing threads: for (int i = 0; i < m_NumThreads; i++) { StartThread(); } // Wait for all the threads to finish: while (!m_Threads.empty()) { m_Threads.front()->Wait(); delete m_Threads.front(); m_Threads.pop_front(); } } void cMCADefrag::StartThread(void) { cThread * Thread = new cThread(*this); m_Threads.push_back(Thread); Thread->Start(); } AString cMCADefrag::GetNextFileName(void) { cCSLock Lock(m_CS); if (m_Queue.empty()) { return AString(); } AString res = m_Queue.back(); m_Queue.pop_back(); return res; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cMCADefrag::cThread: cMCADefrag::cThread::cThread(cMCADefrag & a_Parent) : super("MCADefrag thread"), m_Parent(a_Parent), m_IsChunkUncompressed(false) { } void cMCADefrag::cThread::Execute(void) { for (;;) { AString FileName = m_Parent.GetNextFileName(); if (FileName.empty()) { return; } ProcessFile(FileName); } } void cMCADefrag::cThread::ProcessFile(const AString & a_FileName) { // Filter out non-MCA files: if ((a_FileName.length() < 4) || (a_FileName.substr(a_FileName.length() - 4, 4) != ".mca")) { return; } LOGINFO("%s", a_FileName.c_str()); // Open input and output files: AString OutFileName = a_FileName + ".new"; cFile In, Out; if (!In.Open(a_FileName, cFile::fmRead)) { LOGWARNING("Cannot open file %s for reading, skipping file.", a_FileName.c_str()); return; } if (!Out.Open(OutFileName.c_str(), cFile::fmWrite)) { LOGWARNING("Cannot open file %s for writing, skipping file.", OutFileName.c_str()); return; } // Read the Locations and Timestamps from the input file: Byte Locations[4096]; UInt32 Timestamps[1024]; if (In.Read(Locations, sizeof(Locations)) != sizeof(Locations)) { LOGWARNING("Cannot read Locations in file %s, skipping file.", a_FileName.c_str()); return; } if (In.Read(Timestamps, sizeof(Timestamps)) != sizeof(Timestamps)) { LOGWARNING("Cannot read Timestamps in file %s, skipping file.", a_FileName.c_str()); return; } // Write dummy Locations to the Out file (will be overwritten once the correct ones are known) if (Out.Write(Locations, sizeof(Locations)) != sizeof(Locations)) { LOGWARNING("Cannot write Locations to file %s, skipping file.", OutFileName.c_str()); return; } m_CurrentSectorOut = 2; // Write a copy of the Timestamps into the Out file: if (Out.Write(Timestamps, sizeof(Timestamps)) != sizeof(Timestamps)) { LOGWARNING("Cannot write Timestamps to file %s, skipping file.", OutFileName.c_str()); return; } // Process each chunk: for (size_t i = 0; i < 1024; i++) { size_t idx = i * 4; if ( (Locations[idx] == 0) && (Locations[idx + 1] == 0) && (Locations[idx + 2] == 0) && (Locations[idx + 3] == 0) ) { // Chunk not present continue; } m_IsChunkUncompressed = false; if (!ReadChunk(In, Locations + idx)) { LOGWARNING("Cannot read chunk #%d from file %s. Skipping file.", i, a_FileName.c_str()); return; } if (!WriteChunk(Out, Locations + idx)) { LOGWARNING("Cannot write chunk #%d to file %s. Skipping file.", i, OutFileName.c_str()); return; } } // Write the new Locations into the MCA header: Out.Seek(0); if (Out.Write(Locations, sizeof(Locations)) != sizeof(Locations)) { LOGWARNING("Cannot write updated Locations to file %s, skipping file.", OutFileName.c_str()); return; } // Close the files, delete orig, rename new: In.Close(); Out.Close(); cFile::Delete(a_FileName); cFile::Rename(OutFileName, a_FileName); } bool cMCADefrag::cThread::ReadChunk(cFile & a_File, const Byte * a_LocationRaw) { int SectorNum = (a_LocationRaw[0] << 16) | (a_LocationRaw[1] << 8) | a_LocationRaw[2]; int SizeInSectors = a_LocationRaw[3] * (4 KiB); if (a_File.Seek(SectorNum * (4 KiB)) < 0) { LOGWARNING("Failed to seek to chunk data - file pos %llu (%d KiB, %.02f MiB)!", (Int64)SectorNum * (4 KiB), SectorNum * 4, ((double)SectorNum) / 256); return false; } // Read the exact size: Byte Buf[4]; if (a_File.Read(Buf, 4) != 4) { LOGWARNING("Failed to read chunk data length"); return false; } m_CompressedChunkDataSize = (Buf[0] << 24) | (Buf[1] << 16) | (Buf[2] << 8) | Buf[3]; if ((m_CompressedChunkDataSize > SizeInSectors) || (m_CompressedChunkDataSize < 0)) { LOGWARNING("Invalid chunk data - SizeInSectors (%d) smaller that RealSize (%d)", SizeInSectors, m_CompressedChunkDataSize); return false; } // Read the data: if (a_File.Read(m_CompressedChunkData, m_CompressedChunkDataSize) != m_CompressedChunkDataSize) { LOGWARNING("Failed to read chunk data!"); return false; } // Uncompress the data if recompression is active if (m_Parent.m_ShouldRecompress) { m_IsChunkUncompressed = UncompressChunk(); if (!m_IsChunkUncompressed) { LOGINFO("Chunk failed to uncompress, will be copied verbatim instead."); } } return true; } bool cMCADefrag::cThread::WriteChunk(cFile & a_File, Byte * a_LocationRaw) { // Recompress the data if recompression is active: if (m_Parent.m_ShouldRecompress) { if (!CompressChunk()) { LOGINFO("Chunk failed to recompress, will be coped verbatim instead."); } } // Update the Location: a_LocationRaw[0] = m_CurrentSectorOut >> 16; a_LocationRaw[1] = (m_CurrentSectorOut >> 8) & 0xff; a_LocationRaw[2] = m_CurrentSectorOut & 0xff; a_LocationRaw[3] = (m_CompressedChunkDataSize + (4 KiB) + 3) / (4 KiB); // +3 because the m_CompressedChunkDataSize doesn't include the exact-length m_CurrentSectorOut += a_LocationRaw[3]; // Write the data length: Byte Buf[4]; Buf[0] = m_CompressedChunkDataSize >> 24; Buf[1] = (m_CompressedChunkDataSize >> 16) & 0xff; Buf[2] = (m_CompressedChunkDataSize >> 8) & 0xff; Buf[3] = m_CompressedChunkDataSize & 0xff; if (a_File.Write(Buf, 4) != 4) { LOGWARNING("Failed to write chunk length!"); return false; } // Write the data: if (a_File.Write(m_CompressedChunkData, m_CompressedChunkDataSize) != m_CompressedChunkDataSize) { LOGWARNING("Failed to write chunk data!"); return false; } // Pad onto the next sector: int NumPadding = a_LocationRaw[3] * 4096 - (m_CompressedChunkDataSize + 4); ASSERT(NumPadding >= 0); if ((NumPadding > 0) && (a_File.Write(g_Zeroes, NumPadding) != NumPadding)) { LOGWARNING("Failed to write padding"); return false; } return true; } bool cMCADefrag::cThread::UncompressChunk(void) { switch (m_CompressedChunkData[0]) { case COMPRESSION_GZIP: return UncompressChunkGzip(); case COMPRESSION_ZLIB: return UncompressChunkZlib(); } LOGINFO("Chunk is compressed with in an unknown algorithm"); return false; } bool cMCADefrag::cThread::UncompressChunkGzip(void) { // TODO // This format is not used in practice return false; } bool cMCADefrag::cThread::UncompressChunkZlib(void) { // Uncompress the data: z_stream strm; strm.zalloc = (alloc_func)NULL; strm.zfree = (free_func)NULL; strm.opaque = NULL; inflateInit(&strm); strm.next_out = m_RawChunkData; strm.avail_out = sizeof(m_RawChunkData); strm.next_in = m_CompressedChunkData + 1; // The first byte is the compression method, skip it strm.avail_in = m_CompressedChunkDataSize; int res = inflate(&strm, Z_FINISH); inflateEnd(&strm); if (res != Z_STREAM_END) { LOGWARNING("Failed to uncompress chunk data: %s", strm.msg); return false; } m_RawChunkDataSize = strm.total_out; return true; } bool cMCADefrag::cThread::CompressChunk(void) { // Check that the compressed data can fit: uLongf CompressedSize = compressBound(m_RawChunkDataSize); if (CompressedSize > sizeof(m_CompressedChunkData)) { LOGINFO("Too much data for the internal compression buffer!"); return false; } // Compress the data using the highest compression factor: int errorcode = compress2(m_CompressedChunkData + 1, &CompressedSize, m_RawChunkData, m_RawChunkDataSize, Z_BEST_COMPRESSION); if (errorcode != Z_OK) { LOGINFO("Recompression failed: %d", errorcode); return false; } m_CompressedChunkData[0] = COMPRESSION_ZLIB; m_CompressedChunkDataSize = CompressedSize + 1; return true; } <|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <string.h> #include "HBridgeCtrlRequest.h" #include "HBridgeCtrlIndication.h" #include "GeneratedTypes.h" class HBridgeCtrlIndication : public HBridgeCtrlIndicationWrapper { public: HBridgeCtrlIndication(int id) : HBridgeCtrlIndicationWrapper(id) {} virtual void hbc_event( uint32_t e){ fprintf(stderr, "hbc_event: {"); if (e & (1 << HBridgeCtrlEvent_Started)) fprintf(stderr, "Started"); if (e & (1 << HBridgeCtrlEvent_Stopped)) fprintf(stderr, "Stopped"); fprintf(stderr, "}\n"); } }; #define RIGHT 1 #define LEFT 0 #define CW 0 #define CCW 1 #define POWER_0 0x0000 #define POWER_1 0x0200 #define POWER_2 0x0400 #define POWER_3 0x0500 #define POWER_4 0x0600 #define POWER_5 0x0680 #define POWER_6 0x0700 #define POWER_7 0x0780 #define POWER_8 0x07FF #define STOP {power[RIGHT] = POWER_0; power[LEFT] = POWER_0; device->ctrl(power,direction);} #define MOVE_FOREWARD(p) { direction[RIGHT] = CW; direction[LEFT] = CCW; power[RIGHT] = (p); power[LEFT] = (p); device->ctrl(power,direction);} #define MOVE_BACKWARD(p) { direction[RIGHT] = CCW; direction[LEFT] = CW; power[RIGHT] = (p); power[LEFT] = (p); device->ctrl(power,direction);} #define TURN_RIGHT(p) { direction[RIGHT] = CCW; direction[LEFT] = CCW; power[RIGHT] = (p); power[LEFT] = (p); device->ctrl(power,direction);} #define TURN_LEFT(p) { direction[RIGHT] = CW; direction[LEFT] = CW; power[RIGHT] = (p); power[LEFT] = (p); device->ctrl(power,direction);} int main(int argc, const char **argv) { HBridgeCtrlIndication *ind = new HBridgeCtrlIndication(IfcNames_ControllerIndication); HBridgeCtrlRequestProxy *device = new HBridgeCtrlRequestProxy(IfcNames_ControllerRequest); portalExec_start(); uint32_t direction[2]; uint32_t power[2]; sleep(1); MOVE_FOREWARD(POWER_5); usleep(1000000); STOP; MOVE_BACKWARD(POWER_5); usleep(1000000); STOP; TURN_RIGHT(POWER_5); usleep(1000000); STOP; TURN_LEFT(POWER_5); usleep(1000000); STOP; sleep(2); } <commit_msg>add a indication->request path to SW controller<commit_after> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <string.h> #include "HBridgeCtrlRequest.h" #include "HBridgeCtrlIndication.h" #include "GeneratedTypes.h" bool finished = false; class HBridgeCtrlIndication : public HBridgeCtrlIndicationWrapper { private: int hbc_event_cnt; public: HBridgeCtrlIndication(int id) : HBridgeCtrlIndicationWrapper(id), hbc_event_cnt(0){} virtual void hbc_event( uint32_t e){ hbc_event_cnt++; fprintf(stderr, "(%d) hbc_event: {", hbc_event_cnt); if (e & (1 << HBridgeCtrlEvent_Started)) fprintf(stderr, "Started"); if (e & (1 << HBridgeCtrlEvent_Stopped)) fprintf(stderr, "Stopped"); fprintf(stderr, "}\n"); finished = (hbc_event_cnt >= 8); } }; #define RIGHT 1 #define LEFT 0 #define CW 0 #define CCW 1 #define POWER_0 0x0000 #define POWER_1 0x0200 #define POWER_2 0x0400 #define POWER_3 0x0500 #define POWER_4 0x0600 #define POWER_5 0x0680 #define POWER_6 0x0700 #define POWER_7 0x0780 #define POWER_8 0x07FF #define STOP {power[RIGHT] = POWER_0; power[LEFT] = POWER_0; device->ctrl(power,direction);} #define MOVE_FOREWARD(p) { direction[RIGHT] = CW; direction[LEFT] = CCW; power[RIGHT] = (p); power[LEFT] = (p); device->ctrl(power,direction);} #define MOVE_BACKWARD(p) { direction[RIGHT] = CCW; direction[LEFT] = CW; power[RIGHT] = (p); power[LEFT] = (p); device->ctrl(power,direction);} #define TURN_RIGHT(p) { direction[RIGHT] = CCW; direction[LEFT] = CCW; power[RIGHT] = (p); power[LEFT] = (p); device->ctrl(power,direction);} #define TURN_LEFT(p) { direction[RIGHT] = CW; direction[LEFT] = CW; power[RIGHT] = (p); power[LEFT] = (p); device->ctrl(power,direction);} int main(int argc, const char **argv) { HBridgeCtrlIndication *ind = new HBridgeCtrlIndication(IfcNames_ControllerIndication); HBridgeCtrlRequestProxy *device = new HBridgeCtrlRequestProxy(IfcNames_ControllerRequest); portalExec_start(); uint32_t direction[2]; uint32_t power[2]; sleep(2); while(!finished){ MOVE_FOREWARD(POWER_5); usleep(1000000); STOP; MOVE_BACKWARD(POWER_5); usleep(1000000); STOP; TURN_RIGHT(POWER_5); usleep(1000000); STOP; TURN_LEFT(POWER_5); usleep(1000000); STOP; sleep(1); } } <|endoftext|>
<commit_before>/* -*- Mode:C++; c-file-style:"gnu" -*- */ /* * Copyright 2014 Waseda University, Sato Laboratory * Author: Takahiro Miyamoto <mt3.mos@gmail.com> * Jairo Eduardo Lopez <jairo@ruri.waseda.jp> * * nnn-nnpt.cc is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nnn-nnpt.cc is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with nnn-nnpt.cc. If not, see <http://www.gnu.org/licenses/>. */ #include "nnn-nnpt.h" namespace ns3 { namespace nnn { TypeId NNPT::GetTypeId (void) { static TypeId tid = TypeId ("ns3::nnn::NNPT") // cheating ns3 object system .SetParent<Object> () .SetGroupName ("nnn") ; return tid; } NNPT::NNPT() { } NNPT::~NNPT() { } void NNPT::addEntry (NNNAddress oldName, NNNAddress newName, Time lease_expire) { container.insert(NNPTEntry(oldName, newName, lease_expire)); Simulator::Schedule(lease_expire, &NNPT::cleanExpired, this); } void NNPT::addEntry (NNNAddress oldName, NNNAddress newName, Time lease_expire, Time renew) { container.insert(NNPTEntry(oldName, newName, lease_expire, renew)); Simulator::Schedule(lease_expire, &NNPT::cleanExpired, this); } void NNPT::addEntry (NNPTEntry nnptEntry) { container.insert(nnptEntry); Simulator::Schedule(nnptEntry.m_lease_expire, &NNPT::cleanExpired, this); } void NNPT::deleteEntry (NNNAddress oldName) { NNPTEntry tmp = findEntry (oldName); container.erase(tmp); } void NNPT::deleteEntry (NNPTEntry nnptEntry) { container.erase(nnptEntry); } bool NNPT::foundName (NNNAddress name) { pair_set_by_name& names_index = container.get<pair> (); pair_set_by_name::iterator it = names_index.find(name); if (it == names_index.end()) return false; else return true; } NNNAddress NNPT::findPairedName (NNNAddress oldName) { pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.find(oldName); if (it != pair_index.end()) { NNPTEntry tmp = *it; NNNAddress newName = tmp.m_newName; return newName; } else { return oldName; } } NNPTEntry NNPT::findEntry (NNNAddress name) { pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.find(name); if (it != pair_index.end()) { return *it; } else { return NNPTEntry (); } } NNNAddress NNPT::findNewestName () { pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.end(); it--; return it->m_oldName; } void NNPT::updateLeaseTime (NNNAddress oldName, Time lease_expire) { pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.find(oldName); if (it != pair_index.end()) { NNPTEntry tmp = *it; tmp.m_lease_expire = lease_expire; tmp.m_renew = lease_expire - Seconds (1); if (pair_index.replace(it, tmp)) { Simulator::Schedule(lease_expire, &NNPT::cleanExpired, this); } } } void NNPT::updateLeaseTime (NNNAddress oldName, Time lease_expire, Time renew) { pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.find(oldName); if (it != pair_index.end()) { NNPTEntry tmp = *it; tmp.m_lease_expire = lease_expire; tmp.m_renew = renew; if (pair_index.replace(it, tmp)) { Simulator::Schedule(lease_expire, &NNPT::cleanExpired, this); } } } uint32_t NNPT::size () { return container.size(); } bool NNPT::isEmpty () { return (container.size() == 0); } Time NNPT::findNameExpireTime (NNNAddress name) { NNPTEntry tmp = findEntry(name); return tmp.m_lease_expire; } Time NNPT::findNameExpireTime (NNPTEntry nnptEntry) { return nnptEntry.m_lease_expire; } void NNPT::cleanExpired () { pair_set_by_lease& lease_index = container.get<lease> (); Time now = Simulator::Now(); //std::cout << "Deleting expired entries at " << now << std::endl; pair_set_by_lease::iterator it = lease_index.begin(); while (! isEmpty()) { if (it->m_lease_expire <= now) { deleteEntry(*it); break; } ++it; } } void NNPT::printByAddress () { pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.begin(); std::cout << "Old Address\t| New Address\t| Lease Expire\t| Renew" << std::endl; std::cout << "--------------------------------------------------------" << std::endl; while (it != pair_index.end()) { std::cout << *it; ++it; } } void NNPT::printByLease () { pair_set_by_lease& lease_index = container.get<lease> (); pair_set_by_lease::iterator it = lease_index.begin(); std::cout << "NNN Address\t| New Address\t| Lease Expire\t| Renew" << std::endl; std::cout << "--------------------------------------------------------" << std::endl; while (it != lease_index.end ()) { std::cout << *it; ++it; } } std::ostream& operator<< (std::ostream& os, const NNPT &nnpt) { return os; } } /* namespace nnn */ } /* namespace ns3 */ <commit_msg>NS_LOG Functions for NNPT<commit_after>/* -*- Mode:C++; c-file-style:"gnu" -*- */ /* * Copyright 2014 Waseda University, Sato Laboratory * Author: Takahiro Miyamoto <mt3.mos@gmail.com> * Jairo Eduardo Lopez <jairo@ruri.waseda.jp> * * nnn-nnpt.cc is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nnn-nnpt.cc is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with nnn-nnpt.cc. If not, see <http://www.gnu.org/licenses/>. */ #include <ns3-dev/ns3/log.h> #include "nnn-nnpt.h" NS_LOG_COMPONENT_DEFINE ("nnn.nnpt"); namespace ns3 { namespace nnn { TypeId NNPT::GetTypeId (void) { static TypeId tid = TypeId ("ns3::nnn::NNPT") // cheating ns3 object system .SetParent<Object> () .SetGroupName ("nnn") ; return tid; } NNPT::NNPT() { } NNPT::~NNPT() { } void NNPT::addEntry (NNNAddress oldName, NNNAddress newName, Time lease_expire) { NS_LOG_FUNCTION (this << oldName << newName << lease_expire); container.insert(NNPTEntry(oldName, newName, lease_expire)); Simulator::Schedule(lease_expire, &NNPT::cleanExpired, this); } void NNPT::addEntry (NNNAddress oldName, NNNAddress newName, Time lease_expire, Time renew) { NS_LOG_FUNCTION (this << oldName << newName << lease_expire << renew); container.insert(NNPTEntry(oldName, newName, lease_expire, renew)); Simulator::Schedule(lease_expire, &NNPT::cleanExpired, this); } void NNPT::addEntry (NNPTEntry nnptEntry) { NS_LOG_FUNCTION (this); container.insert(nnptEntry); Simulator::Schedule(nnptEntry.m_lease_expire, &NNPT::cleanExpired, this); } void NNPT::deleteEntry (NNNAddress oldName) { NS_LOG_FUNCTION (this << oldName); NNPTEntry tmp = findEntry (oldName); container.erase(tmp); } void NNPT::deleteEntry (NNPTEntry nnptEntry) { NS_LOG_FUNCTION (this); container.erase(nnptEntry); } bool NNPT::foundName (NNNAddress name) { NS_LOG_FUNCTION (this << name); pair_set_by_name& names_index = container.get<pair> (); pair_set_by_name::iterator it = names_index.find(name); if (it == names_index.end()) return false; else return true; } NNNAddress NNPT::findPairedName (NNNAddress oldName) { NS_LOG_FUNCTION (this << oldName); pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.find(oldName); if (it != pair_index.end()) { NNPTEntry tmp = *it; NNNAddress newName = tmp.m_newName; return newName; } else { return oldName; } } NNPTEntry NNPT::findEntry (NNNAddress name) { NS_LOG_FUNCTION (this << name); pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.find(name); if (it != pair_index.end()) { return *it; } else { return NNPTEntry (); } } NNNAddress NNPT::findNewestName () { NS_LOG_FUNCTION (this); pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.end(); it--; return it->m_oldName; } void NNPT::updateLeaseTime (NNNAddress oldName, Time lease_expire) { NS_LOG_FUNCTION (this << oldName << lease_expire); pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.find(oldName); if (it != pair_index.end()) { NNPTEntry tmp = *it; tmp.m_lease_expire = lease_expire; tmp.m_renew = lease_expire - Seconds (1); if (pair_index.replace(it, tmp)) { Simulator::Schedule(lease_expire, &NNPT::cleanExpired, this); } } } void NNPT::updateLeaseTime (NNNAddress oldName, Time lease_expire, Time renew) { NS_LOG_FUNCTION (this << oldName << lease_expire << renew); pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.find(oldName); if (it != pair_index.end()) { NNPTEntry tmp = *it; tmp.m_lease_expire = lease_expire; tmp.m_renew = renew; if (pair_index.replace(it, tmp)) { Simulator::Schedule(lease_expire, &NNPT::cleanExpired, this); } } } uint32_t NNPT::size () { return container.size(); } bool NNPT::isEmpty () { return (container.size() == 0); } Time NNPT::findNameExpireTime (NNNAddress name) { NS_LOG_FUNCTION (this << name); NNPTEntry tmp = findEntry(name); return tmp.m_lease_expire; } Time NNPT::findNameExpireTime (NNPTEntry nnptEntry) { NS_LOG_FUNCTION (this); return nnptEntry.m_lease_expire; } void NNPT::cleanExpired () { NS_LOG_FUNCTION (this); pair_set_by_lease& lease_index = container.get<lease> (); Time now = Simulator::Now(); //std::cout << "Deleting expired entries at " << now << std::endl; pair_set_by_lease::iterator it = lease_index.begin(); while (! isEmpty()) { if (it->m_lease_expire <= now) { deleteEntry(*it); break; } ++it; } } void NNPT::printByAddress () { pair_set_by_name& pair_index = container.get<pair> (); pair_set_by_name::iterator it = pair_index.begin(); std::cout << "Old Address\t| New Address\t| Lease Expire\t| Renew" << std::endl; std::cout << "--------------------------------------------------------" << std::endl; while (it != pair_index.end()) { std::cout << *it; ++it; } } void NNPT::printByLease () { pair_set_by_lease& lease_index = container.get<lease> (); pair_set_by_lease::iterator it = lease_index.begin(); std::cout << "NNN Address\t| New Address\t| Lease Expire\t| Renew" << std::endl; std::cout << "--------------------------------------------------------" << std::endl; while (it != lease_index.end ()) { std::cout << *it; ++it; } } std::ostream& operator<< (std::ostream& os, const NNPT &nnpt) { return os; } } /* namespace nnn */ } /* namespace ns3 */ <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "QtUiAsset.h" #include "AssetAPI.h" #include <QByteArrayMatcher> #include <QUrl> #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("QtUiAsset") QtUiAsset::QtUiAsset(AssetAPI *owner, const QString &type_, const QString &name_) : IAsset(owner, type_, name_) { patterns_ << "http://" << "https://" << "local://" << "file://"; invalid_ref_chars_ << " " << "\n" << "\r" << "\t" << "\v" << "\f" << "\a"; } QtUiAsset::~QtUiAsset() { } bool QtUiAsset::DeserializeFromData(const u8 *data, size_t numBytes) { refs_.clear(); data_.clear(); data_.insert(data_.begin(), data, data + numBytes); // Find references QByteArray dataQt((const char*)&data_[0], data_.size()); if (!dataQt.isNull() && !dataQt.isEmpty()) { QByteArrayMatcher matcher; foreach(QByteArray pattern, patterns_) { int from = 0; int indexStart = 0; matcher.setPattern(pattern); while (indexStart != -1) { indexStart = matcher.indexIn(dataQt, from); if (indexStart == -1) break; // ")" due to Qt style sheets have this syntax most commonly: "some-image-property: url(pattern);" int indexStop = dataQt.indexOf(")", indexStart); if (indexStop == -1) { from = indexStart + 1; continue; } from = indexStop; // Asset reference validation QString stringRef = dataQt.mid(indexStart, indexStop - indexStart).trimmed(); if (stringRef.isEmpty() || stringRef.isNull()) continue; // Check for not wanted characters foreach(QString invalid, invalid_ref_chars_) if (stringRef.contains(invalid)) continue; // QUrl validation, in tolerant mode QUrl ref(stringRef, QUrl::TolerantMode); if (!ref.isValid()) continue; // Seems legit, add it refs_.push_back(AssetReference(ref.toString())); } } } else LogError("FindReferences: Could not process .ui file content, error: data was null."); return true; } bool QtUiAsset::SerializeTo(std::vector<u8> &data, const QString &serializationParameters ) { if (data_.empty()) return false; data.clear(); data = data_; return true; } void QtUiAsset::DoUnload() { } std::vector<AssetReference> QtUiAsset::FindReferences() const { return refs_; } int QtUiAsset::ReplaceAssetReferences(QByteArray &uiData) { int replacedRefs = 0; for(uint i=0; i<refs_.size(); ++i) { QString assetRef = refs_[i].ref; AssetPtr asset = assetAPI->GetAsset(assetRef); if (!asset.get()) { LogError("ReplaceAssetReferences: Asset not found from asset system even when it was marked as a dependency earlier, skipping: " + assetRef.toStdString()); continue; } QString refDiskSource = asset->DiskSource(); if (refDiskSource.isEmpty()) { LogWarning("ReplaceAssetReferences: Asset disk source empty, skipping: " + assetRef.toStdString()); continue; } if (!QFile::exists(refDiskSource)) { LogWarning("ReplaceAssetReferences: Asset disk source does not exist, skipping: " + assetRef.toStdString()); continue; } uiData.replace(assetRef, refDiskSource.toStdString().c_str()); replacedRefs++; } return replacedRefs; } bool QtUiAsset::IsDataValid() const { return !data_.empty(); } QByteArray QtUiAsset::GetRawData() const { QByteArray returnData; if (!IsDataValid()) return returnData; returnData = QByteArray((const char*)&data_[0], data_.size()); return returnData; } <commit_msg>QtUiAsset: Alot more checking for different kind of scenarios where we would falsely find a pattern but it really was not intended to be a sset reference. Now also works in the generic ui xml, not only with stylesheets.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "QtUiAsset.h" #include "AssetAPI.h" #include <QByteArrayMatcher> #include <QUrl> #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("QtUiAsset") QtUiAsset::QtUiAsset(AssetAPI *owner, const QString &type_, const QString &name_) : IAsset(owner, type_, name_) { patterns_ << "http://" << "https://" << "local://" << "file://"; invalid_ref_chars_ << " " << "\n" << "\r" << "\t" << "\v" << "\f" << "\a"; } QtUiAsset::~QtUiAsset() { } bool QtUiAsset::DeserializeFromData(const u8 *data, size_t numBytes) { refs_.clear(); data_.clear(); data_.insert(data_.begin(), data, data + numBytes); // If we are in headless mode, do not mark refs as dependency as it will // just spawn unneeded resources to the asset api without the actual need for them. // Note that this means we assume you will not show any ui on a headless run, while you // still could without the main window. if (assetAPI->IsHeadless()) return true; // Find references QByteArray dataQt((const char*)&data_[0], data_.size()); if (!dataQt.isNull() && !dataQt.isEmpty()) { QByteArrayMatcher matcher; foreach(QByteArray pattern, patterns_) { int from = 0; int indexStart = 0; matcher.setPattern(pattern); while (indexStart != -1) { indexStart = matcher.indexIn(dataQt, from); if (indexStart == -1) break; // ")" due to Qt style sheets have this syntax for example: // some-image-property: url({"|'}pattern{"|'}); int indexStop1 = dataQt.indexOf(")", indexStart); // "<" due to normal qt xml defining images, for example: // <iconset><normaloff>pattern</normaloff>pattern</iconset> int indexStop2 = dataQt.indexOf("<", indexStart); if (indexStop1 == -1 && indexStop2 == -1) { from = indexStart + 1; continue; } int indexStop = indexStop1; if (indexStop2 < indexStop || indexStop == -1) indexStop = indexStop2; from = indexStop; if (indexStop < indexStart) continue; // Asset reference validation QString stringRef = dataQt.mid(indexStart, indexStop - indexStart).trimmed(); // Ignore ui elements that have patterns as text, for example: // <widget><property name="text"><string>pattern</string></property></widget> if (indexStop == indexStop2) { int indexStop3 = dataQt.indexOf(">", indexStart); QString xmlEndTag = dataQt.mid(indexStop2, (indexStop3 - indexStop2) + 1); if (xmlEndTag.toLower() == "</string>") continue; } // Remove the last ' or " from url({"|'}pattern{"|'}) before the found ) QChar lastChar = stringRef.at(stringRef.length()-1); if (lastChar == '\'' || lastChar == '\"') stringRef.chop(1); if (stringRef.isEmpty() || stringRef.isNull()) continue; // Check for not wanted characters foreach(QString invalid, invalid_ref_chars_) if (stringRef.contains(invalid)) continue; // QUrl validation, in tolerant mode QUrl ref(stringRef, QUrl::TolerantMode); if (!ref.isValid()) continue; // Seems legit, add it refs_.push_back(AssetReference(ref.toString())); } } } else LogError("FindReferences: Could not process .ui file content, error: data was null."); return true; } bool QtUiAsset::SerializeTo(std::vector<u8> &data, const QString &serializationParameters ) { if (data_.empty()) return false; data.clear(); data = data_; return true; } void QtUiAsset::DoUnload() { } std::vector<AssetReference> QtUiAsset::FindReferences() const { return refs_; } int QtUiAsset::ReplaceAssetReferences(QByteArray &uiData) { int replacedRefs = 0; for(uint i=0; i<refs_.size(); ++i) { QString assetRef = refs_[i].ref; AssetPtr asset = assetAPI->GetAsset(assetRef); if (!asset.get()) { LogError("ReplaceAssetReferences: Asset not found from asset system even when it was marked as a dependency earlier, skipping: " + assetRef.toStdString()); continue; } QString refDiskSource = asset->DiskSource(); if (refDiskSource.isEmpty()) { LogWarning("ReplaceAssetReferences: Asset disk source empty, skipping: " + assetRef.toStdString()); continue; } if (!QFile::exists(refDiskSource)) { LogWarning("ReplaceAssetReferences: Asset disk source does not exist, skipping: " + assetRef.toStdString()); continue; } uiData.replace(assetRef, refDiskSource.toStdString().c_str()); replacedRefs++; } return replacedRefs; } bool QtUiAsset::IsDataValid() const { return !data_.empty(); } QByteArray QtUiAsset::GetRawData() const { QByteArray returnData; if (!IsDataValid()) return returnData; returnData = QByteArray((const char*)&data_[0], data_.size()); return returnData; } <|endoftext|>
<commit_before>#ifndef OM_GCSAFE_HPP_ #define OM_GCSAFE_HPP_ namespace Om { /// GC Safety indicator. /// `yes` as a parameter indicates that an operation may GC. /// `no` indicates that it is not safe to GC, operations can not GC. /// GC unsafe allocations are more likely to fail due to OOM. enum class GcSafe { yes = 1, no = 0 }; } // namespace Om #endif // OM_GCSAFE_HPP_ <commit_msg>Use uppercase for constants<commit_after>#ifndef OM_GCSAFE_HPP_ #define OM_GCSAFE_HPP_ namespace Om { /// GC Safety indicator. /// `yes` as a parameter indicates that an operation may GC. /// `no` indicates that it is not safe to GC, operations can not GC. /// GC unsafe allocations are more likely to fail due to OOM. enum class GcSafe { YES = 1, NO = 0 }; } // namespace Om #endif // OM_GCSAFE_HPP_ <|endoftext|>
<commit_before>#ifndef __HOST_IPMI_DCMI_HANDLER_H__ #define __HOST_IPMI_DCMI_HANDLER_H__ #include <map> #include <string> #include <vector> #include <sdbusplus/bus.hpp> #include "nlohmann/json.hpp" namespace dcmi { enum Commands { // Get capability bits GET_CAPABILITIES = 0x01, GET_POWER_LIMIT = 0x03, SET_POWER_LIMIT = 0x04, APPLY_POWER_LIMIT = 0x05, GET_ASSET_TAG = 0x06, SET_ASSET_TAG = 0x08, GET_MGMNT_CTRL_ID_STR = 0x09, SET_MGMNT_CTRL_ID_STR = 0x0A, GET_TEMP_READINGS = 0x10, }; static constexpr auto propIntf = "org.freedesktop.DBus.Properties"; static constexpr auto assetTagIntf = "xyz.openbmc_project.Inventory.Decorator.AssetTag"; static constexpr auto assetTagProp = "AssetTag"; static constexpr auto networkServiceName = "xyz.openbmc_project.Network"; static constexpr auto networkConfigObj = "/xyz/openbmc_project/network/config"; static constexpr auto networkConfigIntf = "xyz.openbmc_project.Network.SystemConfiguration"; static constexpr auto hostNameProp = "HostName"; static constexpr auto temperatureSensorType = 0x01; namespace assettag { using ObjectPath = std::string; using Service = std::string; using Interfaces = std::vector<std::string>; using ObjectTree = std::map<ObjectPath, std::map<Service, Interfaces>>; } //namespace assettag namespace temp_readings { static constexpr auto maxDataSets = 8; static constexpr auto maxInstances = 255; static constexpr auto maxTemp = 128; // degrees C static constexpr auto configFile = "/usr/share/ipmi-providers/dcmi_temp_readings.json"; /** @struct Response * * DCMI payload for Get Temperature Readings response */ struct Response { #if BYTE_ORDER == LITTLE_ENDIAN uint8_t temperature: 7; //!< Temperature reading in Celsius uint8_t sign: 1; //!< Sign bit #endif #if BYTE_ORDER == BIG_ENDIAN uint8_t sign: 1; //!< Sign bit uint8_t temperature: 7; //!< Temperature reading in Celsius #endif uint8_t instance; //!< Entity instance number } __attribute__((packed)); using ResponseList = std::vector<Response>; using NumInstances = size_t; using Value = uint8_t; using Sign = bool; using Temperature = std::tuple<Value, Sign>; using Json = nlohmann::json; } static constexpr auto groupExtId = 0xDC; static constexpr auto assetTagMaxOffset = 62; static constexpr auto assetTagMaxSize = 63; static constexpr auto maxBytes = 16; static constexpr size_t maxCtrlIdStrLen = 63; /** @struct GetAssetTagRequest * * DCMI payload for Get Asset Tag command request. */ struct GetAssetTagRequest { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Offset to read. uint8_t bytes; //!< Number of bytes to read. } __attribute__((packed)); /** @struct GetAssetTagResponse * * DCMI payload for Get Asset Tag command response. */ struct GetAssetTagResponse { uint8_t groupID; //!< Group extension identification. uint8_t tagLength; //!< Total asset tag length. } __attribute__((packed)); /** @struct SetAssetTagRequest * * DCMI payload for Set Asset Tag command request. */ struct SetAssetTagRequest { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Offset to write. uint8_t bytes; //!< Number of bytes to write. } __attribute__((packed)); /** @struct SetAssetTagResponse * * DCMI payload for Set Asset Tag command response. */ struct SetAssetTagResponse { uint8_t groupID; //!< Group extension identification. uint8_t tagLength; //!< Total asset tag length. } __attribute__((packed)); /** @brief Read the object tree to fetch the object path that implemented the * Asset tag interface. * * @param[in,out] objectTree - object tree * * @return On success return the object tree with the object path that * implemented the AssetTag interface. */ void readAssetTagObjectTree(dcmi::assettag::ObjectTree& objectTree); /** @brief Read the asset tag of the server * * @return On success return the asset tag. */ std::string readAssetTag(); /** @brief Write the asset tag to the asset tag DBUS property * * @param[in] assetTag - Asset Tag to be written to the property. */ void writeAssetTag(const std::string& assetTag); /** @brief Read the current power cap value * * @param[in] bus - dbus connection * * @return On success return the power cap value. */ uint32_t getPcap(sdbusplus::bus::bus& bus); /** @brief Check if the power capping is enabled * * @param[in] bus - dbus connection * * @return true if the powerCap is enabled and false if the powercap * is disabled. */ bool getPcapEnabled(sdbusplus::bus::bus& bus); /** @struct GetPowerLimitRequest * * DCMI payload for Get Power Limit command request. */ struct GetPowerLimitRequest { uint8_t groupID; //!< Group extension identification. uint16_t reserved; //!< Reserved } __attribute__((packed)); /** @struct GetPowerLimitResponse * * DCMI payload for Get Power Limit command response. */ struct GetPowerLimitResponse { uint8_t groupID; //!< Group extension identification. uint16_t reserved; //!< Reserved. uint8_t exceptionAction; //!< Exception action. uint16_t powerLimit; //!< Power limit requested in watts. uint32_t correctionTime; //!< Correction time limit in milliseconds. uint16_t reserved1; //!< Reserved. uint16_t samplingPeriod; //!< Statistics sampling period in seconds. } __attribute__((packed)); /** @brief Set the power cap value * * @param[in] bus - dbus connection * @param[in] powerCap - power cap value */ void setPcap(sdbusplus::bus::bus& bus, const uint32_t powerCap); /** @struct SetPowerLimitRequest * * DCMI payload for Set Power Limit command request. */ struct SetPowerLimitRequest { uint8_t groupID; //!< Group extension identification. uint16_t reserved; //!< Reserved uint8_t reserved1; //!< Reserved uint8_t exceptionAction; //!< Exception action. uint16_t powerLimit; //!< Power limit requested in watts. uint32_t correctionTime; //!< Correction time limit in milliseconds. uint16_t reserved2; //!< Reserved. uint16_t samplingPeriod; //!< Statistics sampling period in seconds. } __attribute__((packed)); /** @struct SetPowerLimitResponse * * DCMI payload for Set Power Limit command response. */ struct SetPowerLimitResponse { uint8_t groupID; //!< Group extension identification. } __attribute__((packed)); /** @brief Enable or disable the power capping * * @param[in] bus - dbus connection * @param[in] enabled - enable/disable */ void setPcapEnable(sdbusplus::bus::bus& bus, bool enabled); /** @struct ApplyPowerLimitRequest * * DCMI payload for Activate/Deactivate Power Limit command request. */ struct ApplyPowerLimitRequest { uint8_t groupID; //!< Group extension identification. uint8_t powerLimitAction; //!< Power limit activation uint16_t reserved; //!< Reserved } __attribute__((packed)); /** @struct ApplyPowerLimitResponse * * DCMI payload for Acticate/Deactivate Power Limit command response. */ struct ApplyPowerLimitResponse { uint8_t groupID; //!< Group extension identification. } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrRequest * * DCMI payload for Get Management Controller Identifier String cmd request. */ struct GetMgmntCtrlIdStrRequest { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Offset to read. uint8_t bytes; //!< Number of bytes to read. } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrResponse * * DCMI payload for Get Management Controller Identifier String cmd response. */ struct GetMgmntCtrlIdStrResponse { uint8_t groupID; //!< Group extension identification. uint8_t strLen; //!< ID string length. char data[]; //!< ID string } __attribute__((packed)); /** @struct SetMgmntCtrlIdStrRequest * * DCMI payload for Set Management Controller Identifier String cmd request. */ struct SetMgmntCtrlIdStrRequest { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Offset to write. uint8_t bytes; //!< Number of bytes to read. char data[]; //!< ID string } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrResponse * * DCMI payload for Get Management Controller Identifier String cmd response. */ struct SetMgmntCtrlIdStrResponse { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Last Offset Written. } __attribute__((packed)); /** @enum DCMICapParameters * * DCMI Capability parameters */ enum class DCMICapParameters { SUPPORTED_DCMI_CAPS = 0x01, //!< Supported DCMI Capabilities MANDATORY_PLAT_ATTRIBUTES = 0x02, //!< Mandatory Platform Attributes OPTIONAL_PLAT_ATTRIBUTES = 0x03, //!< Optional Platform Attributes MANAGEABILITY_ACCESS_ATTRIBUTES = 0x04, //!< Manageability Access Attributes }; /** @struct GetDCMICapRequest * * DCMI payload for Get capabilities cmd request. */ struct GetDCMICapRequest { uint8_t groupID; //!< Group extension identification. uint8_t param; //!< Capability parameter selector. } __attribute__((packed)); /** @struct GetDCMICapRequest * * DCMI payload for Get capabilities cmd response. */ struct GetDCMICapResponse { uint8_t groupID; //!< Group extension identification. uint8_t major; //!< DCMI Specification Conformance - major ver uint8_t minor; //!< DCMI Specification Conformance - minor ver uint8_t paramRevision; //!< Parameter Revision = 02h uint8_t data[]; //!< Capability array } __attribute__((packed)); /** @struct DCMICap * * DCMI capabilities protocol info. */ struct DCMICap { std::string name; //!< Name of DCMI capability. uint8_t bytePosition; //!< Starting byte number from DCMI spec. uint8_t position; //!< bit position from the DCMI spec. uint8_t length; //!< Length of the value from DCMI spec. }; using DCMICapList = std::vector<DCMICap>; /** @struct DCMICapEntry * * DCMI capabilities list and size for each parameter. */ struct DCMICapEntry { uint8_t size; //!< Size of capability array in bytes. DCMICapList capList; //!< List of capabilities for a parameter. }; using DCMICaps = std::map<DCMICapParameters, DCMICapEntry>; /** @struct GetTempReadingsRequest * * DCMI payload for Get Temperature Readings request */ struct GetTempReadingsRequest { uint8_t groupID; //!< Group extension identification. uint8_t sensorType; //!< Type of the sensor uint8_t entityId; //!< Entity ID uint8_t entityInstance; //!< Entity Instance (0 means all instances) uint8_t instanceStart; //!< Instance start (used if instance is 0) } __attribute__((packed)); /** @struct GetTempReadingsResponse * * DCMI header for Get Temperature Readings response */ struct GetTempReadingsResponseHdr { uint8_t groupID; //!< Group extension identification. uint8_t numInstances; //!< No. of instances for requested id uint8_t numDataSets; //!< No. of sets of temperature data } __attribute__((packed)); namespace temp_readings { /** @brief Read temperature from a d-bus object, scale it as per dcmi * get temperature reading requirements. * * @param[in] dbusService - the D-Bus service * @param[in] dbusPath - the D-Bus path * * @return A temperature reading */ Temperature readTemp(const std::string& dbusService, const std::string& dbusPath); /** @brief Parse out JSON config file containing information * related to temperature readings. * * @return A json object */ Json parseConfig(); /** @brief Read temperatures and fill up DCMI response for the Get * Temperature Readings command. This looks at a specific * instance. * * @param[in] type - one of "inlet", "cpu", "baseboard" * @param[in] instance - A non-zero Entity instance number * * @return A tuple, containing a temperature reading and the * number of instances. */ std::tuple<Response, NumInstances> read (const std::string& type, uint8_t instance); /** @brief Read temperatures and fill up DCMI response for the Get * Temperature Readings command. This looks at a range of * instances. * * @param[in] type - one of "inlet", "cpu", "baseboard" * @param[in] instanceStart - Entity instance start index * * @return A tuple, containing a list of temperature readings and the * number of instances. */ std::tuple<ResponseList, NumInstances> readAll(const std::string& type, uint8_t instanceStart); } } // namespace dcmi #endif <commit_msg>dcmi: fix max temperature constant<commit_after>#ifndef __HOST_IPMI_DCMI_HANDLER_H__ #define __HOST_IPMI_DCMI_HANDLER_H__ #include <map> #include <string> #include <vector> #include <sdbusplus/bus.hpp> #include "nlohmann/json.hpp" namespace dcmi { enum Commands { // Get capability bits GET_CAPABILITIES = 0x01, GET_POWER_LIMIT = 0x03, SET_POWER_LIMIT = 0x04, APPLY_POWER_LIMIT = 0x05, GET_ASSET_TAG = 0x06, SET_ASSET_TAG = 0x08, GET_MGMNT_CTRL_ID_STR = 0x09, SET_MGMNT_CTRL_ID_STR = 0x0A, GET_TEMP_READINGS = 0x10, }; static constexpr auto propIntf = "org.freedesktop.DBus.Properties"; static constexpr auto assetTagIntf = "xyz.openbmc_project.Inventory.Decorator.AssetTag"; static constexpr auto assetTagProp = "AssetTag"; static constexpr auto networkServiceName = "xyz.openbmc_project.Network"; static constexpr auto networkConfigObj = "/xyz/openbmc_project/network/config"; static constexpr auto networkConfigIntf = "xyz.openbmc_project.Network.SystemConfiguration"; static constexpr auto hostNameProp = "HostName"; static constexpr auto temperatureSensorType = 0x01; namespace assettag { using ObjectPath = std::string; using Service = std::string; using Interfaces = std::vector<std::string>; using ObjectTree = std::map<ObjectPath, std::map<Service, Interfaces>>; } //namespace assettag namespace temp_readings { static constexpr auto maxDataSets = 8; static constexpr auto maxInstances = 255; static constexpr auto maxTemp = 127; // degrees C static constexpr auto configFile = "/usr/share/ipmi-providers/dcmi_temp_readings.json"; /** @struct Response * * DCMI payload for Get Temperature Readings response */ struct Response { #if BYTE_ORDER == LITTLE_ENDIAN uint8_t temperature: 7; //!< Temperature reading in Celsius uint8_t sign: 1; //!< Sign bit #endif #if BYTE_ORDER == BIG_ENDIAN uint8_t sign: 1; //!< Sign bit uint8_t temperature: 7; //!< Temperature reading in Celsius #endif uint8_t instance; //!< Entity instance number } __attribute__((packed)); using ResponseList = std::vector<Response>; using NumInstances = size_t; using Value = uint8_t; using Sign = bool; using Temperature = std::tuple<Value, Sign>; using Json = nlohmann::json; } static constexpr auto groupExtId = 0xDC; static constexpr auto assetTagMaxOffset = 62; static constexpr auto assetTagMaxSize = 63; static constexpr auto maxBytes = 16; static constexpr size_t maxCtrlIdStrLen = 63; /** @struct GetAssetTagRequest * * DCMI payload for Get Asset Tag command request. */ struct GetAssetTagRequest { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Offset to read. uint8_t bytes; //!< Number of bytes to read. } __attribute__((packed)); /** @struct GetAssetTagResponse * * DCMI payload for Get Asset Tag command response. */ struct GetAssetTagResponse { uint8_t groupID; //!< Group extension identification. uint8_t tagLength; //!< Total asset tag length. } __attribute__((packed)); /** @struct SetAssetTagRequest * * DCMI payload for Set Asset Tag command request. */ struct SetAssetTagRequest { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Offset to write. uint8_t bytes; //!< Number of bytes to write. } __attribute__((packed)); /** @struct SetAssetTagResponse * * DCMI payload for Set Asset Tag command response. */ struct SetAssetTagResponse { uint8_t groupID; //!< Group extension identification. uint8_t tagLength; //!< Total asset tag length. } __attribute__((packed)); /** @brief Read the object tree to fetch the object path that implemented the * Asset tag interface. * * @param[in,out] objectTree - object tree * * @return On success return the object tree with the object path that * implemented the AssetTag interface. */ void readAssetTagObjectTree(dcmi::assettag::ObjectTree& objectTree); /** @brief Read the asset tag of the server * * @return On success return the asset tag. */ std::string readAssetTag(); /** @brief Write the asset tag to the asset tag DBUS property * * @param[in] assetTag - Asset Tag to be written to the property. */ void writeAssetTag(const std::string& assetTag); /** @brief Read the current power cap value * * @param[in] bus - dbus connection * * @return On success return the power cap value. */ uint32_t getPcap(sdbusplus::bus::bus& bus); /** @brief Check if the power capping is enabled * * @param[in] bus - dbus connection * * @return true if the powerCap is enabled and false if the powercap * is disabled. */ bool getPcapEnabled(sdbusplus::bus::bus& bus); /** @struct GetPowerLimitRequest * * DCMI payload for Get Power Limit command request. */ struct GetPowerLimitRequest { uint8_t groupID; //!< Group extension identification. uint16_t reserved; //!< Reserved } __attribute__((packed)); /** @struct GetPowerLimitResponse * * DCMI payload for Get Power Limit command response. */ struct GetPowerLimitResponse { uint8_t groupID; //!< Group extension identification. uint16_t reserved; //!< Reserved. uint8_t exceptionAction; //!< Exception action. uint16_t powerLimit; //!< Power limit requested in watts. uint32_t correctionTime; //!< Correction time limit in milliseconds. uint16_t reserved1; //!< Reserved. uint16_t samplingPeriod; //!< Statistics sampling period in seconds. } __attribute__((packed)); /** @brief Set the power cap value * * @param[in] bus - dbus connection * @param[in] powerCap - power cap value */ void setPcap(sdbusplus::bus::bus& bus, const uint32_t powerCap); /** @struct SetPowerLimitRequest * * DCMI payload for Set Power Limit command request. */ struct SetPowerLimitRequest { uint8_t groupID; //!< Group extension identification. uint16_t reserved; //!< Reserved uint8_t reserved1; //!< Reserved uint8_t exceptionAction; //!< Exception action. uint16_t powerLimit; //!< Power limit requested in watts. uint32_t correctionTime; //!< Correction time limit in milliseconds. uint16_t reserved2; //!< Reserved. uint16_t samplingPeriod; //!< Statistics sampling period in seconds. } __attribute__((packed)); /** @struct SetPowerLimitResponse * * DCMI payload for Set Power Limit command response. */ struct SetPowerLimitResponse { uint8_t groupID; //!< Group extension identification. } __attribute__((packed)); /** @brief Enable or disable the power capping * * @param[in] bus - dbus connection * @param[in] enabled - enable/disable */ void setPcapEnable(sdbusplus::bus::bus& bus, bool enabled); /** @struct ApplyPowerLimitRequest * * DCMI payload for Activate/Deactivate Power Limit command request. */ struct ApplyPowerLimitRequest { uint8_t groupID; //!< Group extension identification. uint8_t powerLimitAction; //!< Power limit activation uint16_t reserved; //!< Reserved } __attribute__((packed)); /** @struct ApplyPowerLimitResponse * * DCMI payload for Acticate/Deactivate Power Limit command response. */ struct ApplyPowerLimitResponse { uint8_t groupID; //!< Group extension identification. } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrRequest * * DCMI payload for Get Management Controller Identifier String cmd request. */ struct GetMgmntCtrlIdStrRequest { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Offset to read. uint8_t bytes; //!< Number of bytes to read. } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrResponse * * DCMI payload for Get Management Controller Identifier String cmd response. */ struct GetMgmntCtrlIdStrResponse { uint8_t groupID; //!< Group extension identification. uint8_t strLen; //!< ID string length. char data[]; //!< ID string } __attribute__((packed)); /** @struct SetMgmntCtrlIdStrRequest * * DCMI payload for Set Management Controller Identifier String cmd request. */ struct SetMgmntCtrlIdStrRequest { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Offset to write. uint8_t bytes; //!< Number of bytes to read. char data[]; //!< ID string } __attribute__((packed)); /** @struct GetMgmntCtrlIdStrResponse * * DCMI payload for Get Management Controller Identifier String cmd response. */ struct SetMgmntCtrlIdStrResponse { uint8_t groupID; //!< Group extension identification. uint8_t offset; //!< Last Offset Written. } __attribute__((packed)); /** @enum DCMICapParameters * * DCMI Capability parameters */ enum class DCMICapParameters { SUPPORTED_DCMI_CAPS = 0x01, //!< Supported DCMI Capabilities MANDATORY_PLAT_ATTRIBUTES = 0x02, //!< Mandatory Platform Attributes OPTIONAL_PLAT_ATTRIBUTES = 0x03, //!< Optional Platform Attributes MANAGEABILITY_ACCESS_ATTRIBUTES = 0x04, //!< Manageability Access Attributes }; /** @struct GetDCMICapRequest * * DCMI payload for Get capabilities cmd request. */ struct GetDCMICapRequest { uint8_t groupID; //!< Group extension identification. uint8_t param; //!< Capability parameter selector. } __attribute__((packed)); /** @struct GetDCMICapRequest * * DCMI payload for Get capabilities cmd response. */ struct GetDCMICapResponse { uint8_t groupID; //!< Group extension identification. uint8_t major; //!< DCMI Specification Conformance - major ver uint8_t minor; //!< DCMI Specification Conformance - minor ver uint8_t paramRevision; //!< Parameter Revision = 02h uint8_t data[]; //!< Capability array } __attribute__((packed)); /** @struct DCMICap * * DCMI capabilities protocol info. */ struct DCMICap { std::string name; //!< Name of DCMI capability. uint8_t bytePosition; //!< Starting byte number from DCMI spec. uint8_t position; //!< bit position from the DCMI spec. uint8_t length; //!< Length of the value from DCMI spec. }; using DCMICapList = std::vector<DCMICap>; /** @struct DCMICapEntry * * DCMI capabilities list and size for each parameter. */ struct DCMICapEntry { uint8_t size; //!< Size of capability array in bytes. DCMICapList capList; //!< List of capabilities for a parameter. }; using DCMICaps = std::map<DCMICapParameters, DCMICapEntry>; /** @struct GetTempReadingsRequest * * DCMI payload for Get Temperature Readings request */ struct GetTempReadingsRequest { uint8_t groupID; //!< Group extension identification. uint8_t sensorType; //!< Type of the sensor uint8_t entityId; //!< Entity ID uint8_t entityInstance; //!< Entity Instance (0 means all instances) uint8_t instanceStart; //!< Instance start (used if instance is 0) } __attribute__((packed)); /** @struct GetTempReadingsResponse * * DCMI header for Get Temperature Readings response */ struct GetTempReadingsResponseHdr { uint8_t groupID; //!< Group extension identification. uint8_t numInstances; //!< No. of instances for requested id uint8_t numDataSets; //!< No. of sets of temperature data } __attribute__((packed)); namespace temp_readings { /** @brief Read temperature from a d-bus object, scale it as per dcmi * get temperature reading requirements. * * @param[in] dbusService - the D-Bus service * @param[in] dbusPath - the D-Bus path * * @return A temperature reading */ Temperature readTemp(const std::string& dbusService, const std::string& dbusPath); /** @brief Parse out JSON config file containing information * related to temperature readings. * * @return A json object */ Json parseConfig(); /** @brief Read temperatures and fill up DCMI response for the Get * Temperature Readings command. This looks at a specific * instance. * * @param[in] type - one of "inlet", "cpu", "baseboard" * @param[in] instance - A non-zero Entity instance number * * @return A tuple, containing a temperature reading and the * number of instances. */ std::tuple<Response, NumInstances> read (const std::string& type, uint8_t instance); /** @brief Read temperatures and fill up DCMI response for the Get * Temperature Readings command. This looks at a range of * instances. * * @param[in] type - one of "inlet", "cpu", "baseboard" * @param[in] instanceStart - Entity instance start index * * @return A tuple, containing a list of temperature readings and the * number of instances. */ std::tuple<ResponseList, NumInstances> readAll(const std::string& type, uint8_t instanceStart); } } // namespace dcmi #endif <|endoftext|>
<commit_before>/* PCDM Login Manager: * Written by Ken Moore (ken@pcbsd.org) 2012/2013 * Copyright(c) 2013 by the PC-BSD Project * Available under the 3-clause BSD license */ #include <QApplication> #include <QTranslator> #include <QLocale> #include <QDesktopWidget> #include <QFile> #include <QSplashScreen> #include <QTime> #include <QDebug> #include <QX11Info> #include <QTextCodec> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> //#define TMPLANGFILE QString("/var/tmp/.PCDMLang") #define TMPAUTOLOGINFILE QString("/var/tmp/.PCDMAutoLogin") #define TMPAUTHFILE QString("/var/tmp/.PCDMAuth") #define TMPSTOPFILE QString("/var/tmp/.PCDMstop") #include "pcdm-gui.h" #include "pcdm-backend.h" #include "pcdm-config.h" #include "pcdm-xprocess.h" #include "pcdm-logindelay.h" //bool USECLIBS=false; //Global classes UserList *USERS = 0; //Setup any qDebug/qWarning/qError messages to get saved into this log file directly QFile logfile("/var/log/PCDM.log"); void MessageOutput(QtMsgType type, const QMessageLogContext &, const QString &msg){ QString txt; switch(type){ case QtDebugMsg: txt = QString("Debug: %1").arg(msg); break; case QtWarningMsg: txt = QString("Warning: %1").arg(msg); break; case QtCriticalMsg: txt = QString("CRITICAL: %1").arg(msg); break; case QtFatalMsg: txt = QString("FATAL: %1").arg(msg); break; default: txt = msg; } QTextStream out(&logfile); out << txt; if(!txt.endsWith("\n")){ out << "\n"; } } int runSingleSession(int argc, char *argv[]){ //QTime clock; //clock.start(); Backend::checkLocalDirs(); // Create and fill "/usr/local/share/PCDM" if needed //Setup the log file qDebug() << "PCDM Log File: /var/log/PCDM.log"; //This does not go into the log if(QFile::exists(logfile.fileName()+".old")){ QFile::remove(logfile.fileName()+".old"); } if(logfile.exists()){ QFile::rename(logfile.fileName(), logfile.fileName()+".old"); } //Make sure the parent directory exists if(!QFile::exists("/var/log")){ QDir dir; dir.mkpath("/var/log"); } logfile.open(QIODevice::WriteOnly | QIODevice::Append); //Backend::openLogFile("/var/log/PCDM.log"); //qDebug() << "Backend Checks Finished:" << QString::number(clock.elapsed())+" ms"; Backend::loadDPIpreference(); //Setup the initial system environment (locale, keyboard) QString lang, kmodel, klayout, kvariant; Backend::readDefaultSysEnvironment(lang,kmodel,klayout,kvariant); lang = lang.section(".",0,0).simplified(); //just in case it also had the encoding saved to the file if(lang.isEmpty() || lang.toLower()=="c"){ lang = "en_US"; } setenv("LANG", lang.toUtf8(), 0); Backend::changeKbMap(kmodel,klayout,kvariant); //Check for the flag to try and auto-login bool ALtriggered = false; if(QFile::exists(TMPAUTOLOGINFILE)){ ALtriggered=true; QFile::remove(TMPAUTOLOGINFILE); } //QString changeLang; // Load the configuration file QString confFile = "/usr/local/etc/pcdm.conf"; if(!QFile::exists(confFile)){ qDebug() << "PCDM: Configuration file missing:"<<confFile<<"\n - Using default configuration"; QFile::copy(":samples/pcdm.conf", confFile); } Config::loadConfigFile(confFile); // Now set the backend functionality of which usernames are allowed if(USERS==0){ USERS = new UserList(); USERS->allowUnder1K(Config::allowUnder1KUsers()); USERS->allowRootUser(Config::allowRootUser()); USERS->excludeUsers(Config::excludedUserList()); USERS->updateList(); //now start the probe so things are ready on demand } //Backend::allowUidUnder1K(Config::allowUnder1KUsers(), Config::excludedUserList()); //qDebug() << "Config File Loaded:" << QString::number(clock.elapsed())+" ms"; // Startup the main application QApplication a(argc,argv); //Setup Log File qInstallMessageHandler(MessageOutput); int retCode = 0; //used for UI/application return // Show our splash screen, so the user doesn't freak that that it takes a few seconds to show up /*QSplashScreen splash; if(!Config::splashscreen().isEmpty()){ splash.setPixmap( QPixmap(Config::splashscreen()) ); //load the splashscreen file } splash.show();*/ //QCoreApplication::processEvents(); //Process the splash screen event immediately //qDebug() << "SplashScreen Started:" << QString::number(clock.elapsed())+" ms"; //Initialize the xprocess XProcess desktop; // Check what directory our app is in QString appDir = "/usr/local/share/PCDM"; // Load the translator QTranslator translator; QString langCode = lang; //Check for a language change detected //if ( ! changeLang.isEmpty() ) //langCode = changeLang; //Load the proper locale for the translator if ( QFile::exists(appDir + "/i18n/PCDM_" + langCode + ".qm" ) ) { translator.load( QString("PCDM_") + langCode, appDir + "/i18n/" ); a.installTranslator(&translator); qDebug() <<"Loaded Translation:" + appDir + "/i18n/PCDM_" + langCode + ".qm"; } else { qDebug() << "Could not find: " + appDir + "/i18n/PCDM_" + langCode + ".qm"; langCode = "en_US"; //always default to US english } QTextCodec::setCodecForLocale( QTextCodec::codecForName("UTF-8") ); //Force Utf-8 compliance //qDebug() << "Translation Finished:" << QString::number(clock.elapsed())+" ms"; QProcess compositor; if ( QFile::exists("/usr/local/bin/compton") ) { compositor.start("/usr/local/bin/compton"); } // Check if VirtualGL is in use, open up the system for GL rendering if so if ( Config::enableVGL() ) { system("xhost +"); } // *** STARTUP THE PROGRAM *** bool goodAL = false; //Flag for whether the autologin was successful // Start the autologin procedure if applicable if( ALtriggered && Config::useAutoLogin() ){ //Setup the Auto Login QString user = Backend::getALUsername(); QString pwd = Backend::getALPassword(); QString dsk = Backend::getLastDE(user, ""); if( user.isEmpty() || dsk.isEmpty() || QFile::exists("/var/db/personacrypt/"+user+".key") ){ //Invalid inputs (or a PersonaCrypt user) goodAL=false; }else{ //Run the time delay for the autologin attempt if(Config::autoLoginDelay() > 1){ ThemeStruct ctheme; ctheme.loadThemeFile(Config::themeFile()); loginDelay dlg(Config::autoLoginDelay(), user, ctheme.itemValue("background") ); //splash.close(); dlg.start(); dlg.activateWindow(); dlg.exec(); goodAL = dlg.continueLogin; }else{ goodAL = true; } //now start the autologin if appropriate if(goodAL){ desktop.loginToXSession(user,pwd, dsk,lang,"",false); //splash.close(); if(desktop.isRunning()){ goodAL=true; //flag this as a good login to skip the GUI } } } } //qDebug() << "AutoLogin Finished:" << QString::number(clock.elapsed())+" ms"; if(!goodAL){ // ------START THE PCDM GUI------- retCode = -1; while(retCode==-1){ retCode = 0; qDebug() << "Starting up PCDM interface"; PCDMgui w; QLocale locale(lang); //Always use the "lang" saved from last login - even if the "langCode" was reset to en_US for loading PCDM translations w.setLocale(locale); //qDebug() << "Main GUI Created:" << QString::number(clock.elapsed())+" ms"; //splash.finish(&w); //close the splash when the GUI starts up //Setup the signals/slots to startup the desktop session QObject::connect( &w,SIGNAL(xLoginAttempt(QString,QString,QString,QString, QString, bool)), &desktop,SLOT(loginToXSession(QString,QString,QString,QString, QString,bool)) ); //Setup the signals/slots for return information for the GUI QObject::connect( &desktop, SIGNAL(InvalidLogin()), &w, SLOT(slotLoginFailure()) ); QObject::connect( &desktop, SIGNAL(started()), &w, SLOT(slotLoginSuccess()) ); QObject::connect( &desktop, SIGNAL(ValidLogin()), &w, SLOT(slotLoginSuccess()) ); //qDebug() << "Showing GUI:" << QString::number(clock.elapsed())+" ms"; w.show(); //Now start the event loop until the window closes retCode = a.exec(); }//end special retCode==-1 check (restart GUI) } // end of PCDM GUI running USERS->stopUpdates(); //Wait for the desktop session to finish before exiting if(compositor.state()==QProcess::Running){ compositor.terminate(); } desktop.waitForSessionClosed(); qDebug() << "PCDM Session finished"; logfile.close(); //splash.show(); //show the splash screen again //Now wait a couple seconds for things to settle QTime wTime = QTime::currentTime().addSecs(2); while( QTime::currentTime() < wTime ){ QCoreApplication::processEvents(QEventLoop::AllEvents,100); } //check for shutdown process if( QFile::exists(TMPSTOPFILE) || QFile::exists("/var/run/nologin") || retCode > 0){ //splash.showMessage(QObject::tr("System Shutting Down"), Qt::AlignHCenter | Qt::AlignBottom, Qt::white); QCoreApplication::processEvents(); //Pause for a few seconds to prevent starting a new session during a shutdown wTime = QTime::currentTime().addSecs(30); while( QTime::currentTime() < wTime ){ //Keep processing events during the wait (for splashscreen) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); } } //Clean up Code delete &desktop; delete &a; //delete &splash; return retCode; } int main(int argc, char *argv[]) { bool neverquit = true; bool runonce = true; //Always set this for now until the internal repeater works properly setenv("MM_CHARSET", "UTF-8", 1); //ensure UTF-8 text formatting if(argc==2){ if( QString(argv[1]) == "-once"){ runonce = true; } } while(neverquit){ if(runonce){ neverquit = false; } qDebug() << " -- PCDM Session Starting..."; /*int sid = -1; int pid = fork(); if(pid < 0){ qDebug() << "Error: Could not fork the PCDM session"; return -1; }else if( pid ==0 ){ //New Child Process sid = setsid(); //start a session qDebug() << "-- Session ID:" << sid;*/ int retCode = runSingleSession(argc,argv); qDebug() << "-- PCDM Session Ended --"; //check for special exit code if(retCode == -1){ neverquit=true; } //make sure we go around again at least once else if(retCode != 0){ neverquit=false; } //Now kill the shild process (whole session) /*qDebug() << "Exiting child process"; exit(3); }else{ //Parent (calling) process int status; sleep(2); waitpid(sid,&status,0); //wait for the child (session) to finish //NOTE: the parent will eventually become a login-watcher daemon process that // can spawn multiple child sessions on different TTY displays }*/ qDebug() << "-- PCDM Session Ended --"; if(QFile::exists("/var/run/nologin") || QFile::exists(TMPSTOPFILE) ){ neverquit = false; } } return 0; } <commit_msg>Remove these double deletes.<commit_after>/* PCDM Login Manager: * Written by Ken Moore (ken@pcbsd.org) 2012/2013 * Copyright(c) 2013 by the PC-BSD Project * Available under the 3-clause BSD license */ #include <QApplication> #include <QTranslator> #include <QLocale> #include <QDesktopWidget> #include <QFile> #include <QSplashScreen> #include <QTime> #include <QDebug> #include <QX11Info> #include <QTextCodec> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> //#define TMPLANGFILE QString("/var/tmp/.PCDMLang") #define TMPAUTOLOGINFILE QString("/var/tmp/.PCDMAutoLogin") #define TMPAUTHFILE QString("/var/tmp/.PCDMAuth") #define TMPSTOPFILE QString("/var/tmp/.PCDMstop") #include "pcdm-gui.h" #include "pcdm-backend.h" #include "pcdm-config.h" #include "pcdm-xprocess.h" #include "pcdm-logindelay.h" //bool USECLIBS=false; //Global classes UserList *USERS = 0; //Setup any qDebug/qWarning/qError messages to get saved into this log file directly QFile logfile("/var/log/PCDM.log"); void MessageOutput(QtMsgType type, const QMessageLogContext &, const QString &msg){ QString txt; switch(type){ case QtDebugMsg: txt = QString("Debug: %1").arg(msg); break; case QtWarningMsg: txt = QString("Warning: %1").arg(msg); break; case QtCriticalMsg: txt = QString("CRITICAL: %1").arg(msg); break; case QtFatalMsg: txt = QString("FATAL: %1").arg(msg); break; default: txt = msg; } QTextStream out(&logfile); out << txt; if(!txt.endsWith("\n")){ out << "\n"; } } int runSingleSession(int argc, char *argv[]){ //QTime clock; //clock.start(); Backend::checkLocalDirs(); // Create and fill "/usr/local/share/PCDM" if needed //Setup the log file qDebug() << "PCDM Log File: /var/log/PCDM.log"; //This does not go into the log if(QFile::exists(logfile.fileName()+".old")){ QFile::remove(logfile.fileName()+".old"); } if(logfile.exists()){ QFile::rename(logfile.fileName(), logfile.fileName()+".old"); } //Make sure the parent directory exists if(!QFile::exists("/var/log")){ QDir dir; dir.mkpath("/var/log"); } logfile.open(QIODevice::WriteOnly | QIODevice::Append); //Backend::openLogFile("/var/log/PCDM.log"); //qDebug() << "Backend Checks Finished:" << QString::number(clock.elapsed())+" ms"; Backend::loadDPIpreference(); //Setup the initial system environment (locale, keyboard) QString lang, kmodel, klayout, kvariant; Backend::readDefaultSysEnvironment(lang,kmodel,klayout,kvariant); lang = lang.section(".",0,0).simplified(); //just in case it also had the encoding saved to the file if(lang.isEmpty() || lang.toLower()=="c"){ lang = "en_US"; } setenv("LANG", lang.toUtf8(), 0); Backend::changeKbMap(kmodel,klayout,kvariant); //Check for the flag to try and auto-login bool ALtriggered = false; if(QFile::exists(TMPAUTOLOGINFILE)){ ALtriggered=true; QFile::remove(TMPAUTOLOGINFILE); } //QString changeLang; // Load the configuration file QString confFile = "/usr/local/etc/pcdm.conf"; if(!QFile::exists(confFile)){ qDebug() << "PCDM: Configuration file missing:"<<confFile<<"\n - Using default configuration"; QFile::copy(":samples/pcdm.conf", confFile); } Config::loadConfigFile(confFile); // Now set the backend functionality of which usernames are allowed if(USERS==0){ USERS = new UserList(); USERS->allowUnder1K(Config::allowUnder1KUsers()); USERS->allowRootUser(Config::allowRootUser()); USERS->excludeUsers(Config::excludedUserList()); USERS->updateList(); //now start the probe so things are ready on demand } //Backend::allowUidUnder1K(Config::allowUnder1KUsers(), Config::excludedUserList()); //qDebug() << "Config File Loaded:" << QString::number(clock.elapsed())+" ms"; // Startup the main application QApplication a(argc,argv); //Setup Log File qInstallMessageHandler(MessageOutput); int retCode = 0; //used for UI/application return // Show our splash screen, so the user doesn't freak that that it takes a few seconds to show up /*QSplashScreen splash; if(!Config::splashscreen().isEmpty()){ splash.setPixmap( QPixmap(Config::splashscreen()) ); //load the splashscreen file } splash.show();*/ //QCoreApplication::processEvents(); //Process the splash screen event immediately //qDebug() << "SplashScreen Started:" << QString::number(clock.elapsed())+" ms"; //Initialize the xprocess XProcess desktop; // Check what directory our app is in QString appDir = "/usr/local/share/PCDM"; // Load the translator QTranslator translator; QString langCode = lang; //Check for a language change detected //if ( ! changeLang.isEmpty() ) //langCode = changeLang; //Load the proper locale for the translator if ( QFile::exists(appDir + "/i18n/PCDM_" + langCode + ".qm" ) ) { translator.load( QString("PCDM_") + langCode, appDir + "/i18n/" ); a.installTranslator(&translator); qDebug() <<"Loaded Translation:" + appDir + "/i18n/PCDM_" + langCode + ".qm"; } else { qDebug() << "Could not find: " + appDir + "/i18n/PCDM_" + langCode + ".qm"; langCode = "en_US"; //always default to US english } QTextCodec::setCodecForLocale( QTextCodec::codecForName("UTF-8") ); //Force Utf-8 compliance //qDebug() << "Translation Finished:" << QString::number(clock.elapsed())+" ms"; QProcess compositor; if ( QFile::exists("/usr/local/bin/compton") ) { compositor.start("/usr/local/bin/compton"); } // Check if VirtualGL is in use, open up the system for GL rendering if so if ( Config::enableVGL() ) { system("xhost +"); } // *** STARTUP THE PROGRAM *** bool goodAL = false; //Flag for whether the autologin was successful // Start the autologin procedure if applicable if( ALtriggered && Config::useAutoLogin() ){ //Setup the Auto Login QString user = Backend::getALUsername(); QString pwd = Backend::getALPassword(); QString dsk = Backend::getLastDE(user, ""); if( user.isEmpty() || dsk.isEmpty() || QFile::exists("/var/db/personacrypt/"+user+".key") ){ //Invalid inputs (or a PersonaCrypt user) goodAL=false; }else{ //Run the time delay for the autologin attempt if(Config::autoLoginDelay() > 1){ ThemeStruct ctheme; ctheme.loadThemeFile(Config::themeFile()); loginDelay dlg(Config::autoLoginDelay(), user, ctheme.itemValue("background") ); //splash.close(); dlg.start(); dlg.activateWindow(); dlg.exec(); goodAL = dlg.continueLogin; }else{ goodAL = true; } //now start the autologin if appropriate if(goodAL){ desktop.loginToXSession(user,pwd, dsk,lang,"",false); //splash.close(); if(desktop.isRunning()){ goodAL=true; //flag this as a good login to skip the GUI } } } } //qDebug() << "AutoLogin Finished:" << QString::number(clock.elapsed())+" ms"; if(!goodAL){ // ------START THE PCDM GUI------- retCode = -1; while(retCode==-1){ retCode = 0; qDebug() << "Starting up PCDM interface"; PCDMgui w; QLocale locale(lang); //Always use the "lang" saved from last login - even if the "langCode" was reset to en_US for loading PCDM translations w.setLocale(locale); //qDebug() << "Main GUI Created:" << QString::number(clock.elapsed())+" ms"; //splash.finish(&w); //close the splash when the GUI starts up //Setup the signals/slots to startup the desktop session QObject::connect( &w,SIGNAL(xLoginAttempt(QString,QString,QString,QString, QString, bool)), &desktop,SLOT(loginToXSession(QString,QString,QString,QString, QString,bool)) ); //Setup the signals/slots for return information for the GUI QObject::connect( &desktop, SIGNAL(InvalidLogin()), &w, SLOT(slotLoginFailure()) ); QObject::connect( &desktop, SIGNAL(started()), &w, SLOT(slotLoginSuccess()) ); QObject::connect( &desktop, SIGNAL(ValidLogin()), &w, SLOT(slotLoginSuccess()) ); //qDebug() << "Showing GUI:" << QString::number(clock.elapsed())+" ms"; w.show(); //Now start the event loop until the window closes retCode = a.exec(); }//end special retCode==-1 check (restart GUI) } // end of PCDM GUI running USERS->stopUpdates(); //Wait for the desktop session to finish before exiting if(compositor.state()==QProcess::Running){ compositor.terminate(); } desktop.waitForSessionClosed(); qDebug() << "PCDM Session finished"; logfile.close(); //splash.show(); //show the splash screen again //Now wait a couple seconds for things to settle QTime wTime = QTime::currentTime().addSecs(2); while( QTime::currentTime() < wTime ){ QCoreApplication::processEvents(QEventLoop::AllEvents,100); } //check for shutdown process if( QFile::exists(TMPSTOPFILE) || QFile::exists("/var/run/nologin") || retCode > 0){ //splash.showMessage(QObject::tr("System Shutting Down"), Qt::AlignHCenter | Qt::AlignBottom, Qt::white); QCoreApplication::processEvents(); //Pause for a few seconds to prevent starting a new session during a shutdown wTime = QTime::currentTime().addSecs(30); while( QTime::currentTime() < wTime ){ //Keep processing events during the wait (for splashscreen) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); } } return retCode; } int main(int argc, char *argv[]) { bool neverquit = true; bool runonce = true; //Always set this for now until the internal repeater works properly setenv("MM_CHARSET", "UTF-8", 1); //ensure UTF-8 text formatting if(argc==2){ if( QString(argv[1]) == "-once"){ runonce = true; } } while(neverquit){ if(runonce){ neverquit = false; } qDebug() << " -- PCDM Session Starting..."; /*int sid = -1; int pid = fork(); if(pid < 0){ qDebug() << "Error: Could not fork the PCDM session"; return -1; }else if( pid ==0 ){ //New Child Process sid = setsid(); //start a session qDebug() << "-- Session ID:" << sid;*/ int retCode = runSingleSession(argc,argv); qDebug() << "-- PCDM Session Ended --"; //check for special exit code if(retCode == -1){ neverquit=true; } //make sure we go around again at least once else if(retCode != 0){ neverquit=false; } //Now kill the shild process (whole session) /*qDebug() << "Exiting child process"; exit(3); }else{ //Parent (calling) process int status; sleep(2); waitpid(sid,&status,0); //wait for the child (session) to finish //NOTE: the parent will eventually become a login-watcher daemon process that // can spawn multiple child sessions on different TTY displays }*/ qDebug() << "-- PCDM Session Ended --"; if(QFile::exists("/var/run/nologin") || QFile::exists(TMPSTOPFILE) ){ neverquit = false; } } return 0; } <|endoftext|>
<commit_before>/// \file Buffer/main.cpp /// Contains the main code for the Buffer. #include <fcntl.h> #include <iostream> #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <string.h> #include <unistd.h> #include <signal.h> #include "../util/dtsc.h" //DTSC support #include "../util/socket.h" //Socket lib #include "../util/json/json.h" /// Holds all code unique to the Buffer. namespace Buffer{ Json::Value Storage = Json::Value(Json::objectValue); ///< Global storage of data. ///A simple signal handler that ignores all signals. void termination_handler (int signum){ switch (signum){ case SIGPIPE: return; break; default: return; break; } } DTSC::Stream * Strm = 0; /// Converts a stats line to up, down, host, connector and conntime values. class Stats{ public: unsigned int up; unsigned int down; std::string host; std::string connector; unsigned int conntime; Stats(){ up = 0; down = 0; conntime = 0; } Stats(std::string s){ size_t f = s.find(' '); if (f != std::string::npos){ host = s.substr(0, f); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ connector = s.substr(0, f); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ conntime = atoi(s.substr(0, f).c_str()); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ up = atoi(s.substr(0, f).c_str()); s.erase(0, f+1); down = atoi(s.c_str()); } } }; /// Holds connected users. /// Keeps track of what buffer users are using and the connection status. class user{ public: DTSC::Ring * myRing; ///< Ring of the buffer for this user. int MyNum; ///< User ID of this user. std::string MyStr; ///< User ID of this user as a string. int currsend; ///< Current amount of bytes sent. Stats lastStats; ///< Holds last known stats for this connection. unsigned int curr_up; ///< Holds the current estimated transfer speed up. unsigned int curr_down; ///< Holds the current estimated transfer speed down. bool gotproperaudio; ///< Whether the user received proper audio yet. void * lastpointer; ///< Pointer to data part of current buffer. static int UserCount; ///< Global user counter. Socket::Connection S; ///< Connection to user /// Creates a new user from a newly connected socket. /// Also prints "User connected" text to stdout. user(Socket::Connection fd){ S = fd; MyNum = UserCount++; std::stringstream st; st << MyNum; MyStr = st.str(); curr_up = 0; curr_down = 0; currsend = 0; myRing = 0; std::cout << "User " << MyNum << " connected" << std::endl; }//constructor /// Drops held DTSC::Ring class, if one is held. ~user(){ Strm->dropRing(myRing); }//destructor /// Disconnects the current user. Doesn't do anything if already disconnected. /// Prints "Disconnected user" to stdout if disconnect took place. void Disconnect(std::string reason) { if (S.connected()) { S.close(); } Storage["curr"].removeMember(MyStr); Storage["log"][MyStr]["connector"] = lastStats.connector; Storage["log"][MyStr]["up"] = lastStats.up; Storage["log"][MyStr]["down"] = lastStats.down; Storage["log"][MyStr]["conntime"] = lastStats.conntime; Storage["log"][MyStr]["host"] = lastStats.host; Storage["log"][MyStr]["start"] = (unsigned int)time(0) - lastStats.conntime; std::cout << "Disconnected user " << MyStr << ": " << reason << ". " << lastStats.connector << " transferred " << lastStats.up << " up and " << lastStats.down << " down in " << lastStats.conntime << " seconds to " << lastStats.host << std::endl; }//Disconnect /// Tries to send the current buffer, returns true if success, false otherwise. /// Has a side effect of dropping the connection if send will never complete. bool doSend(const char * ptr, int len){ int r = S.iwrite(ptr+currsend, len-currsend); if (r <= 0){ if (errno == EWOULDBLOCK){return false;} Disconnect(S.getError()); return false; } currsend += r; return (currsend == len); }//doSend /// Try to send data to this user. Disconnects if any problems occur. void Send(){ if (!myRing){return;}//no ring! if (!S.connected()){return;}//cancel if not connected if (myRing->waiting){return;}//still waiting for next buffer? if (myRing->starved){ //if corrupt data, warn and get new DTSC::Ring std::cout << "Warning: User was send corrupt video data and send to the next keyframe!" << std::endl; Strm->dropRing(myRing); myRing = Strm->getRing(); } currsend = 0; //try to complete a send if (doSend(Strm->outPacket(myRing->b).c_str(), Strm->outPacket(myRing->b).length())){ //switch to next buffer if (myRing->b <= 0){myRing->waiting = true; return;}//no next buffer? go in waiting mode. myRing->b--; currsend = 0; }//completed a send }//send }; int user::UserCount = 0; /// Starts a loop, waiting for connections to send data to. int Start(int argc, char ** argv) { //first make sure no segpipe signals will kill us struct sigaction new_action; new_action.sa_handler = termination_handler; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; sigaction (SIGPIPE, &new_action, NULL); //then check and parse the commandline if (argc < 2) { std::cout << "usage: " << argv[0] << " streamName [awaiting_IP]" << std::endl; return 1; } std::string waiting_ip = ""; bool ip_waiting = false; Socket::Connection ip_input; if (argc >= 4){ waiting_ip += argv[2]; ip_waiting = true; } std::string shared_socket = "/tmp/shared_socket_"; shared_socket += argv[1]; Socket::Server SS(shared_socket, true); Strm = new DTSC::Stream(5); std::vector<user> users; std::vector<user>::iterator usersIt; std::string inBuffer; char charBuffer[1024*10]; unsigned int charCount; unsigned int stattimer = 0; Socket::Connection incoming; Socket::Connection std_input(fileno(stdin)); Socket::Connection StatsSocket = Socket::Connection("/tmp/ddv_statistics", true); Storage["log"] = Json::Value(Json::objectValue); Storage["curr"] = Json::Value(Json::objectValue); Storage["totals"] = Json::Value(Json::objectValue); while((!feof(stdin) || ip_waiting) && !FLV::Parse_Error){ usleep(1000); //sleep for 1 ms, to prevent 100% CPU time unsigned int now = time(0); if (now != stattimer){ stattimer = now; unsigned int tot_up = 0, tot_down = 0, tot_count = 0; if (users.size() > 0){ for (usersIt = users.begin(); usersIt != users.end(); usersIt++){ tot_down += usersIt->curr_down; tot_up += usersIt->curr_up; tot_count++; } } Storage["totals"]["down"] = tot_down; Storage["totals"]["up"] = tot_up; Storage["totals"]["count"] = tot_count; Storage["totals"]["now"] = now; Storage["totals"]["buffer"] = argv[2]; if (!StatsSocket.connected()){ StatsSocket = Socket::Connection("/tmp/ddv_statistics", true); } if (StatsSocket.connected()){ StatsSocket.write(Storage.toStyledString()+"\n\n"); Storage["log"].clear(); } } //invalidate the current buffer if ( (!ip_waiting && std_input.canRead()) || (ip_waiting && ip_input.connected()) ){ std::cin.read(charBuffer, 1024*10); charCount = std::cin.gcount(); inBuffer.append(charBuffer, charCount); Strm->parsePacket(inBuffer); } //check for new connections, accept them if there are any incoming = SS.accept(true); if (incoming.connected()){ users.push_back(incoming); //send the header users.back().myRing = Strm->getRing(); if (!users.back().S.write(Strm->outHeader())){ /// \todo Do this more nicely? users.back().Disconnect("failed to receive the header!"); } } //go through all users if (users.size() > 0){ for (usersIt = users.begin(); usersIt != users.end(); usersIt++){ //remove disconnected users if (!(*usersIt).S.connected()){ (*usersIt).Disconnect("Closed"); users.erase(usersIt); break; }else{ if ((*usersIt).S.canRead()){ std::string tmp = ""; char charbuf; while (((*usersIt).S.iread(&charbuf, 1) == 1) && charbuf != '\n' ){ tmp += charbuf; } if (tmp != ""){ if (tmp[0] == 'P'){ std::cout << "Push attempt from IP " << tmp.substr(2) << std::endl; if (tmp.substr(2) == waiting_ip){ if (!ip_input.connected()){ std::cout << "Push accepted!" << std::endl; ip_input = (*usersIt).S; users.erase(usersIt); break; }else{ (*usersIt).Disconnect("Push denied - push already in progress!"); } }else{ (*usersIt).Disconnect("Push denied - invalid IP address!"); } } if (tmp[0] == 'S'){ Stats tmpStats = Stats(tmp.substr(2)); unsigned int secs = tmpStats.conntime - (*usersIt).lastStats.conntime; if (secs < 1){secs = 1;} (*usersIt).curr_up = (tmpStats.up - (*usersIt).lastStats.up) / secs; (*usersIt).curr_down = (tmpStats.down - (*usersIt).lastStats.down) / secs; (*usersIt).lastStats = tmpStats; Storage["curr"][(*usersIt).MyStr]["connector"] = tmpStats.connector; Storage["curr"][(*usersIt).MyStr]["up"] = tmpStats.up; Storage["curr"][(*usersIt).MyStr]["down"] = tmpStats.down; Storage["curr"][(*usersIt).MyStr]["conntime"] = tmpStats.conntime; Storage["curr"][(*usersIt).MyStr]["host"] = tmpStats.host; Storage["curr"][(*usersIt).MyStr]["start"] = (unsigned int) time(0) - tmpStats.conntime; } } } (*usersIt).Send(); } } } }//main loop // disconnect listener /// \todo Deal with EOF more nicely - doesn't send the end of the stream to all users! std::cout << "Reached EOF of input" << std::endl; SS.close(); while (users.size() > 0){ for (usersIt = users.begin(); usersIt != users.end(); usersIt++){ (*usersIt).Disconnect("Shutting down..."); if (!(*usersIt).S.connected()){users.erase(usersIt);break;} } } delete Strm; return 0; } };//Buffer namespace /// Entry point for Buffer, simply calls Buffer::Start(). int main(int argc, char ** argv){ return Buffer::Start(argc, argv); }//main <commit_msg>Buffer now compiles again<commit_after>/// \file Buffer/main.cpp /// Contains the main code for the Buffer. #include <fcntl.h> #include <iostream> #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <string.h> #include <unistd.h> #include <signal.h> #include <sstream> #include "../util/dtsc.h" //DTSC support #include "../util/socket.h" //Socket lib #include "../util/json/json.h" /// Holds all code unique to the Buffer. namespace Buffer{ Json::Value Storage = Json::Value(Json::objectValue); ///< Global storage of data. ///A simple signal handler that ignores all signals. void termination_handler (int signum){ switch (signum){ case SIGPIPE: return; break; default: return; break; } } DTSC::Stream * Strm = 0; /// Converts a stats line to up, down, host, connector and conntime values. class Stats{ public: unsigned int up; unsigned int down; std::string host; std::string connector; unsigned int conntime; Stats(){ up = 0; down = 0; conntime = 0; } Stats(std::string s){ size_t f = s.find(' '); if (f != std::string::npos){ host = s.substr(0, f); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ connector = s.substr(0, f); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ conntime = atoi(s.substr(0, f).c_str()); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ up = atoi(s.substr(0, f).c_str()); s.erase(0, f+1); down = atoi(s.c_str()); } } }; /// Holds connected users. /// Keeps track of what buffer users are using and the connection status. class user{ public: DTSC::Ring * myRing; ///< Ring of the buffer for this user. int MyNum; ///< User ID of this user. std::string MyStr; ///< User ID of this user as a string. int currsend; ///< Current amount of bytes sent. Stats lastStats; ///< Holds last known stats for this connection. unsigned int curr_up; ///< Holds the current estimated transfer speed up. unsigned int curr_down; ///< Holds the current estimated transfer speed down. bool gotproperaudio; ///< Whether the user received proper audio yet. void * lastpointer; ///< Pointer to data part of current buffer. static int UserCount; ///< Global user counter. Socket::Connection S; ///< Connection to user /// Creates a new user from a newly connected socket. /// Also prints "User connected" text to stdout. user(Socket::Connection fd){ S = fd; MyNum = UserCount++; std::stringstream st; st << MyNum; MyStr = st.str(); curr_up = 0; curr_down = 0; currsend = 0; myRing = 0; std::cout << "User " << MyNum << " connected" << std::endl; }//constructor /// Drops held DTSC::Ring class, if one is held. ~user(){ Strm->dropRing(myRing); }//destructor /// Disconnects the current user. Doesn't do anything if already disconnected. /// Prints "Disconnected user" to stdout if disconnect took place. void Disconnect(std::string reason) { if (S.connected()) { S.close(); } Storage["curr"].removeMember(MyStr); Storage["log"][MyStr]["connector"] = lastStats.connector; Storage["log"][MyStr]["up"] = lastStats.up; Storage["log"][MyStr]["down"] = lastStats.down; Storage["log"][MyStr]["conntime"] = lastStats.conntime; Storage["log"][MyStr]["host"] = lastStats.host; Storage["log"][MyStr]["start"] = (unsigned int)time(0) - lastStats.conntime; std::cout << "Disconnected user " << MyStr << ": " << reason << ". " << lastStats.connector << " transferred " << lastStats.up << " up and " << lastStats.down << " down in " << lastStats.conntime << " seconds to " << lastStats.host << std::endl; }//Disconnect /// Tries to send the current buffer, returns true if success, false otherwise. /// Has a side effect of dropping the connection if send will never complete. bool doSend(const char * ptr, int len){ int r = S.iwrite(ptr+currsend, len-currsend); if (r <= 0){ if (errno == EWOULDBLOCK){return false;} Disconnect(S.getError()); return false; } currsend += r; return (currsend == len); }//doSend /// Try to send data to this user. Disconnects if any problems occur. void Send(){ if (!myRing){return;}//no ring! if (!S.connected()){return;}//cancel if not connected if (myRing->waiting){return;}//still waiting for next buffer? if (myRing->starved){ //if corrupt data, warn and get new DTSC::Ring std::cout << "Warning: User was send corrupt video data and send to the next keyframe!" << std::endl; Strm->dropRing(myRing); myRing = Strm->getRing(); } currsend = 0; //try to complete a send if (doSend(Strm->outPacket(myRing->b).c_str(), Strm->outPacket(myRing->b).length())){ //switch to next buffer if (myRing->b <= 0){myRing->waiting = true; return;}//no next buffer? go in waiting mode. myRing->b--; currsend = 0; }//completed a send }//send }; int user::UserCount = 0; /// Starts a loop, waiting for connections to send data to. int Start(int argc, char ** argv) { //first make sure no segpipe signals will kill us struct sigaction new_action; new_action.sa_handler = termination_handler; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; sigaction (SIGPIPE, &new_action, NULL); //then check and parse the commandline if (argc < 2) { std::cout << "usage: " << argv[0] << " streamName [awaiting_IP]" << std::endl; return 1; } std::string waiting_ip = ""; bool ip_waiting = false; Socket::Connection ip_input; if (argc >= 4){ waiting_ip += argv[2]; ip_waiting = true; } std::string shared_socket = "/tmp/shared_socket_"; shared_socket += argv[1]; Socket::Server SS(shared_socket, true); Strm = new DTSC::Stream(5); std::vector<user> users; std::vector<user>::iterator usersIt; std::string inBuffer; char charBuffer[1024*10]; unsigned int charCount; unsigned int stattimer = 0; Socket::Connection incoming; Socket::Connection std_input(fileno(stdin)); Socket::Connection StatsSocket = Socket::Connection("/tmp/ddv_statistics", true); Storage["log"] = Json::Value(Json::objectValue); Storage["curr"] = Json::Value(Json::objectValue); Storage["totals"] = Json::Value(Json::objectValue); while (!feof(stdin) || ip_waiting){ usleep(1000); //sleep for 1 ms, to prevent 100% CPU time unsigned int now = time(0); if (now != stattimer){ stattimer = now; unsigned int tot_up = 0, tot_down = 0, tot_count = 0; if (users.size() > 0){ for (usersIt = users.begin(); usersIt != users.end(); usersIt++){ tot_down += usersIt->curr_down; tot_up += usersIt->curr_up; tot_count++; } } Storage["totals"]["down"] = tot_down; Storage["totals"]["up"] = tot_up; Storage["totals"]["count"] = tot_count; Storage["totals"]["now"] = now; Storage["totals"]["buffer"] = argv[2]; if (!StatsSocket.connected()){ StatsSocket = Socket::Connection("/tmp/ddv_statistics", true); } if (StatsSocket.connected()){ StatsSocket.write(Storage.toStyledString()+"\n\n"); Storage["log"].clear(); } } //invalidate the current buffer if ( (!ip_waiting && std_input.canRead()) || (ip_waiting && ip_input.connected()) ){ std::cin.read(charBuffer, 1024*10); charCount = std::cin.gcount(); inBuffer.append(charBuffer, charCount); Strm->parsePacket(inBuffer); } //check for new connections, accept them if there are any incoming = SS.accept(true); if (incoming.connected()){ users.push_back(incoming); //send the header users.back().myRing = Strm->getRing(); if (!users.back().S.write(Strm->outHeader())){ /// \todo Do this more nicely? users.back().Disconnect("failed to receive the header!"); } } //go through all users if (users.size() > 0){ for (usersIt = users.begin(); usersIt != users.end(); usersIt++){ //remove disconnected users if (!(*usersIt).S.connected()){ (*usersIt).Disconnect("Closed"); users.erase(usersIt); break; }else{ if ((*usersIt).S.canRead()){ std::string tmp = ""; char charbuf; while (((*usersIt).S.iread(&charbuf, 1) == 1) && charbuf != '\n' ){ tmp += charbuf; } if (tmp != ""){ if (tmp[0] == 'P'){ std::cout << "Push attempt from IP " << tmp.substr(2) << std::endl; if (tmp.substr(2) == waiting_ip){ if (!ip_input.connected()){ std::cout << "Push accepted!" << std::endl; ip_input = (*usersIt).S; users.erase(usersIt); break; }else{ (*usersIt).Disconnect("Push denied - push already in progress!"); } }else{ (*usersIt).Disconnect("Push denied - invalid IP address!"); } } if (tmp[0] == 'S'){ Stats tmpStats = Stats(tmp.substr(2)); unsigned int secs = tmpStats.conntime - (*usersIt).lastStats.conntime; if (secs < 1){secs = 1;} (*usersIt).curr_up = (tmpStats.up - (*usersIt).lastStats.up) / secs; (*usersIt).curr_down = (tmpStats.down - (*usersIt).lastStats.down) / secs; (*usersIt).lastStats = tmpStats; Storage["curr"][(*usersIt).MyStr]["connector"] = tmpStats.connector; Storage["curr"][(*usersIt).MyStr]["up"] = tmpStats.up; Storage["curr"][(*usersIt).MyStr]["down"] = tmpStats.down; Storage["curr"][(*usersIt).MyStr]["conntime"] = tmpStats.conntime; Storage["curr"][(*usersIt).MyStr]["host"] = tmpStats.host; Storage["curr"][(*usersIt).MyStr]["start"] = (unsigned int) time(0) - tmpStats.conntime; } } } (*usersIt).Send(); } } } }//main loop // disconnect listener /// \todo Deal with EOF more nicely - doesn't send the end of the stream to all users! std::cout << "Reached EOF of input" << std::endl; SS.close(); while (users.size() > 0){ for (usersIt = users.begin(); usersIt != users.end(); usersIt++){ (*usersIt).Disconnect("Shutting down..."); if (!(*usersIt).S.connected()){users.erase(usersIt);break;} } } delete Strm; return 0; } };//Buffer namespace /// Entry point for Buffer, simply calls Buffer::Start(). int main(int argc, char ** argv){ return Buffer::Start(argc, argv); }//main <|endoftext|>
<commit_before>#include "Arduino.h" #include "ButtonState.h" ButtonState::ButtonState(int pin) { pinMode(pin, INPUT_PULLUP); _pin = pin; _state = HIGH; _lastState = HIGH; _startHold = 0; _holdDelay = 20; _allow = false; _dSwitch = -1; } void ButtonState::observer() { _state = digitalRead(_pin); if (_state == LOW && _lastState == HIGH){ _startHold = millis(); _allow = true; } if (_allow == true && _state == LOW && _lastState == LOW){ if ((millis() - _startHold) >= _holdDelay){ Serial.println(_pin); _allow = false; if (_dSwitch>-1) { digitalWrite(_dSwitch, !digitalRead(_dSwitch)); } if (_call) { _call(); } } } _lastState = _state; } void ButtonState::whenPressedCall(void (*callType)()) { _call = &(*callType); } void ButtonState::whenPressedDigitalSwitch(int pin) { _dSwitch = pin; } void ButtonState::setHoldDelay(long delay) { _holdDelay = delay; } <commit_msg>Refactory internal callback variable<commit_after>#include "Arduino.h" #include "ButtonState.h" ButtonState::ButtonState(int pin) { pinMode(pin, INPUT_PULLUP); _pin = pin; _state = HIGH; _lastState = HIGH; _startHold = 0; _holdDelay = 20; _allow = false; _dSwitch = -1; } void ButtonState::observer() { _state = digitalRead(_pin); if (_state == LOW && _lastState == HIGH){ _startHold = millis(); _allow = true; } if (_allow == true && _state == LOW && _lastState == LOW){ if ((millis() - _startHold) >= _holdDelay){ Serial.println(_pin); _allow = false; if (_dSwitch>-1) { digitalWrite(_dSwitch, !digitalRead(_dSwitch)); } if (_call) { _call(); } } } _lastState = _state; } void ButtonState::whenPressedCall(void (*callback)()) { _call = &(*callback); } void ButtonState::whenPressedDigitalSwitch(int pin) { _dSwitch = pin; } void ButtonState::setHoldDelay(long delay) { _holdDelay = delay; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <cctype> using namespace std; int main(int argc, char *argv[]) { if(argc==1) //quit if no argument { cerr<<"Usage: "<<argv[0]<<" filename[s]\n"; exit(EXIT_FAILURE); } string str,str1; for(int file=1;file<argc;file++) { ifstream fin; //open stream fin.open(argv[file]); getline(fin,str); for(auto c : str) { if(!ispunct(c)) str1 += c; } fin.clear(); fin.close(); } cout<<str1<<endl; return 0; }<commit_msg>test for ex3_11<commit_after>#include <iostream> #include <fstream> #include <string> #include <cctype> using namespace std; int main(int argc, char *argv[]) { if(argc==1) //quit if no argument { cerr<<"Usage: "<<argv[0]<<" filename[s]\n"; exit(EXIT_FAILURE); } string str,str1; for(int file=1;file<argc;file++) { ifstream fin; //open stream fin.open(argv[file]); while(getline(fin,str)) { for(auto c : str) { if(!ispunct(c)) str1 += c; } } fin.clear(); fin.close(); } cout<<str1<<endl; return 0; }<|endoftext|>
<commit_before>//===- Writer.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Config.h" #include "Writer.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstdio> #include <functional> #include <map> #include <utility> using namespace llvm; using namespace llvm::COFF; using namespace llvm::object; using namespace llvm::support; using namespace llvm::support::endian; static const int PageSize = 4096; static const int FileAlignment = 512; static const int SectionAlignment = 4096; static const int DOSStubSize = 64; static const int NumberfOfDataDirectory = 16; static const int HeaderSize = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) + sizeof(pe32plus_header) + sizeof(data_directory) * NumberfOfDataDirectory; namespace lld { namespace coff { void OutputSection::setRVA(uint64_t RVA) { Header.VirtualAddress = RVA; for (Chunk *C : Chunks) C->setRVA(C->getRVA() + RVA); } void OutputSection::setFileOffset(uint64_t Off) { // If a section has no actual data (i.e. BSS section), we want to // set 0 to its PointerToRawData. Otherwise the output is rejected // by the loader. if (Header.SizeOfRawData == 0) return; Header.PointerToRawData = Off; for (Chunk *C : Chunks) C->setFileOff(C->getFileOff() + Off); } void OutputSection::addChunk(Chunk *C) { Chunks.push_back(C); uint64_t Off = Header.VirtualSize; Off = RoundUpToAlignment(Off, C->getAlign()); C->setRVA(Off); C->setFileOff(Off); Off += C->getSize(); Header.VirtualSize = Off; if (C->hasData()) Header.SizeOfRawData = RoundUpToAlignment(Off, FileAlignment); } void OutputSection::addPermissions(uint32_t C) { Header.Characteristics = Header.Characteristics | (C & PermMask); } // Write the section header to a given buffer. void OutputSection::writeHeader(uint8_t *Buf) { auto *Hdr = reinterpret_cast<coff_section *>(Buf); *Hdr = Header; if (StringTableOff) { // If name is too long, write offset into the string table as a name. sprintf(Hdr->Name, "/%d", StringTableOff); } else { assert(Name.size() <= COFF::NameSize); strncpy(Hdr->Name, Name.data(), Name.size()); } } void Writer::markLive() { for (StringRef Name : Config->GCRoots) cast<Defined>(Symtab->find(Name))->markLive(); for (Chunk *C : Symtab->getChunks()) if (C->isRoot()) C->markLive(); } void Writer::createSections() { std::map<StringRef, std::vector<Chunk *>> Map; for (Chunk *C : Symtab->getChunks()) { if (!C->isLive()) { if (Config->Verbose) C->printDiscardedMessage(); continue; } // '$' and all following characters in input section names are // discarded when determining output section. So, .text$foo // contributes to .text, for example. See PE/COFF spec 3.2. Map[C->getSectionName().split('$').first].push_back(C); } // Input sections are ordered by their names including '$' parts, // which gives you some control over the output layout. auto Comp = [](Chunk *A, Chunk *B) { return A->getSectionName() < B->getSectionName(); }; for (auto &P : Map) { StringRef SectionName = P.first; std::vector<Chunk *> &Chunks = P.second; std::stable_sort(Chunks.begin(), Chunks.end(), Comp); size_t SectIdx = OutputSections.size(); auto Sec = new (CAlloc.Allocate()) OutputSection(SectionName, SectIdx); for (Chunk *C : Chunks) { C->setOutputSection(Sec); Sec->addChunk(C); Sec->addPermissions(C->getPermissions()); } OutputSections.push_back(Sec); } } // Create .idata section for the DLL-imported symbol table. // The format of this section is inherently Windows-specific. // IdataContents class abstracted away the details for us, // so we just let it create chunks and add them to the section. void Writer::createImportTables() { if (Symtab->ImportFiles.empty()) return; OutputSection *Text = createSection(".text"); Idata.reset(new IdataContents()); for (std::unique_ptr<ImportFile> &File : Symtab->ImportFiles) { for (SymbolBody *Body : File->getSymbols()) { if (auto *Import = dyn_cast<DefinedImportData>(Body)) { Idata->add(Import); continue; } // Linker-created function thunks for DLL symbols are added to // .text section. Text->addChunk(cast<DefinedImportThunk>(Body)->getChunk()); } } OutputSection *Sec = createSection(".idata"); for (Chunk *C : Idata->getChunks()) Sec->addChunk(C); } // The Windows loader doesn't seem to like empty sections, // so we remove them if any. void Writer::removeEmptySections() { auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; }; OutputSections.erase( std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty), OutputSections.end()); } // Visits all sections to assign incremental, non-overlapping RVAs and // file offsets. void Writer::assignAddresses() { SizeOfHeaders = RoundUpToAlignment( HeaderSize + sizeof(coff_section) * OutputSections.size(), PageSize); uint64_t RVA = 0x1000; // The first page is kept unmapped. uint64_t FileOff = SizeOfHeaders; for (OutputSection *Sec : OutputSections) { Sec->setRVA(RVA); Sec->setFileOffset(FileOff); RVA += RoundUpToAlignment(Sec->getVirtualSize(), PageSize); FileOff += RoundUpToAlignment(Sec->getRawSize(), FileAlignment); } SizeOfImage = SizeOfHeaders + RoundUpToAlignment(RVA - 0x1000, PageSize); FileSize = SizeOfHeaders + RoundUpToAlignment(FileOff - SizeOfHeaders, FileAlignment); } static MachineTypes inferMachineType(std::vector<std::unique_ptr<ObjectFile>> &ObjectFiles) { for (std::unique_ptr<ObjectFile> &File : ObjectFiles) { // Try to infer machine type from the magic byte of the object file. auto MT = static_cast<MachineTypes>(File->getCOFFObj()->getMachine()); if (MT != IMAGE_FILE_MACHINE_UNKNOWN) return MT; } return IMAGE_FILE_MACHINE_UNKNOWN; } void Writer::writeHeader() { // Write DOS stub uint8_t *Buf = Buffer->getBufferStart(); auto *DOS = reinterpret_cast<dos_header *>(Buf); Buf += DOSStubSize; DOS->Magic[0] = 'M'; DOS->Magic[1] = 'Z'; DOS->AddressOfRelocationTable = sizeof(dos_header); DOS->AddressOfNewExeHeader = DOSStubSize; // Write PE magic memcpy(Buf, PEMagic, sizeof(PEMagic)); Buf += sizeof(PEMagic); // Determine machine type, infer if needed. TODO: diagnose conflicts. MachineTypes MachineType = Config->MachineType; if (MachineType == IMAGE_FILE_MACHINE_UNKNOWN) MachineType = inferMachineType(Symtab->ObjectFiles); // Write COFF header auto *COFF = reinterpret_cast<coff_file_header *>(Buf); Buf += sizeof(*COFF); COFF->Machine = MachineType; COFF->NumberOfSections = OutputSections.size(); COFF->Characteristics = (IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_RELOCS_STRIPPED | IMAGE_FILE_LARGE_ADDRESS_AWARE); COFF->SizeOfOptionalHeader = sizeof(pe32plus_header) + sizeof(data_directory) * NumberfOfDataDirectory; // Write PE header auto *PE = reinterpret_cast<pe32plus_header *>(Buf); Buf += sizeof(*PE); PE->Magic = PE32Header::PE32_PLUS; PE->ImageBase = Config->ImageBase; PE->SectionAlignment = SectionAlignment; PE->FileAlignment = FileAlignment; PE->MajorImageVersion = Config->MajorImageVersion; PE->MinorImageVersion = Config->MinorImageVersion; PE->MajorOperatingSystemVersion = Config->MajorOSVersion; PE->MinorOperatingSystemVersion = Config->MinorOSVersion; PE->MajorSubsystemVersion = Config->MajorOSVersion; PE->MinorSubsystemVersion = Config->MinorOSVersion; PE->Subsystem = Config->Subsystem; PE->SizeOfImage = SizeOfImage; PE->SizeOfHeaders = SizeOfHeaders; Defined *Entry = cast<Defined>(Symtab->find(Config->EntryName)); PE->AddressOfEntryPoint = Entry->getRVA(); PE->SizeOfStackReserve = Config->StackReserve; PE->SizeOfStackCommit = Config->StackCommit; PE->SizeOfHeapReserve = Config->HeapReserve; PE->SizeOfHeapCommit = Config->HeapCommit; PE->NumberOfRvaAndSize = NumberfOfDataDirectory; if (OutputSection *Text = findSection(".text")) { PE->BaseOfCode = Text->getRVA(); PE->SizeOfCode = Text->getRawSize(); } PE->SizeOfInitializedData = getSizeOfInitializedData(); // Write data directory auto *DataDirectory = reinterpret_cast<data_directory *>(Buf); Buf += sizeof(*DataDirectory) * NumberfOfDataDirectory; if (Idata) { DataDirectory[IMPORT_TABLE].RelativeVirtualAddress = Idata->getDirRVA(); DataDirectory[IMPORT_TABLE].Size = Idata->getDirSize(); DataDirectory[IAT].RelativeVirtualAddress = Idata->getIATRVA(); DataDirectory[IAT].Size = Idata->getIATSize(); } // Section table // Name field in the section table is 8 byte long. Longer names need // to be written to the string table. First, construct string table. std::vector<char> Strtab; for (OutputSection *Sec : OutputSections) { StringRef Name = Sec->getName(); if (Name.size() <= COFF::NameSize) continue; Sec->setStringTableOff(Strtab.size() + 4); // +4 for the size field Strtab.insert(Strtab.end(), Name.begin(), Name.end()); Strtab.push_back('\0'); } // Write section table for (OutputSection *Sec : OutputSections) { Sec->writeHeader(Buf); Buf += sizeof(coff_section); } // Write string table if we need to. The string table immediately // follows the symbol table, so we create a dummy symbol table // first. The symbol table contains one dummy symbol. if (Strtab.empty()) return; COFF->PointerToSymbolTable = Buf - Buffer->getBufferStart(); COFF->NumberOfSymbols = 1; auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(Buf); Buf += sizeof(*SymbolTable); // (Set 4 to make the dummy symbol point to the first string table // entry, so that tools to print out symbols don't read NUL bytes.) SymbolTable->Name.Offset.Offset = 4; // Then create the symbol table. The first 4 bytes is length // including itself. write32le(Buf, Strtab.size() + 4); memcpy(Buf + 4, Strtab.data(), Strtab.size()); } std::error_code Writer::openFile(StringRef Path) { if (auto EC = FileOutputBuffer::create(Path, FileSize, Buffer, FileOutputBuffer::F_executable)) { llvm::errs() << "failed to open " << Path << ": " << EC.message() << "\n"; return EC; } return std::error_code(); } // Write section contents to a mmap'ed file. void Writer::writeSections() { uint8_t *Buf = Buffer->getBufferStart(); for (OutputSection *Sec : OutputSections) { // Fill gaps between functions in .text with INT3 instructions // instead of leaving as NUL bytes (which can be interpreted as // ADD instructions). if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE) memset(Buf + Sec->getFileOff(), 0xCC, Sec->getRawSize()); for (Chunk *C : Sec->getChunks()) C->writeTo(Buf); } } OutputSection *Writer::findSection(StringRef Name) { for (OutputSection *Sec : OutputSections) if (Sec->getName() == Name) return Sec; return nullptr; } uint32_t Writer::getSizeOfInitializedData() { uint32_t Res = 0; for (OutputSection *S : OutputSections) if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA) Res += S->getRawSize(); return Res; } // Returns an existing section or create a new one if not found. OutputSection *Writer::createSection(StringRef Name) { if (auto *Sec = findSection(Name)) return Sec; const auto R = IMAGE_SCN_MEM_READ; const auto W = IMAGE_SCN_MEM_WRITE; const auto E = IMAGE_SCN_MEM_EXECUTE; uint32_t Perm = StringSwitch<uint32_t>(Name) .Case(".bss", IMAGE_SCN_CNT_UNINITIALIZED_DATA | R | W) .Case(".data", IMAGE_SCN_CNT_INITIALIZED_DATA | R | W) .Case(".idata", IMAGE_SCN_CNT_INITIALIZED_DATA | R) .Case(".rdata", IMAGE_SCN_CNT_INITIALIZED_DATA | R) .Case(".text", IMAGE_SCN_CNT_CODE | R | E) .Default(0); if (!Perm) llvm_unreachable("unknown section name"); size_t SectIdx = OutputSections.size(); auto Sec = new (CAlloc.Allocate()) OutputSection(Name, SectIdx); Sec->addPermissions(Perm); OutputSections.push_back(Sec); return Sec; } std::error_code Writer::write(StringRef OutputPath) { markLive(); createSections(); createImportTables(); assignAddresses(); removeEmptySections(); if (auto EC = openFile(OutputPath)) return EC; writeHeader(); writeSections(); return Buffer->commit(); } } // namespace coff } // namespace lld <commit_msg>COFF: Add .didat section.<commit_after>//===- Writer.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Config.h" #include "Writer.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstdio> #include <functional> #include <map> #include <utility> using namespace llvm; using namespace llvm::COFF; using namespace llvm::object; using namespace llvm::support; using namespace llvm::support::endian; static const int PageSize = 4096; static const int FileAlignment = 512; static const int SectionAlignment = 4096; static const int DOSStubSize = 64; static const int NumberfOfDataDirectory = 16; static const int HeaderSize = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) + sizeof(pe32plus_header) + sizeof(data_directory) * NumberfOfDataDirectory; namespace lld { namespace coff { void OutputSection::setRVA(uint64_t RVA) { Header.VirtualAddress = RVA; for (Chunk *C : Chunks) C->setRVA(C->getRVA() + RVA); } void OutputSection::setFileOffset(uint64_t Off) { // If a section has no actual data (i.e. BSS section), we want to // set 0 to its PointerToRawData. Otherwise the output is rejected // by the loader. if (Header.SizeOfRawData == 0) return; Header.PointerToRawData = Off; for (Chunk *C : Chunks) C->setFileOff(C->getFileOff() + Off); } void OutputSection::addChunk(Chunk *C) { Chunks.push_back(C); uint64_t Off = Header.VirtualSize; Off = RoundUpToAlignment(Off, C->getAlign()); C->setRVA(Off); C->setFileOff(Off); Off += C->getSize(); Header.VirtualSize = Off; if (C->hasData()) Header.SizeOfRawData = RoundUpToAlignment(Off, FileAlignment); } void OutputSection::addPermissions(uint32_t C) { Header.Characteristics = Header.Characteristics | (C & PermMask); } // Write the section header to a given buffer. void OutputSection::writeHeader(uint8_t *Buf) { auto *Hdr = reinterpret_cast<coff_section *>(Buf); *Hdr = Header; if (StringTableOff) { // If name is too long, write offset into the string table as a name. sprintf(Hdr->Name, "/%d", StringTableOff); } else { assert(Name.size() <= COFF::NameSize); strncpy(Hdr->Name, Name.data(), Name.size()); } } void Writer::markLive() { for (StringRef Name : Config->GCRoots) cast<Defined>(Symtab->find(Name))->markLive(); for (Chunk *C : Symtab->getChunks()) if (C->isRoot()) C->markLive(); } void Writer::createSections() { std::map<StringRef, std::vector<Chunk *>> Map; for (Chunk *C : Symtab->getChunks()) { if (!C->isLive()) { if (Config->Verbose) C->printDiscardedMessage(); continue; } // '$' and all following characters in input section names are // discarded when determining output section. So, .text$foo // contributes to .text, for example. See PE/COFF spec 3.2. Map[C->getSectionName().split('$').first].push_back(C); } // Input sections are ordered by their names including '$' parts, // which gives you some control over the output layout. auto Comp = [](Chunk *A, Chunk *B) { return A->getSectionName() < B->getSectionName(); }; for (auto &P : Map) { StringRef SectionName = P.first; std::vector<Chunk *> &Chunks = P.second; std::stable_sort(Chunks.begin(), Chunks.end(), Comp); size_t SectIdx = OutputSections.size(); auto Sec = new (CAlloc.Allocate()) OutputSection(SectionName, SectIdx); for (Chunk *C : Chunks) { C->setOutputSection(Sec); Sec->addChunk(C); Sec->addPermissions(C->getPermissions()); } OutputSections.push_back(Sec); } } // Create .idata section for the DLL-imported symbol table. // The format of this section is inherently Windows-specific. // IdataContents class abstracted away the details for us, // so we just let it create chunks and add them to the section. void Writer::createImportTables() { if (Symtab->ImportFiles.empty()) return; OutputSection *Text = createSection(".text"); Idata.reset(new IdataContents()); for (std::unique_ptr<ImportFile> &File : Symtab->ImportFiles) { for (SymbolBody *Body : File->getSymbols()) { if (auto *Import = dyn_cast<DefinedImportData>(Body)) { Idata->add(Import); continue; } // Linker-created function thunks for DLL symbols are added to // .text section. Text->addChunk(cast<DefinedImportThunk>(Body)->getChunk()); } } OutputSection *Sec = createSection(".idata"); for (Chunk *C : Idata->getChunks()) Sec->addChunk(C); } // The Windows loader doesn't seem to like empty sections, // so we remove them if any. void Writer::removeEmptySections() { auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; }; OutputSections.erase( std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty), OutputSections.end()); } // Visits all sections to assign incremental, non-overlapping RVAs and // file offsets. void Writer::assignAddresses() { SizeOfHeaders = RoundUpToAlignment( HeaderSize + sizeof(coff_section) * OutputSections.size(), PageSize); uint64_t RVA = 0x1000; // The first page is kept unmapped. uint64_t FileOff = SizeOfHeaders; for (OutputSection *Sec : OutputSections) { Sec->setRVA(RVA); Sec->setFileOffset(FileOff); RVA += RoundUpToAlignment(Sec->getVirtualSize(), PageSize); FileOff += RoundUpToAlignment(Sec->getRawSize(), FileAlignment); } SizeOfImage = SizeOfHeaders + RoundUpToAlignment(RVA - 0x1000, PageSize); FileSize = SizeOfHeaders + RoundUpToAlignment(FileOff - SizeOfHeaders, FileAlignment); } static MachineTypes inferMachineType(std::vector<std::unique_ptr<ObjectFile>> &ObjectFiles) { for (std::unique_ptr<ObjectFile> &File : ObjectFiles) { // Try to infer machine type from the magic byte of the object file. auto MT = static_cast<MachineTypes>(File->getCOFFObj()->getMachine()); if (MT != IMAGE_FILE_MACHINE_UNKNOWN) return MT; } return IMAGE_FILE_MACHINE_UNKNOWN; } void Writer::writeHeader() { // Write DOS stub uint8_t *Buf = Buffer->getBufferStart(); auto *DOS = reinterpret_cast<dos_header *>(Buf); Buf += DOSStubSize; DOS->Magic[0] = 'M'; DOS->Magic[1] = 'Z'; DOS->AddressOfRelocationTable = sizeof(dos_header); DOS->AddressOfNewExeHeader = DOSStubSize; // Write PE magic memcpy(Buf, PEMagic, sizeof(PEMagic)); Buf += sizeof(PEMagic); // Determine machine type, infer if needed. TODO: diagnose conflicts. MachineTypes MachineType = Config->MachineType; if (MachineType == IMAGE_FILE_MACHINE_UNKNOWN) MachineType = inferMachineType(Symtab->ObjectFiles); // Write COFF header auto *COFF = reinterpret_cast<coff_file_header *>(Buf); Buf += sizeof(*COFF); COFF->Machine = MachineType; COFF->NumberOfSections = OutputSections.size(); COFF->Characteristics = (IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_RELOCS_STRIPPED | IMAGE_FILE_LARGE_ADDRESS_AWARE); COFF->SizeOfOptionalHeader = sizeof(pe32plus_header) + sizeof(data_directory) * NumberfOfDataDirectory; // Write PE header auto *PE = reinterpret_cast<pe32plus_header *>(Buf); Buf += sizeof(*PE); PE->Magic = PE32Header::PE32_PLUS; PE->ImageBase = Config->ImageBase; PE->SectionAlignment = SectionAlignment; PE->FileAlignment = FileAlignment; PE->MajorImageVersion = Config->MajorImageVersion; PE->MinorImageVersion = Config->MinorImageVersion; PE->MajorOperatingSystemVersion = Config->MajorOSVersion; PE->MinorOperatingSystemVersion = Config->MinorOSVersion; PE->MajorSubsystemVersion = Config->MajorOSVersion; PE->MinorSubsystemVersion = Config->MinorOSVersion; PE->Subsystem = Config->Subsystem; PE->SizeOfImage = SizeOfImage; PE->SizeOfHeaders = SizeOfHeaders; Defined *Entry = cast<Defined>(Symtab->find(Config->EntryName)); PE->AddressOfEntryPoint = Entry->getRVA(); PE->SizeOfStackReserve = Config->StackReserve; PE->SizeOfStackCommit = Config->StackCommit; PE->SizeOfHeapReserve = Config->HeapReserve; PE->SizeOfHeapCommit = Config->HeapCommit; PE->NumberOfRvaAndSize = NumberfOfDataDirectory; if (OutputSection *Text = findSection(".text")) { PE->BaseOfCode = Text->getRVA(); PE->SizeOfCode = Text->getRawSize(); } PE->SizeOfInitializedData = getSizeOfInitializedData(); // Write data directory auto *DataDirectory = reinterpret_cast<data_directory *>(Buf); Buf += sizeof(*DataDirectory) * NumberfOfDataDirectory; if (Idata) { DataDirectory[IMPORT_TABLE].RelativeVirtualAddress = Idata->getDirRVA(); DataDirectory[IMPORT_TABLE].Size = Idata->getDirSize(); DataDirectory[IAT].RelativeVirtualAddress = Idata->getIATRVA(); DataDirectory[IAT].Size = Idata->getIATSize(); } // Section table // Name field in the section table is 8 byte long. Longer names need // to be written to the string table. First, construct string table. std::vector<char> Strtab; for (OutputSection *Sec : OutputSections) { StringRef Name = Sec->getName(); if (Name.size() <= COFF::NameSize) continue; Sec->setStringTableOff(Strtab.size() + 4); // +4 for the size field Strtab.insert(Strtab.end(), Name.begin(), Name.end()); Strtab.push_back('\0'); } // Write section table for (OutputSection *Sec : OutputSections) { Sec->writeHeader(Buf); Buf += sizeof(coff_section); } // Write string table if we need to. The string table immediately // follows the symbol table, so we create a dummy symbol table // first. The symbol table contains one dummy symbol. if (Strtab.empty()) return; COFF->PointerToSymbolTable = Buf - Buffer->getBufferStart(); COFF->NumberOfSymbols = 1; auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(Buf); Buf += sizeof(*SymbolTable); // (Set 4 to make the dummy symbol point to the first string table // entry, so that tools to print out symbols don't read NUL bytes.) SymbolTable->Name.Offset.Offset = 4; // Then create the symbol table. The first 4 bytes is length // including itself. write32le(Buf, Strtab.size() + 4); memcpy(Buf + 4, Strtab.data(), Strtab.size()); } std::error_code Writer::openFile(StringRef Path) { if (auto EC = FileOutputBuffer::create(Path, FileSize, Buffer, FileOutputBuffer::F_executable)) { llvm::errs() << "failed to open " << Path << ": " << EC.message() << "\n"; return EC; } return std::error_code(); } // Write section contents to a mmap'ed file. void Writer::writeSections() { uint8_t *Buf = Buffer->getBufferStart(); for (OutputSection *Sec : OutputSections) { // Fill gaps between functions in .text with INT3 instructions // instead of leaving as NUL bytes (which can be interpreted as // ADD instructions). if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE) memset(Buf + Sec->getFileOff(), 0xCC, Sec->getRawSize()); for (Chunk *C : Sec->getChunks()) C->writeTo(Buf); } } OutputSection *Writer::findSection(StringRef Name) { for (OutputSection *Sec : OutputSections) if (Sec->getName() == Name) return Sec; return nullptr; } uint32_t Writer::getSizeOfInitializedData() { uint32_t Res = 0; for (OutputSection *S : OutputSections) if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA) Res += S->getRawSize(); return Res; } // Returns an existing section or create a new one if not found. OutputSection *Writer::createSection(StringRef Name) { if (auto *Sec = findSection(Name)) return Sec; const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA; const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA; const auto CODE = IMAGE_SCN_CNT_CODE; const auto R = IMAGE_SCN_MEM_READ; const auto W = IMAGE_SCN_MEM_WRITE; const auto E = IMAGE_SCN_MEM_EXECUTE; uint32_t Perms = StringSwitch<uint32_t>(Name) .Case(".bss", BSS | R | W) .Case(".data", DATA | R | W) .Case(".didat", DATA | R) .Case(".idata", DATA | R) .Case(".rdata", DATA | R) .Case(".text", CODE | R | E) .Default(0); if (!Perms) llvm_unreachable("unknown section name"); size_t SectIdx = OutputSections.size(); auto Sec = new (CAlloc.Allocate()) OutputSection(Name, SectIdx); Sec->addPermissions(Perms); OutputSections.push_back(Sec); return Sec; } std::error_code Writer::write(StringRef OutputPath) { markLive(); createSections(); createImportTables(); assignAddresses(); removeEmptySections(); if (auto EC = openFile(OutputPath)) return EC; writeHeader(); writeSections(); return Buffer->commit(); } } // namespace coff } // namespace lld <|endoftext|>
<commit_before>/* Copyright (C) 2013 BMW Group * Author: Manfred Bathelt (manfred.bathelt@bmw.de) * Author: Juergen Gehring (juergen.gehring@bmw.de) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <dlfcn.h> #include <algorithm> #include <iostream> #include <unordered_map> #include <stdexcept> #include "Runtime.h" #include "Configuration.h" #include "utils.h" namespace CommonAPI { static std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>* registeredRuntimeLoadFunctions_; static bool isDynamic_ = false; static const char COMMONAPI_LIB_PREFIX[] = "libCommonAPI-"; static const char MIDDLEWARE_INFO_SYMBOL_NAME[] = "middlewareInfo"; inline bool Runtime::tryLoadLibrary(const std::string& libraryPath, void** sharedLibraryHandle, MiddlewareInfo** foundMiddlewareInfo) { //In case we find an already loaded library again while looking for another one, //there is no need to look at it if (dlopen(libraryPath.c_str(), RTLD_NOLOAD)) { return false; } //In order to place symbols of the newly loaded library ahead of already resolved symbols, we need //RTLD_DEEPBIND. This is necessary for this case: A library already is linked at compile time, but while //trying to resolve another library dynamically we might find the very same library again. //dlopen() doesn't know about the compile time linked library and will close it if dlclose() ever is //called, thereby causing memory corruptions. Therefore, we must be able to access the middlewareInfo //of the newly dlopened library in order to determine whether it already has been linked. auto flags = RTLD_LAZY | RTLD_LOCAL; #ifdef __linux__ flags |= RTLD_DEEPBIND; #endif *sharedLibraryHandle = dlopen(libraryPath.c_str(), flags); if (sharedLibraryHandle == NULL) { return false; } *foundMiddlewareInfo = static_cast<MiddlewareInfo*>(dlsym(*sharedLibraryHandle, MIDDLEWARE_INFO_SYMBOL_NAME)); //In this context, a resolved value of NULL it is just as invalid as if dlerror() was set additionally. if (!*foundMiddlewareInfo) { dlclose(*sharedLibraryHandle); return false; } if (!(*foundMiddlewareInfo)->middlewareName_ || !(*foundMiddlewareInfo)->getInstance_) { dlclose(sharedLibraryHandle); return false; } return true; } bool Runtime::checkAndLoadLibrary(const std::string& libraryPath, const std::string& requestedBindingIdentifier, bool keepLibrary) { void* sharedLibraryHandle = NULL; MiddlewareInfo* foundMiddlewareInfo; if (!tryLoadLibrary(libraryPath, &sharedLibraryHandle, &foundMiddlewareInfo)) { return false; } if (foundMiddlewareInfo->middlewareName_ != requestedBindingIdentifier) { //If library was linked at compile time (and therefore an appropriate runtime loader is registered), //the library must not be closed! auto foundRegisteredRuntimeLoader = registeredRuntimeLoadFunctions_->find(foundMiddlewareInfo->middlewareName_); if (foundRegisteredRuntimeLoader == registeredRuntimeLoadFunctions_->end()) { dlclose(sharedLibraryHandle); } return false; } if (!keepLibrary) { dlclose(sharedLibraryHandle); } else { //Extend visibility to make symbols available to all other libraries that are loaded afterwards, //e.g. libraries containing generated binding specific code. sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_GLOBAL); if (!sharedLibraryHandle) { return false; } registeredRuntimeLoadFunctions_->insert( {foundMiddlewareInfo->middlewareName_, foundMiddlewareInfo->getInstance_} ); } return true; } bool Runtime::checkAndLoadDefaultLibrary(std::string& foundBindingIdentifier, const std::string& libraryPath) { void* sharedLibraryHandle = NULL; MiddlewareInfo* foundMiddlewareInfo; if (!tryLoadLibrary(libraryPath, &sharedLibraryHandle, &foundMiddlewareInfo)) { return false; } //Extend visibility to make symbols available to all other linked libraries, //e.g. libraries containing generated binding specific code sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_GLOBAL); if (!sharedLibraryHandle) { return false; } registeredRuntimeLoadFunctions_->insert( {foundMiddlewareInfo->middlewareName_, foundMiddlewareInfo->getInstance_} ); foundBindingIdentifier = foundMiddlewareInfo->middlewareName_; return true; } const std::vector<std::string> Runtime::readDirectory(const std::string& path) { std::vector<std::string> result; struct stat filestat; DIR *directory = opendir(path.c_str()); if (!directory) { return std::vector<std::string>(); } struct dirent* entry; while ((entry = readdir(directory))) { const std::string fqnOfEntry = path + entry->d_name; if (stat(fqnOfEntry.c_str(), &filestat)) { continue; } if (S_ISDIR(filestat.st_mode)) { continue; } if (strncmp(COMMONAPI_LIB_PREFIX, entry->d_name, strlen(COMMONAPI_LIB_PREFIX)) != 0) { continue; } const char* fileNamePtr = entry->d_name; while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) { if (strncmp(".so", fileNamePtr, 3) == 0) { break; } } if (fileNamePtr) { result.push_back(fqnOfEntry); } } closedir (directory); std::sort( result.begin(), result.end() ); return result; } struct LibraryVersion { int32_t major; int32_t minor; int32_t revision; }; bool operator<(LibraryVersion const& lhs, LibraryVersion const& rhs) { if (lhs.major == rhs.major) { if (lhs.minor == rhs.minor) { return lhs.revision < rhs.revision; } return lhs.minor < rhs.minor; } return lhs.major < rhs.major; } std::shared_ptr<Runtime> Runtime::checkDynamicLibraries(const std::string& requestedMiddlewareName, LoadState& loadState) { const std::string& middlewareLibraryPath = Configuration::getInstance().getMiddlewareLibraryPath(requestedMiddlewareName); if (middlewareLibraryPath != "") { if (!checkAndLoadLibrary(middlewareLibraryPath, requestedMiddlewareName, true)) { //A path for requestedMiddlewareName was configured, but no corresponding library was found loadState = LoadState::CONFIGURATION_ERROR; return std::shared_ptr<Runtime>(NULL); } else { const std::string currentBinaryFQN = getCurrentBinaryFileFQN(); const uint32_t lastPathSeparatorPosition = currentBinaryFQN.find_last_of("/\\"); const std::string currentBinaryPath = currentBinaryFQN.substr(0, lastPathSeparatorPosition + 1); auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(requestedMiddlewareName); if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (foundRuntimeLoader->second)(); } //One should not get here loadState = LoadState::BINDING_ERROR; return std::shared_ptr<Runtime>(NULL); } } const std::vector<std::string>& librarySearchPaths = Configuration::getInstance().getLibrarySearchPaths(); LibraryVersion highestVersionFound = {0, 0, 0}; std::string fqnOfHighestVersion = ""; struct stat filestat; for (const std::string& singleSearchPath: librarySearchPaths) { std::vector<std::string> orderedLibraries = readDirectory(singleSearchPath); for (const std::string& fqnOfEntry : orderedLibraries) { std::string versionString; LibraryVersion currentLibraryVersion = {-1, -1, -1}; const char* fileNamePtr = fqnOfEntry.c_str(); while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) { if (strncmp(".so", fileNamePtr, 3) == 0) { break; } } const char* positionOfFirstDot = strchr(fileNamePtr + 1, '.'); if (positionOfFirstDot) { versionString = positionOfFirstDot + 1; } std::vector<std::string> versionElements = split(versionString, '.'); if (versionElements.size() >= 1 && containsOnlyDigits(versionElements[0])) { currentLibraryVersion.major = strtol(versionElements[0].c_str(), NULL, 0); } if (versionElements.size() >= 3 && containsOnlyDigits(versionElements[2])) { currentLibraryVersion.minor = strtol(versionElements[1].c_str(), NULL, 0); currentLibraryVersion.revision = strtol(versionElements[2].c_str(), NULL, 0); } if (highestVersionFound < currentLibraryVersion) { if (!checkAndLoadLibrary(fqnOfEntry, requestedMiddlewareName, false)) { continue; } highestVersionFound = currentLibraryVersion; fqnOfHighestVersion = fqnOfEntry; } } } if (fqnOfHighestVersion != "") { checkAndLoadLibrary(fqnOfHighestVersion, requestedMiddlewareName, true); auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(requestedMiddlewareName); if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { std::shared_ptr<Runtime> loadedRuntime = foundRuntimeLoader->second(); if (!loadedRuntime) { loadState = LoadState::BINDING_ERROR; } return loadedRuntime; } } loadState = LoadState::NO_LIBRARY_FOUND; return std::shared_ptr<Runtime>(); } std::shared_ptr<Runtime> Runtime::checkDynamicLibraries(LoadState& loadState) { const std::vector<std::string>& librarySearchPaths = Configuration::getInstance().getLibrarySearchPaths(); for (const std::string& singleSearchPath : librarySearchPaths) { std::vector<std::string> orderedLibraries = readDirectory(singleSearchPath); for (const std::string& fqnOfEntry: orderedLibraries) { std::string foundBindingName; if (!checkAndLoadDefaultLibrary(foundBindingName, fqnOfEntry)) { continue; } auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(foundBindingName); if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (foundRuntimeLoader->second)(); } } } loadState = LoadState::NO_LIBRARY_FOUND; return std::shared_ptr<Runtime>(); } void Runtime::registerRuntimeLoader(const std::string& middlewareName, const MiddlewareRuntimeLoadFunction& middlewareRuntimeLoadFunction) { if (!registeredRuntimeLoadFunctions_) { registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); } if (!isDynamic_) { registeredRuntimeLoadFunctions_->insert( {middlewareName, middlewareRuntimeLoadFunction}); } } std::shared_ptr<Runtime> Runtime::load() { LoadState dummyState; return load(dummyState); } std::shared_ptr<Runtime> Runtime::load(LoadState& loadState) { isDynamic_ = true; loadState = LoadState::SUCCESS; if(!registeredRuntimeLoadFunctions_) { registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); } const std::string& defaultBindingIdentifier = Configuration::getInstance().getDefaultMiddlewareIdentifier(); if (defaultBindingIdentifier != "") { const auto defaultRuntimeLoader = registeredRuntimeLoadFunctions_->find(defaultBindingIdentifier); if (defaultRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (defaultRuntimeLoader->second)(); } return checkDynamicLibraries(defaultBindingIdentifier, loadState); } else { const auto defaultRuntimeLoader = registeredRuntimeLoadFunctions_->begin(); if (defaultRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (defaultRuntimeLoader->second)(); } return checkDynamicLibraries(loadState); } } std::shared_ptr<Runtime> Runtime::load(const std::string& middlewareIdOrAlias) { LoadState dummyState; return load(middlewareIdOrAlias, dummyState); } std::shared_ptr<Runtime> Runtime::load(const std::string& middlewareIdOrAlias, LoadState& loadState) { isDynamic_ = true; loadState = LoadState::SUCCESS; if (!registeredRuntimeLoadFunctions_) { registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); } const std::string middlewareName = Configuration::getInstance().getMiddlewareNameForAlias(middlewareIdOrAlias); auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(middlewareName); if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (foundRuntimeLoader->second)(); } return checkDynamicLibraries(middlewareName, loadState); } std::shared_ptr<MainLoopContext> Runtime::getNewMainLoopContext() const { return std::make_shared<MainLoopContext>(); } std::shared_ptr<Factory> Runtime::createFactory(const std::string factoryName, const bool nullOnInvalidName) { return createFactory(std::shared_ptr<MainLoopContext>(NULL), factoryName, nullOnInvalidName); } std::shared_ptr<Factory> Runtime::createFactory(std::shared_ptr<MainLoopContext> mainLoopContext, const std::string factoryName, const bool nullOnInvalidName) { if(mainLoopContext && !mainLoopContext->isInitialized()) { return std::shared_ptr<Factory>(NULL); } return doCreateFactory(mainLoopContext, factoryName, nullOnInvalidName); } } // namespace CommonAPI <commit_msg>Revert MacOS compatiblity fix<commit_after>/* Copyright (C) 2013 BMW Group * Author: Manfred Bathelt (manfred.bathelt@bmw.de) * Author: Juergen Gehring (juergen.gehring@bmw.de) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <dlfcn.h> #include <algorithm> #include <iostream> #include <unordered_map> #include <stdexcept> #include "Runtime.h" #include "Configuration.h" #include "utils.h" namespace CommonAPI { static std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>* registeredRuntimeLoadFunctions_; static bool isDynamic_ = false; static const char COMMONAPI_LIB_PREFIX[] = "libCommonAPI-"; static const char MIDDLEWARE_INFO_SYMBOL_NAME[] = "middlewareInfo"; inline bool Runtime::tryLoadLibrary(const std::string& libraryPath, void** sharedLibraryHandle, MiddlewareInfo** foundMiddlewareInfo) { //In case we find an already loaded library again while looking for another one, //there is no need to look at it if (dlopen(libraryPath.c_str(), RTLD_NOLOAD)) { return false; } //In order to place symbols of the newly loaded library ahead of already resolved symbols, we need //RTLD_DEEPBIND. This is necessary for this case: A library already is linked at compile time, but while //trying to resolve another library dynamically we might find the very same library again. //dlopen() doesn't know about the compile time linked library and will close it if dlclose() ever is //called, thereby causing memory corruptions. Therefore, we must be able to access the middlewareInfo //of the newly dlopened library in order to determine whether it already has been linked. *sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND); if (sharedLibraryHandle == NULL) { return false; } *foundMiddlewareInfo = static_cast<MiddlewareInfo*>(dlsym(*sharedLibraryHandle, MIDDLEWARE_INFO_SYMBOL_NAME)); //In this context, a resolved value of NULL it is just as invalid as if dlerror() was set additionally. if (!*foundMiddlewareInfo) { dlclose(*sharedLibraryHandle); return false; } if (!(*foundMiddlewareInfo)->middlewareName_ || !(*foundMiddlewareInfo)->getInstance_) { dlclose(sharedLibraryHandle); return false; } return true; } bool Runtime::checkAndLoadLibrary(const std::string& libraryPath, const std::string& requestedBindingIdentifier, bool keepLibrary) { void* sharedLibraryHandle = NULL; MiddlewareInfo* foundMiddlewareInfo; if (!tryLoadLibrary(libraryPath, &sharedLibraryHandle, &foundMiddlewareInfo)) { return false; } if (foundMiddlewareInfo->middlewareName_ != requestedBindingIdentifier) { //If library was linked at compile time (and therefore an appropriate runtime loader is registered), //the library must not be closed! auto foundRegisteredRuntimeLoader = registeredRuntimeLoadFunctions_->find(foundMiddlewareInfo->middlewareName_); if (foundRegisteredRuntimeLoader == registeredRuntimeLoadFunctions_->end()) { dlclose(sharedLibraryHandle); } return false; } if (!keepLibrary) { dlclose(sharedLibraryHandle); } else { //Extend visibility to make symbols available to all other libraries that are loaded afterwards, //e.g. libraries containing generated binding specific code. sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_GLOBAL); if (!sharedLibraryHandle) { return false; } registeredRuntimeLoadFunctions_->insert( {foundMiddlewareInfo->middlewareName_, foundMiddlewareInfo->getInstance_} ); } return true; } bool Runtime::checkAndLoadDefaultLibrary(std::string& foundBindingIdentifier, const std::string& libraryPath) { void* sharedLibraryHandle = NULL; MiddlewareInfo* foundMiddlewareInfo; if (!tryLoadLibrary(libraryPath, &sharedLibraryHandle, &foundMiddlewareInfo)) { return false; } //Extend visibility to make symbols available to all other linked libraries, //e.g. libraries containing generated binding specific code sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_GLOBAL); if (!sharedLibraryHandle) { return false; } registeredRuntimeLoadFunctions_->insert( {foundMiddlewareInfo->middlewareName_, foundMiddlewareInfo->getInstance_} ); foundBindingIdentifier = foundMiddlewareInfo->middlewareName_; return true; } const std::vector<std::string> Runtime::readDirectory(const std::string& path) { std::vector<std::string> result; struct stat filestat; DIR *directory = opendir(path.c_str()); if (!directory) { return std::vector<std::string>(); } struct dirent* entry; while ((entry = readdir(directory))) { const std::string fqnOfEntry = path + entry->d_name; if (stat(fqnOfEntry.c_str(), &filestat)) { continue; } if (S_ISDIR(filestat.st_mode)) { continue; } if (strncmp(COMMONAPI_LIB_PREFIX, entry->d_name, strlen(COMMONAPI_LIB_PREFIX)) != 0) { continue; } const char* fileNamePtr = entry->d_name; while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) { if (strncmp(".so", fileNamePtr, 3) == 0) { break; } } if (fileNamePtr) { result.push_back(fqnOfEntry); } } closedir (directory); std::sort( result.begin(), result.end() ); return result; } struct LibraryVersion { int32_t major; int32_t minor; int32_t revision; }; bool operator<(LibraryVersion const& lhs, LibraryVersion const& rhs) { if (lhs.major == rhs.major) { if (lhs.minor == rhs.minor) { return lhs.revision < rhs.revision; } return lhs.minor < rhs.minor; } return lhs.major < rhs.major; } std::shared_ptr<Runtime> Runtime::checkDynamicLibraries(const std::string& requestedMiddlewareName, LoadState& loadState) { const std::string& middlewareLibraryPath = Configuration::getInstance().getMiddlewareLibraryPath(requestedMiddlewareName); if (middlewareLibraryPath != "") { if (!checkAndLoadLibrary(middlewareLibraryPath, requestedMiddlewareName, true)) { //A path for requestedMiddlewareName was configured, but no corresponding library was found loadState = LoadState::CONFIGURATION_ERROR; return std::shared_ptr<Runtime>(NULL); } else { const std::string currentBinaryFQN = getCurrentBinaryFileFQN(); const uint32_t lastPathSeparatorPosition = currentBinaryFQN.find_last_of("/\\"); const std::string currentBinaryPath = currentBinaryFQN.substr(0, lastPathSeparatorPosition + 1); auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(requestedMiddlewareName); if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (foundRuntimeLoader->second)(); } //One should not get here loadState = LoadState::BINDING_ERROR; return std::shared_ptr<Runtime>(NULL); } } const std::vector<std::string>& librarySearchPaths = Configuration::getInstance().getLibrarySearchPaths(); LibraryVersion highestVersionFound = {0, 0, 0}; std::string fqnOfHighestVersion = ""; struct stat filestat; for (const std::string& singleSearchPath: librarySearchPaths) { std::vector<std::string> orderedLibraries = readDirectory(singleSearchPath); for (const std::string& fqnOfEntry : orderedLibraries) { std::string versionString; LibraryVersion currentLibraryVersion = {-1, -1, -1}; const char* fileNamePtr = fqnOfEntry.c_str(); while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) { if (strncmp(".so", fileNamePtr, 3) == 0) { break; } } const char* positionOfFirstDot = strchr(fileNamePtr + 1, '.'); if (positionOfFirstDot) { versionString = positionOfFirstDot + 1; } std::vector<std::string> versionElements = split(versionString, '.'); if (versionElements.size() >= 1 && containsOnlyDigits(versionElements[0])) { currentLibraryVersion.major = strtol(versionElements[0].c_str(), NULL, 0); } if (versionElements.size() >= 3 && containsOnlyDigits(versionElements[2])) { currentLibraryVersion.minor = strtol(versionElements[1].c_str(), NULL, 0); currentLibraryVersion.revision = strtol(versionElements[2].c_str(), NULL, 0); } if (highestVersionFound < currentLibraryVersion) { if (!checkAndLoadLibrary(fqnOfEntry, requestedMiddlewareName, false)) { continue; } highestVersionFound = currentLibraryVersion; fqnOfHighestVersion = fqnOfEntry; } } } if (fqnOfHighestVersion != "") { checkAndLoadLibrary(fqnOfHighestVersion, requestedMiddlewareName, true); auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(requestedMiddlewareName); if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { std::shared_ptr<Runtime> loadedRuntime = foundRuntimeLoader->second(); if (!loadedRuntime) { loadState = LoadState::BINDING_ERROR; } return loadedRuntime; } } loadState = LoadState::NO_LIBRARY_FOUND; return std::shared_ptr<Runtime>(); } std::shared_ptr<Runtime> Runtime::checkDynamicLibraries(LoadState& loadState) { const std::vector<std::string>& librarySearchPaths = Configuration::getInstance().getLibrarySearchPaths(); for (const std::string& singleSearchPath : librarySearchPaths) { std::vector<std::string> orderedLibraries = readDirectory(singleSearchPath); for (const std::string& fqnOfEntry: orderedLibraries) { std::string foundBindingName; if (!checkAndLoadDefaultLibrary(foundBindingName, fqnOfEntry)) { continue; } auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(foundBindingName); if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (foundRuntimeLoader->second)(); } } } loadState = LoadState::NO_LIBRARY_FOUND; return std::shared_ptr<Runtime>(); } void Runtime::registerRuntimeLoader(const std::string& middlewareName, const MiddlewareRuntimeLoadFunction& middlewareRuntimeLoadFunction) { if (!registeredRuntimeLoadFunctions_) { registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); } if (!isDynamic_) { registeredRuntimeLoadFunctions_->insert( {middlewareName, middlewareRuntimeLoadFunction}); } } std::shared_ptr<Runtime> Runtime::load() { LoadState dummyState; return load(dummyState); } std::shared_ptr<Runtime> Runtime::load(LoadState& loadState) { isDynamic_ = true; loadState = LoadState::SUCCESS; if(!registeredRuntimeLoadFunctions_) { registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); } const std::string& defaultBindingIdentifier = Configuration::getInstance().getDefaultMiddlewareIdentifier(); if (defaultBindingIdentifier != "") { const auto defaultRuntimeLoader = registeredRuntimeLoadFunctions_->find(defaultBindingIdentifier); if (defaultRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (defaultRuntimeLoader->second)(); } return checkDynamicLibraries(defaultBindingIdentifier, loadState); } else { const auto defaultRuntimeLoader = registeredRuntimeLoadFunctions_->begin(); if (defaultRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (defaultRuntimeLoader->second)(); } return checkDynamicLibraries(loadState); } } std::shared_ptr<Runtime> Runtime::load(const std::string& middlewareIdOrAlias) { LoadState dummyState; return load(middlewareIdOrAlias, dummyState); } std::shared_ptr<Runtime> Runtime::load(const std::string& middlewareIdOrAlias, LoadState& loadState) { isDynamic_ = true; loadState = LoadState::SUCCESS; if (!registeredRuntimeLoadFunctions_) { registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); } const std::string middlewareName = Configuration::getInstance().getMiddlewareNameForAlias(middlewareIdOrAlias); auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(middlewareName); if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { return (foundRuntimeLoader->second)(); } return checkDynamicLibraries(middlewareName, loadState); } std::shared_ptr<MainLoopContext> Runtime::getNewMainLoopContext() const { return std::make_shared<MainLoopContext>(); } std::shared_ptr<Factory> Runtime::createFactory(const std::string factoryName, const bool nullOnInvalidName) { return createFactory(std::shared_ptr<MainLoopContext>(NULL), factoryName, nullOnInvalidName); } std::shared_ptr<Factory> Runtime::createFactory(std::shared_ptr<MainLoopContext> mainLoopContext, const std::string factoryName, const bool nullOnInvalidName) { if(mainLoopContext && !mainLoopContext->isInitialized()) { return std::shared_ptr<Factory>(NULL); } return doCreateFactory(mainLoopContext, factoryName, nullOnInvalidName); } } // namespace CommonAPI <|endoftext|>
<commit_before>#include "Util/Log.hpp" #include "MainWindow.hpp" #include "Manager/Managers.hpp" #include "Manager/RenderManager.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> MainWindow* MainWindow::instance = nullptr; void WindowSizeCallback(GLFWwindow* window, int width, int height); MainWindow::MainWindow(int width, int height, bool fullscreen, bool borderless, const char* title, bool debugContext) { glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); if (borderless) glfwWindowHint(GLFW_DECORATED, GL_FALSE); this->debugContext = debugContext; if (debugContext) glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); GLFWmonitor* monitor = fullscreen ? glfwGetPrimaryMonitor() : nullptr; window = glfwCreateWindow(width, height, title, monitor, nullptr); if (!window) { glfwTerminate(); /// @todo Print error to log. } glfwMakeContextCurrent(window); // Setup error callbacks. glfwSetErrorCallback(ErrorCallback); input = new InputHandler(window); input->Update(); input->SetActive(); size = glm::vec2(width, height); instance = this; glfwSetWindowSizeCallback(window, WindowSizeCallback); } MainWindow::~MainWindow() { glfwDestroyWindow(window); delete input; } MainWindow* MainWindow::GetInstance() { return instance; } void MainWindow::Init(bool showNotifications) { glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_PROGRAM_POINT_SIZE); if (debugContext) glDebugMessageCallback(showNotifications ? DebugMessageCallback : DebugMessageCallbackIgnoreNotifications, nullptr); } void MainWindow::SetVsync(bool vsync) { glfwSwapInterval(vsync ? 1 : 0); } void MainWindow::Update() { input->Update(); input->SetActive(); if (glfwWindowShouldClose(window) != GL_FALSE) shouldClose = true; } const glm::vec2& MainWindow::GetSize() const { return size; } void MainWindow::SetSize(int width, int height){ size.x = width; size.y = height; } void MainWindow::SetTitle(const char *title) { glfwSetWindowTitle(window, title); } bool MainWindow::ShouldClose() const { return shouldClose; } void MainWindow::Close() { shouldClose = true; } void MainWindow::SwapBuffers() { glfwSwapBuffers(window); } GLFWwindow* MainWindow::GetGLFWWindow() const { return window; } void WindowSizeCallback(GLFWwindow* window, int width, int height) { MainWindow::GetInstance()->SetSize(width, height); Managers().renderManager->UpdateBufferSize(); } <commit_msg>Removed unnecessary windowHint<commit_after>#include "Util/Log.hpp" #include "MainWindow.hpp" #include "Manager/Managers.hpp" #include "Manager/RenderManager.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> MainWindow* MainWindow::instance = nullptr; void WindowSizeCallback(GLFWwindow* window, int width, int height); MainWindow::MainWindow(int width, int height, bool fullscreen, bool borderless, const char* title, bool debugContext) { if (borderless) glfwWindowHint(GLFW_DECORATED, GL_FALSE); this->debugContext = debugContext; if (debugContext) glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); GLFWmonitor* monitor = fullscreen ? glfwGetPrimaryMonitor() : nullptr; window = glfwCreateWindow(width, height, title, monitor, nullptr); if (!window) { glfwTerminate(); /// @todo Print error to log. } glfwMakeContextCurrent(window); // Setup error callbacks. glfwSetErrorCallback(ErrorCallback); input = new InputHandler(window); input->Update(); input->SetActive(); size = glm::vec2(width, height); instance = this; glfwSetWindowSizeCallback(window, WindowSizeCallback); } MainWindow::~MainWindow() { glfwDestroyWindow(window); delete input; } MainWindow* MainWindow::GetInstance() { return instance; } void MainWindow::Init(bool showNotifications) { glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_PROGRAM_POINT_SIZE); if (debugContext) glDebugMessageCallback(showNotifications ? DebugMessageCallback : DebugMessageCallbackIgnoreNotifications, nullptr); } void MainWindow::SetVsync(bool vsync) { glfwSwapInterval(vsync ? 1 : 0); } void MainWindow::Update() { input->Update(); input->SetActive(); if (glfwWindowShouldClose(window) != GL_FALSE) shouldClose = true; } const glm::vec2& MainWindow::GetSize() const { return size; } void MainWindow::SetSize(int width, int height){ size.x = width; size.y = height; } void MainWindow::SetTitle(const char *title) { glfwSetWindowTitle(window, title); } bool MainWindow::ShouldClose() const { return shouldClose; } void MainWindow::Close() { shouldClose = true; } void MainWindow::SwapBuffers() { glfwSwapBuffers(window); } GLFWwindow* MainWindow::GetGLFWWindow() const { return window; } void WindowSizeCallback(GLFWwindow* window, int width, int height) { MainWindow::GetInstance()->SetSize(width, height); Managers().renderManager->UpdateBufferSize(); } <|endoftext|>
<commit_before>// Framework-specific I2C methods, for Arduino and Particle devices #if defined(ARDUINO) || defined(SPARK) #ifdef ARDUINO #include "Arduino.h" #include <Wire.h> #endif #ifdef SPARK #include "application.h" #endif #include "I2CDevice.h" int8_t I2CDevice::readBytes(uint8_t regAddr, uint8_t length, uint8_t *data) { uint8_t count = 0; // Select the slave address and register to read from Wire.beginTransmission(address); Wire.write(regAddr); Wire.endTransmission(); // Request length bytes of data Wire.requestFrom(address, length); while(Wire.available()) { data[count] = Wire.read(); count++; } return count; } int8_t I2CDevice::readWords(uint8_t regAddr, uint8_t length, uint16_t *data) { uint8_t count = 0; // Select the slave address and register to read from Wire.beginTransmission(address); Wire.write(regAddr); Wire.endTransmission(); // Request length*2 bytes of data Wire.requestFrom(address, length * 2); bool msb = true; while(Wire.available()) { // Combine bytes into words if (msb) { data[count] = Wire.read() << 8; } else { data[count] |= Wire.read(); count++; } msb = !msb; } return count; } bool I2CDevice::writeBytes(uint8_t regAddr, uint8_t length, uint8_t *data) { // Select the slave address and register to write to Wire.beginTransmission(address); Wire.write(regAddr); // Write the data Wire.write(data, length); // Finish transmission and return the status return (Wire.endTransmission() == 0); } bool I2CDevice::writeWords(uint8_t regAddr, uint8_t length, uint16_t *data) { // Select the slave address and register to write to Wire.beginTransmission(address); Wire.write(regAddr); // Write the data for (uint8_t i = 0; i < length * 2; i++) { Wire.write((uint8_t)(data[i] >> 8)); Wire.write((uint8_t)data[i++]); } // Finish transmission and return the status return (Wire.endTransmission() == 0); } void I2CDevice::usleep(unsigned int us) { delayMicroseconds(us); } #endif // defined(ARDUINO) || defined(SPARK) <commit_msg>Fix ambiguous requestFrom call<commit_after>// Framework-specific I2C methods, for Arduino and Particle devices #if defined(ARDUINO) || defined(SPARK) #ifdef ARDUINO #include "Arduino.h" #include <Wire.h> #endif #ifdef SPARK #include "application.h" #endif #include "I2CDevice.h" int8_t I2CDevice::readBytes(uint8_t regAddr, uint8_t length, uint8_t *data) { uint8_t count = 0; // Select the slave address and register to read from Wire.beginTransmission(address); Wire.write(regAddr); Wire.endTransmission(); // Request length bytes of data Wire.requestFrom(address, length); while(Wire.available()) { data[count] = Wire.read(); count++; } return count; } int8_t I2CDevice::readWords(uint8_t regAddr, uint8_t length, uint16_t *data) { uint8_t count = 0; // Select the slave address and register to read from Wire.beginTransmission(address); Wire.write(regAddr); Wire.endTransmission(); // Request length*2 bytes of data Wire.requestFrom(address, (uint8_t)(length * 2)); bool msb = true; while(Wire.available()) { // Combine bytes into words if (msb) { data[count] = Wire.read() << 8; } else { data[count] |= Wire.read(); count++; } msb = !msb; } return count; } bool I2CDevice::writeBytes(uint8_t regAddr, uint8_t length, uint8_t *data) { // Select the slave address and register to write to Wire.beginTransmission(address); Wire.write(regAddr); // Write the data Wire.write(data, length); // Finish transmission and return the status return (Wire.endTransmission() == 0); } bool I2CDevice::writeWords(uint8_t regAddr, uint8_t length, uint16_t *data) { // Select the slave address and register to write to Wire.beginTransmission(address); Wire.write(regAddr); // Write the data for (uint8_t i = 0; i < length * 2; i++) { Wire.write((uint8_t)(data[i] >> 8)); Wire.write((uint8_t)data[i++]); } // Finish transmission and return the status return (Wire.endTransmission() == 0); } void I2CDevice::usleep(unsigned int us) { delayMicroseconds(us); } #endif // defined(ARDUINO) || defined(SPARK) <|endoftext|>
<commit_before>#include <cstdlib> #include <sstream> #include <iostream> #include <algorithm> #include <functional> #ifdef ENABLE_MPI #include <mpi.h> #endif #include "Tools/date.h" #include "Tools/general_utils.h" #include "Tools/Display/bash_tools.h" #include "Tools/Exception/exception.hpp" #include "Tools/system_functions.hpp" #include "Factory/Module/Source/Source.hpp" #include "Factory/Module/CRC/CRC.hpp" #include "Factory/Module/Encoder/Encoder.hpp" #include "Factory/Module/Puncturer/Puncturer.hpp" #include "Factory/Module/Interleaver/Interleaver.hpp" #include "Factory/Module/Modem/Modem.hpp" #include "Factory/Module/Channel/Channel.hpp" #include "Factory/Module/Quantizer/Quantizer.hpp" #include "Factory/Module/Decoder/Decoder.hpp" #include "Factory/Module/Monitor/Monitor.hpp" #include "Factory/Tools/Display/Terminal/Terminal.hpp" #include "Launcher.hpp" using namespace aff3ct; using namespace aff3ct::launcher; Launcher::Launcher(const int argc, const char **argv, factory::Simulation::parameters &params, std::ostream &stream) : simu(nullptr), ar(argc, argv), params(params), stream(stream) { cmd_line += std::string(argv[0]) + std::string(" "); for (auto i = 1; i < argc; i++) { if (argv[i][0] == '-') cmd_line += std::string(argv[i]); else cmd_line += std::string("\"") + std::string(argv[i]) + std::string("\""); cmd_line += std::string(" "); } } Launcher::~Launcher() { } void Launcher::get_description_args() { } void Launcher::store_args() { } int Launcher::read_arguments() { this->get_description_args(); std::vector<std::string> cmd_error; bool miss_arg = !ar.parse_arguments(req_args, opt_args, cmd_warn); bool error = !ar.check_arguments(cmd_error); this->store_args(); if (params.display_help) { auto grps = factory::Factory::create_groups({&params}); ar.print_usage(grps); error = true; // in order to exit at the end of this function } // print the errors for (unsigned e = 0; e < cmd_error.size(); e++) std::cerr << tools::format_error(cmd_error[e]) << std::endl; if (miss_arg) std::cerr << tools::format_error("At least one required argument is missing.") << std::endl; // print the help tags if ((miss_arg || error) && !params.display_help) { std::string message = "For more information please display the help ("; std::vector<std::string> help_tag = {"help", "h"}; for (unsigned i = 0; i < help_tag.size(); i++) message += tools::Arguments_reader::print_tag(help_tag[i]) + ((i < help_tag.size()-1)?", ":""); message += ")."; std::cerr << tools::format_info(message) << std::endl; } return ((miss_arg || error) ? EXIT_FAILURE : EXIT_SUCCESS); } void Launcher::print_header() { // display configuration and simulation parameters stream << "# " << tools::style("-------------------------------------------------", tools::Style::BOLD) << std::endl; stream << "# " << tools::style("---- A FAST FORWARD ERROR CORRECTION TOOL >> ----", tools::Style::BOLD) << std::endl; stream << "# " << tools::style("-------------------------------------------------", tools::Style::BOLD) << std::endl; stream << "# " << tools::style(style("Parameters :", tools::Style::BOLD), tools::Style::UNDERLINED) << std::endl; factory::Header::print_parameters({&params}, false, this->stream); this->stream << "#" << std::endl; } void Launcher::launch() { std::srand(this->params.global_seed); // in case of the user call launch multiple times if (simu != nullptr) { delete simu; simu = nullptr; } if (this->read_arguments() == EXIT_FAILURE) { // print the warnings #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif for (unsigned w = 0; w < cmd_warn.size(); w++) std::clog << tools::format_warning(cmd_warn[w]) << std::endl; return; } // write the command and he curve name in the PyBER format #ifdef ENABLE_MPI if (!this->params.pyber.empty() && this->params.mpi_rank == 0) #else if (!this->params.pyber.empty()) #endif { stream << "Run command:" << std::endl; stream << cmd_line << std::endl; stream << "Curve name:" << std::endl; stream << this->params.pyber << std::endl; } #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif this->print_header(); // print the warnings #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif for (unsigned w = 0; w < cmd_warn.size(); w++) std::clog << tools::format_warning(cmd_warn[w]) << std::endl; try { simu = this->build_simu(); } catch (std::exception const& e) { std::cerr << tools::apply_on_each_line(e.what(), &tools::format_error) << std::endl; } if (simu != nullptr) { // launch the simulation #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif stream << "# " << "The simulation is running..." << std::endl; try { simu->launch(); } catch (std::exception const& e) { std::cerr << tools::apply_on_each_line(tools::addr2line(e.what()), &tools::format_error) << std::endl; } } #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif stream << "# End of the simulation." << std::endl; if (simu != nullptr) { delete simu; simu = nullptr; } } <commit_msg>Add a catch where to apply the addr2line function<commit_after>#include <cstdlib> #include <sstream> #include <iostream> #include <algorithm> #include <functional> #ifdef ENABLE_MPI #include <mpi.h> #endif #include "Tools/date.h" #include "Tools/general_utils.h" #include "Tools/Display/bash_tools.h" #include "Tools/Exception/exception.hpp" #include "Tools/system_functions.hpp" #include "Factory/Module/Source/Source.hpp" #include "Factory/Module/CRC/CRC.hpp" #include "Factory/Module/Encoder/Encoder.hpp" #include "Factory/Module/Puncturer/Puncturer.hpp" #include "Factory/Module/Interleaver/Interleaver.hpp" #include "Factory/Module/Modem/Modem.hpp" #include "Factory/Module/Channel/Channel.hpp" #include "Factory/Module/Quantizer/Quantizer.hpp" #include "Factory/Module/Decoder/Decoder.hpp" #include "Factory/Module/Monitor/Monitor.hpp" #include "Factory/Tools/Display/Terminal/Terminal.hpp" #include "Launcher.hpp" using namespace aff3ct; using namespace aff3ct::launcher; Launcher::Launcher(const int argc, const char **argv, factory::Simulation::parameters &params, std::ostream &stream) : simu(nullptr), ar(argc, argv), params(params), stream(stream) { cmd_line += std::string(argv[0]) + std::string(" "); for (auto i = 1; i < argc; i++) { if (argv[i][0] == '-') cmd_line += std::string(argv[i]); else cmd_line += std::string("\"") + std::string(argv[i]) + std::string("\""); cmd_line += std::string(" "); } } Launcher::~Launcher() { } void Launcher::get_description_args() { } void Launcher::store_args() { } int Launcher::read_arguments() { this->get_description_args(); std::vector<std::string> cmd_error; bool miss_arg = !ar.parse_arguments(req_args, opt_args, cmd_warn); bool error = !ar.check_arguments(cmd_error); this->store_args(); if (params.display_help) { auto grps = factory::Factory::create_groups({&params}); ar.print_usage(grps); error = true; // in order to exit at the end of this function } // print the errors for (unsigned e = 0; e < cmd_error.size(); e++) std::cerr << tools::format_error(cmd_error[e]) << std::endl; if (miss_arg) std::cerr << tools::format_error("At least one required argument is missing.") << std::endl; // print the help tags if ((miss_arg || error) && !params.display_help) { std::string message = "For more information please display the help ("; std::vector<std::string> help_tag = {"help", "h"}; for (unsigned i = 0; i < help_tag.size(); i++) message += tools::Arguments_reader::print_tag(help_tag[i]) + ((i < help_tag.size()-1)?", ":""); message += ")."; std::cerr << tools::format_info(message) << std::endl; } return ((miss_arg || error) ? EXIT_FAILURE : EXIT_SUCCESS); } void Launcher::print_header() { // display configuration and simulation parameters stream << "# " << tools::style("-------------------------------------------------", tools::Style::BOLD) << std::endl; stream << "# " << tools::style("---- A FAST FORWARD ERROR CORRECTION TOOL >> ----", tools::Style::BOLD) << std::endl; stream << "# " << tools::style("-------------------------------------------------", tools::Style::BOLD) << std::endl; stream << "# " << tools::style(style("Parameters :", tools::Style::BOLD), tools::Style::UNDERLINED) << std::endl; factory::Header::print_parameters({&params}, false, this->stream); this->stream << "#" << std::endl; } void Launcher::launch() { std::srand(this->params.global_seed); // in case of the user call launch multiple times if (simu != nullptr) { delete simu; simu = nullptr; } if (this->read_arguments() == EXIT_FAILURE) { // print the warnings #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif for (unsigned w = 0; w < cmd_warn.size(); w++) std::clog << tools::format_warning(cmd_warn[w]) << std::endl; return; } // write the command and he curve name in the PyBER format #ifdef ENABLE_MPI if (!this->params.pyber.empty() && this->params.mpi_rank == 0) #else if (!this->params.pyber.empty()) #endif { stream << "Run command:" << std::endl; stream << cmd_line << std::endl; stream << "Curve name:" << std::endl; stream << this->params.pyber << std::endl; } #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif this->print_header(); // print the warnings #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif for (unsigned w = 0; w < cmd_warn.size(); w++) std::clog << tools::format_warning(cmd_warn[w]) << std::endl; try { simu = this->build_simu(); } catch (std::exception const& e) { std::cerr << tools::apply_on_each_line(tools::addr2line(e.what()), &tools::format_error) << std::endl; } if (simu != nullptr) { // launch the simulation #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif stream << "# " << "The simulation is running..." << std::endl; try { simu->launch(); } catch (std::exception const& e) { std::cerr << tools::apply_on_each_line(tools::addr2line(e.what()), &tools::format_error) << std::endl; } } #ifdef ENABLE_MPI if (this->params.mpi_rank == 0) #endif stream << "# End of the simulation." << std::endl; if (simu != nullptr) { delete simu; simu = nullptr; } } <|endoftext|>
<commit_before>#include "LouvainSimplifier.h" #include <Graph.h> #include <Louvain.h> #include <iostream> using namespace std; LouvainSimplifier::LouvainSimplifier(int _max_levels) : max_levels(_max_levels) { keepHashtags(true); keepLinks(false); } bool LouvainSimplifier::apply(Graph & target_graph, time_t start_time, time_t end_time, float start_sentiment, float end_sentiment, Graph & source_graph, RawStatistics & stats) { bool is_changed = processTemporalData(target_graph, start_time, end_time, start_sentiment, end_sentiment, source_graph, stats); if (is_changed) { target_graph.removeAllChildren(); double precision = 0.000001; cerr << "doing Louvain\n"; Louvain c(&target_graph, -1, precision); cerr << "Louvain created\n"; double mod = target_graph.modularity(); int level = 0; bool is_improved = true; cerr << "initial modularity = " << mod << endl; for (int level = 1; level <= max_levels && is_improved; level++) { is_improved = c.oneLevel(); double new_mod = target_graph.modularity(); cerr << "l " << level << ": modularity increase: " << mod << " to " << new_mod << endl; mod = new_mod; for (auto cluster_id : c.getClusterIds()) { auto & td = target_graph.getNodeTertiaryData(cluster_id); assert(td.parent_node == -1); float best_d = 0; int best_node = -1; for (int n = td.first_child; n != -1; ) { auto & ctd = target_graph.getNodeTertiaryData(n); if (ctd.group_leader != -1) { auto & ctd2 = target_graph.getNodeTertiaryData(ctd.group_leader); if (best_node == -1 || ctd2.weighted_indegree > best_d) { best_node = ctd.group_leader; best_d = ctd2.weighted_indegree; } } else if (best_node == -1 || ctd.weighted_indegree > best_d) { best_node = n; best_d = ctd.weighted_indegree; } n = ctd.next_child; } target_graph.setGroupLeader(cluster_id, best_node); } } } return is_changed; } <commit_msg>keep links, don't pick urls or attributes as representative nodes<commit_after>#include "LouvainSimplifier.h" #include <Graph.h> #include <Louvain.h> #include <iostream> using namespace std; LouvainSimplifier::LouvainSimplifier(int _max_levels) : max_levels(_max_levels) { keepHashtags(true); keepLinks(true); } bool LouvainSimplifier::apply(Graph & target_graph, time_t start_time, time_t end_time, float start_sentiment, float end_sentiment, Graph & source_graph, RawStatistics & stats) { bool is_changed = processTemporalData(target_graph, start_time, end_time, start_sentiment, end_sentiment, source_graph, stats); if (is_changed) { target_graph.removeAllChildren(); double precision = 0.000001; cerr << "doing Louvain\n"; Louvain c(&target_graph, -1, precision); cerr << "Louvain created\n"; double mod = target_graph.modularity(); int level = 0; bool is_improved = true; cerr << "initial modularity = " << mod << endl; for (int level = 1; level <= max_levels && is_improved; level++) { is_improved = c.oneLevel(); double new_mod = target_graph.modularity(); cerr << "l " << level << ": modularity increase: " << mod << " to " << new_mod << endl; mod = new_mod; for (auto cluster_id : c.getClusterIds()) { auto & td = target_graph.getNodeTertiaryData(cluster_id); assert(td.parent_node == -1); float best_d = 0; int best_node = -1; for (int n = td.first_child; n != -1; ) { auto & pd = target_graph.getNodeArray().getNodeData(n); auto & ctd = target_graph.getNodeTertiaryData(n); if (pd.type != NODE_URL && pd.type != NODE_ATTRIBUTE) { if (ctd.group_leader != -1) { auto & ctd2 = target_graph.getNodeTertiaryData(ctd.group_leader); if (best_node == -1 || ctd2.weighted_indegree > best_d) { best_node = ctd.group_leader; best_d = ctd2.weighted_indegree; } } else if (best_node == -1 || ctd.weighted_indegree > best_d) { best_node = n; best_d = ctd.weighted_indegree; } } n = ctd.next_child; } target_graph.setGroupLeader(cluster_id, best_node); } } } return is_changed; } <|endoftext|>
<commit_before>// // WinAPI // #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> #include <SetupAPI.h> #include <Shlwapi.h> #include <initguid.h> #include <winioctl.h> #include "XUSB.h" // // STL // #include <string> #include <codecvt> #include <locale> #include <map> #include <iostream> #include <fstream> // // JSON // #include <json/json.h> // // Hooking // #include <detours/detours.h> // // Logging // #include <spdlog/spdlog.h> #include <spdlog/sinks/basic_file_sink.h> #include <spdlog/fmt/bin_to_hex.h> using convert_t = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_t, wchar_t> strconverter; std::once_flag g_init; std::string g_dllDir; static decltype(SetupDiEnumDeviceInterfaces) *real_SetupDiEnumDeviceInterfaces = SetupDiEnumDeviceInterfaces; static decltype(DeviceIoControl) *real_DeviceIoControl = DeviceIoControl; static decltype(CreateFileA) *real_CreateFileA = CreateFileA; static decltype(CreateFileW) *real_CreateFileW = CreateFileW; static decltype(WriteFile)* real_WriteFile = WriteFile; static decltype(GetOverlappedResult)* real_GetOverlappedResult = GetOverlappedResult; static std::map<HANDLE, std::string> g_handleToPath; static std::map<DWORD, std::string> g_ioctlMap; // // Hooks SetupDiEnumDeviceInterfaces() API // BOOL WINAPI DetourSetupDiEnumDeviceInterfaces( HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, const GUID* InterfaceClassGuid, DWORD MemberIndex, PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("SetupDiEnumDeviceInterfaces"); auto retval = real_SetupDiEnumDeviceInterfaces(DeviceInfoSet, DeviceInfoData, InterfaceClassGuid, MemberIndex, DeviceInterfaceData); _logger->info("InterfaceClassGuid = {{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}, " "success = {}, error = 0x{:08X}", InterfaceClassGuid->Data1, InterfaceClassGuid->Data2, InterfaceClassGuid->Data3, InterfaceClassGuid->Data4[0], InterfaceClassGuid->Data4[1], InterfaceClassGuid->Data4[2], InterfaceClassGuid->Data4[3], InterfaceClassGuid->Data4[4], InterfaceClassGuid->Data4[5], InterfaceClassGuid->Data4[6], InterfaceClassGuid->Data4[7], retval ? "true" : "false", retval ? ERROR_SUCCESS : GetLastError()); return retval; } // // Hooks CreateFileA() API // HANDLE WINAPI DetourCreateFileA( LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CreateFileA"); std::string path(lpFileName); const bool isOfInterest = (path.rfind("\\\\", 0) == 0); const auto handle = real_CreateFileA( lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile ); if (isOfInterest && handle != INVALID_HANDLE_VALUE) { g_handleToPath[handle] = path; _logger->info("handle = {}, lpFileName = {}", handle, path); } return handle; } // // Hooks CreateFileW() API // HANDLE WINAPI DetourCreateFileW( LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CreateFileW"); std::string path(strconverter.to_bytes(lpFileName)); const bool isOfInterest = (path.rfind("\\\\", 0) == 0); const auto handle = real_CreateFileW( lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile ); if (isOfInterest && handle != INVALID_HANDLE_VALUE) { g_handleToPath[handle] = path; _logger->info("handle = {}, lpFileName = {}", handle, path); } return handle; } // // Hooks WriteFile() API // BOOL WINAPI DetourWriteFile( HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("WriteFile"); const PUCHAR charInBuf = PUCHAR(lpBuffer); DWORD tmpBytesWritten; const auto ret = real_WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, &tmpBytesWritten, lpOverlapped); const auto error = GetLastError(); if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = tmpBytesWritten; std::string path = "Unknown"; if (g_handleToPath.count(hFile)) { path = g_handleToPath[hFile]; } const auto bufSize = std::min(nNumberOfBytesToWrite, tmpBytesWritten); const std::vector<char> inBuffer(charInBuf, charInBuf + bufSize); // Prevent the logger from causing a crash via exception when it double-detours WriteFile try { _logger->info("success = {}, lastError = 0x{:08X}, path = {} ({:04d}) -> {:Xpn}", ret ? "true" : "false", ret ? ERROR_SUCCESS : error, path, bufSize, spdlog::to_hex(inBuffer) ); } catch (...) { } return ret; } BOOL WINAPI DetourGetOverlappedResult( HANDLE hFile, LPOVERLAPPED lpOverlapped, LPDWORD lpNumberOfBytesTransferred, BOOL bWait ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("GetOverlappedResult"); DWORD tmpBytesTransferred; const auto ret = real_GetOverlappedResult(hFile, lpOverlapped, &tmpBytesTransferred, bWait); const auto error = GetLastError(); if (lpNumberOfBytesTransferred) *lpNumberOfBytesTransferred = tmpBytesTransferred; std::string path = "Unknown"; if (g_handleToPath.count(hFile)) { path = g_handleToPath[hFile]; } _logger->info("success = {}, lastError = 0x{:08X}, bytesTransferred = {}, path = {}", ret ? "true" : "false", ret ? ERROR_SUCCESS : error, tmpBytesTransferred, path ); return ret; } // // Hooks DeviceIoControl() API // BOOL WINAPI DetourDeviceIoControl( HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("DeviceIoControl"); const PUCHAR charInBuf = static_cast<PUCHAR>(lpInBuffer); const std::vector<char> inBuffer(charInBuf, charInBuf + nInBufferSize); std::string path = "Unknown"; if (g_handleToPath.count(hDevice)) { path = g_handleToPath[hDevice]; } if (g_ioctlMap.count(dwIoControlCode)) { _logger->info("[I] [{}] path = {} ({:04d}) -> {:Xpn}", g_ioctlMap[dwIoControlCode], path, nInBufferSize, spdlog::to_hex(inBuffer) ); } DWORD tmpBytesReturned; const auto retval = real_DeviceIoControl( hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, &tmpBytesReturned, // might be null, use our own variable lpOverlapped ); if (lpBytesReturned) *lpBytesReturned = tmpBytesReturned; if (lpOutBuffer && nOutBufferSize > 0) { const PUCHAR charOutBuf = static_cast<PUCHAR>(lpOutBuffer); const auto bufSize = std::min(nOutBufferSize, tmpBytesReturned); const std::vector<char> outBuffer(charOutBuf, charOutBuf + bufSize); if (g_ioctlMap.count(dwIoControlCode)) { _logger->info("[O] [{}] path = {} ({:04d}) -> {:Xpn}", g_ioctlMap[dwIoControlCode], path, bufSize, spdlog::to_hex(outBuffer) ); } } return retval; } EXTERN_C IMAGE_DOS_HEADER __ImageBase; BOOL WINAPI DllMain(HINSTANCE dll_handle, DWORD reason, LPVOID reserved) { if (DetourIsHelperProcess()) { return TRUE; } switch (reason) { case DLL_PROCESS_ATTACH: { CHAR dllPath[MAX_PATH]; GetModuleFileNameA((HINSTANCE)&__ImageBase, dllPath, MAX_PATH); PathRemoveFileSpecA(dllPath); g_dllDir = std::string(dllPath); auto logger = spdlog::basic_logger_mt( "XInputHooker", g_dllDir + "\\XInputHooker.log" ); #if _DEBUG spdlog::set_level(spdlog::level::debug); logger->flush_on(spdlog::level::debug); #else logger->flush_on(spdlog::level::info); #endif set_default_logger(logger); // // Load known IOCTL code definitions // Json::Value root; std::ifstream ifs(g_dllDir + "\\ioctls.json"); ifs >> root; for (auto& i : root) { g_ioctlMap[std::stoul(i["HexValue"].asString(), nullptr, 16)] = i["Ioctl"].asString(); } } DisableThreadLibraryCalls(dll_handle); DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces); DetourAttach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl); DetourAttach((PVOID*)&real_CreateFileA, DetourCreateFileA); DetourAttach((PVOID*)&real_CreateFileW, DetourCreateFileW); DetourAttach((PVOID*)&real_WriteFile, DetourWriteFile); DetourAttach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult); DetourTransactionCommit(); break; case DLL_PROCESS_DETACH: DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces); DetourDetach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl); DetourDetach((PVOID*)&real_CreateFileA, DetourCreateFileA); DetourDetach((PVOID*)&real_CreateFileW, DetourCreateFileW); DetourDetach((PVOID*)&real_WriteFile, DetourWriteFile); DetourDetach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult); DetourTransactionCommit(); break; } return TRUE; } <commit_msg>Don't log for unknown handles by default; add compile option to allow Had to move the in buffer logging for the IOCTL detour to after the real function to keep things sane<commit_after>// // WinAPI // #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> #include <SetupAPI.h> #include <Shlwapi.h> #include <initguid.h> #include <winioctl.h> #include "XUSB.h" // // STL // #include <string> #include <codecvt> #include <locale> #include <map> #include <iostream> #include <fstream> // // JSON // #include <json/json.h> // // Hooking // #include <detours/detours.h> // // Logging // #include <spdlog/spdlog.h> #include <spdlog/sinks/basic_file_sink.h> #include <spdlog/fmt/bin_to_hex.h> using convert_t = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_t, wchar_t> strconverter; std::once_flag g_init; std::string g_dllDir; static decltype(SetupDiEnumDeviceInterfaces) *real_SetupDiEnumDeviceInterfaces = SetupDiEnumDeviceInterfaces; static decltype(DeviceIoControl) *real_DeviceIoControl = DeviceIoControl; static decltype(CreateFileA) *real_CreateFileA = CreateFileA; static decltype(CreateFileW) *real_CreateFileW = CreateFileW; static decltype(WriteFile)* real_WriteFile = WriteFile; static decltype(GetOverlappedResult)* real_GetOverlappedResult = GetOverlappedResult; static std::map<HANDLE, std::string> g_handleToPath; static std::map<DWORD, std::string> g_ioctlMap; // // Hooks SetupDiEnumDeviceInterfaces() API // BOOL WINAPI DetourSetupDiEnumDeviceInterfaces( HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, const GUID* InterfaceClassGuid, DWORD MemberIndex, PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("SetupDiEnumDeviceInterfaces"); auto retval = real_SetupDiEnumDeviceInterfaces(DeviceInfoSet, DeviceInfoData, InterfaceClassGuid, MemberIndex, DeviceInterfaceData); _logger->info("InterfaceClassGuid = {{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}, " "success = {}, error = 0x{:08X}", InterfaceClassGuid->Data1, InterfaceClassGuid->Data2, InterfaceClassGuid->Data3, InterfaceClassGuid->Data4[0], InterfaceClassGuid->Data4[1], InterfaceClassGuid->Data4[2], InterfaceClassGuid->Data4[3], InterfaceClassGuid->Data4[4], InterfaceClassGuid->Data4[5], InterfaceClassGuid->Data4[6], InterfaceClassGuid->Data4[7], retval ? "true" : "false", retval ? ERROR_SUCCESS : GetLastError()); return retval; } // // Hooks CreateFileA() API // HANDLE WINAPI DetourCreateFileA( LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CreateFileA"); std::string path(lpFileName); const bool isOfInterest = (path.rfind("\\\\", 0) == 0); const auto handle = real_CreateFileA( lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile ); if (isOfInterest && handle != INVALID_HANDLE_VALUE) { g_handleToPath[handle] = path; _logger->info("handle = {}, lpFileName = {}", handle, path); } return handle; } // // Hooks CreateFileW() API // HANDLE WINAPI DetourCreateFileW( LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CreateFileW"); std::string path(strconverter.to_bytes(lpFileName)); const bool isOfInterest = (path.rfind("\\\\", 0) == 0); const auto handle = real_CreateFileW( lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile ); if (isOfInterest && handle != INVALID_HANDLE_VALUE) { g_handleToPath[handle] = path; _logger->info("handle = {}, lpFileName = {}", handle, path); } return handle; } // // Hooks WriteFile() API // BOOL WINAPI DetourWriteFile( HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("WriteFile"); const PUCHAR charInBuf = PUCHAR(lpBuffer); DWORD tmpBytesWritten; const auto ret = real_WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, &tmpBytesWritten, lpOverlapped); const auto error = GetLastError(); if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = tmpBytesWritten; std::string path = "Unknown"; if (g_handleToPath.count(hFile)) { path = g_handleToPath[hFile]; } #ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES else { // Ignore unknown handles return ret; } #endif const auto bufSize = std::min(nNumberOfBytesToWrite, tmpBytesWritten); const std::vector<char> inBuffer(charInBuf, charInBuf + bufSize); // Prevent the logger from causing a crash via exception when it double-detours WriteFile try { _logger->info("success = {}, lastError = 0x{:08X}, path = {} ({:04d}) -> {:Xpn}", ret ? "true" : "false", ret ? ERROR_SUCCESS : error, path, bufSize, spdlog::to_hex(inBuffer) ); } catch (...) { } return ret; } BOOL WINAPI DetourGetOverlappedResult( HANDLE hFile, LPOVERLAPPED lpOverlapped, LPDWORD lpNumberOfBytesTransferred, BOOL bWait ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("GetOverlappedResult"); DWORD tmpBytesTransferred; const auto ret = real_GetOverlappedResult(hFile, lpOverlapped, &tmpBytesTransferred, bWait); const auto error = GetLastError(); if (lpNumberOfBytesTransferred) *lpNumberOfBytesTransferred = tmpBytesTransferred; std::string path = "Unknown"; if (g_handleToPath.count(hFile)) { path = g_handleToPath[hFile]; } #ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES else { // Ignore unknown handles return ret; } #endif _logger->info("success = {}, lastError = 0x{:08X}, bytesTransferred = {}, path = {}", ret ? "true" : "false", ret ? ERROR_SUCCESS : error, tmpBytesTransferred, path ); return ret; } // // Hooks DeviceIoControl() API // BOOL WINAPI DetourDeviceIoControl( HANDLE hDevice, DWORD dwIoControlCode, LPVOID lpInBuffer, DWORD nInBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped ) { std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("DeviceIoControl"); const PUCHAR charInBuf = static_cast<PUCHAR>(lpInBuffer); const std::vector<char> inBuffer(charInBuf, charInBuf + nInBufferSize); DWORD tmpBytesReturned; const auto retval = real_DeviceIoControl( hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, &tmpBytesReturned, // might be null, use our own variable lpOverlapped ); if (lpBytesReturned) *lpBytesReturned = tmpBytesReturned; std::string path = "Unknown"; if (g_handleToPath.count(hDevice)) { path = g_handleToPath[hDevice]; } #ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES else { // Ignore unknown handles return retval; } #endif if (g_ioctlMap.count(dwIoControlCode)) { _logger->info("[I] [{}] path = {} ({:04d}) -> {:Xpn}", g_ioctlMap[dwIoControlCode], path, nInBufferSize, spdlog::to_hex(inBuffer) ); } if (lpOutBuffer && nOutBufferSize > 0) { const PUCHAR charOutBuf = static_cast<PUCHAR>(lpOutBuffer); const auto bufSize = std::min(nOutBufferSize, tmpBytesReturned); const std::vector<char> outBuffer(charOutBuf, charOutBuf + bufSize); if (g_ioctlMap.count(dwIoControlCode)) { _logger->info("[O] [{}] path = {} ({:04d}) -> {:Xpn}", g_ioctlMap[dwIoControlCode], path, bufSize, spdlog::to_hex(outBuffer) ); } } return retval; } EXTERN_C IMAGE_DOS_HEADER __ImageBase; BOOL WINAPI DllMain(HINSTANCE dll_handle, DWORD reason, LPVOID reserved) { if (DetourIsHelperProcess()) { return TRUE; } switch (reason) { case DLL_PROCESS_ATTACH: { CHAR dllPath[MAX_PATH]; GetModuleFileNameA((HINSTANCE)&__ImageBase, dllPath, MAX_PATH); PathRemoveFileSpecA(dllPath); g_dllDir = std::string(dllPath); auto logger = spdlog::basic_logger_mt( "XInputHooker", g_dllDir + "\\XInputHooker.log" ); #if _DEBUG spdlog::set_level(spdlog::level::debug); logger->flush_on(spdlog::level::debug); #else logger->flush_on(spdlog::level::info); #endif set_default_logger(logger); // // Load known IOCTL code definitions // Json::Value root; std::ifstream ifs(g_dllDir + "\\ioctls.json"); ifs >> root; for (auto& i : root) { g_ioctlMap[std::stoul(i["HexValue"].asString(), nullptr, 16)] = i["Ioctl"].asString(); } } DisableThreadLibraryCalls(dll_handle); DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces); DetourAttach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl); DetourAttach((PVOID*)&real_CreateFileA, DetourCreateFileA); DetourAttach((PVOID*)&real_CreateFileW, DetourCreateFileW); DetourAttach((PVOID*)&real_WriteFile, DetourWriteFile); DetourAttach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult); DetourTransactionCommit(); break; case DLL_PROCESS_DETACH: DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces); DetourDetach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl); DetourDetach((PVOID*)&real_CreateFileA, DetourCreateFileA); DetourDetach((PVOID*)&real_CreateFileW, DetourCreateFileW); DetourDetach((PVOID*)&real_WriteFile, DetourWriteFile); DetourDetach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult); DetourTransactionCommit(); break; } return TRUE; } <|endoftext|>
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "pointer_injector_delegate.h" #include "flutter/fml/logging.h" namespace flutter_runner { using fup_Config = fuchsia::ui::pointerinjector::Config; using fup_Context = fuchsia::ui::pointerinjector::Context; using fup_Data = fuchsia::ui::pointerinjector::Data; using fup_DeviceType = fuchsia::ui::pointerinjector::DeviceType; using fup_DispatchPolicy = fuchsia::ui::pointerinjector::DispatchPolicy; using fup_Event = fuchsia::ui::pointerinjector::Event; using fup_EventPhase = fuchsia::ui::pointerinjector::EventPhase; using fup_PointerSample = fuchsia::ui::pointerinjector::PointerSample; using fup_Target = fuchsia::ui::pointerinjector::Target; using fup_Viewport = fuchsia::ui::pointerinjector::Viewport; using fuv_ViewRef = fuchsia::ui::views::ViewRef; const auto fup_MAX_INJECT = fuchsia::ui::pointerinjector::MAX_INJECT; namespace { // clang-format off static constexpr std::array<float, 9> kIdentityMatrix = { 1, 0, 0, // column one 0, 1, 0, // column two 0, 0, 1, // column three }; // clang-format on } // namespace bool PointerInjectorDelegate::HandlePlatformMessage( rapidjson::Value request, fml::RefPtr<flutter::PlatformMessageResponse> response) { if (!registry_->is_bound()) { FML_LOG(WARNING) << "Lost connection to fuchsia.ui.pointerinjector.Registry"; return false; } auto method = request.FindMember("method"); if (method == request.MemberEnd() || !method->value.IsString()) { return false; } if (method->value == kPointerInjectorMethodPrefix) { auto args_it = request.FindMember("args"); if (args_it == request.MemberEnd() || !args_it->value.IsObject()) { FML_LOG(ERROR) << "No arguments found."; return false; } const auto& args = args_it->value; auto view_id = args.FindMember("viewId"); if (!view_id->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'viewId' is not a uint64"; return false; } auto id = view_id->value.GetUint64(); auto phase = args.FindMember("phase"); if (!phase->value.IsInt()) { FML_LOG(ERROR) << "Argument 'phase' is not a int"; return false; } auto pointer_x = args.FindMember("x"); if (!pointer_x->value.IsFloat() && !pointer_x->value.IsInt()) { FML_LOG(ERROR) << "Argument 'Pointer.X' is not a float"; return false; } auto pointer_y = args.FindMember("y"); if (!pointer_y->value.IsFloat() && !pointer_y->value.IsInt()) { FML_LOG(ERROR) << "Argument 'Pointer.Y' is not a float"; return false; } auto pointer_id = args.FindMember("pointerId"); if (!pointer_id->value.IsUint()) { FML_LOG(ERROR) << "Argument 'pointerId' is not a uint32"; return false; } auto trace_flow_id = args.FindMember("traceFlowId"); if (!trace_flow_id->value.IsInt()) { FML_LOG(ERROR) << "Argument 'traceFlowId' is not a int"; return false; } // For GFX, the viewRef for the view is provided through the platform // message. For flatland, the viewRef is provided through |OnCreateView|. std::optional<fuv_ViewRef> view_ref; if (!is_flatland_) { auto view_ref_arg = args.FindMember("viewRef"); if (!view_ref_arg->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'viewRef' is not a uint64"; return false; } zx_handle_t handle = view_ref_arg->value.GetUint64(); zx_handle_t out_handle; zx_status_t status = zx_handle_duplicate(handle, ZX_RIGHT_SAME_RIGHTS, &out_handle); if (status != ZX_OK) { FML_LOG(ERROR) << "Argument 'viewRef' is not valid"; return false; } auto ref = fuv_ViewRef({ .reference = zx::eventpair(out_handle), }); view_ref = std::move(ref); } auto width = args.FindMember("logicalWidth"); if (!width->value.IsFloat() && !width->value.IsInt()) { FML_LOG(ERROR) << "Argument 'logicalWidth' is not a float"; return false; } auto height = args.FindMember("logicalHeight"); if (!height->value.IsFloat() && !height->value.IsInt()) { FML_LOG(ERROR) << "Argument 'logicalHeight' is not a float"; return false; } auto timestamp = args.FindMember("timestamp"); if (!timestamp->value.IsInt()) { FML_LOG(ERROR) << "Argument 'timestamp' is not a int"; return false; } PointerInjectorRequest request = { .x = pointer_x->value.GetFloat(), .y = pointer_y->value.GetFloat(), .pointer_id = pointer_id->value.GetUint(), .phase = static_cast<fup_EventPhase>(phase->value.GetInt()), .trace_flow_id = trace_flow_id->value.GetUint64(), .view_ref = std::move(view_ref), .logical_size = {width->value.GetFloat(), height->value.GetFloat()}, .timestamp = timestamp->value.GetInt()}; // Inject the pointer event if the view has been created. if (valid_views_.count(id) > 0) { valid_views_.at(id).InjectEvent(std::move(request)); Complete(std::move(response), "[0]"); } else { return false; } } else { return false; } // All of our methods complete the platform message response. return true; } void PointerInjectorDelegate::OnCreateView( uint64_t view_id, std::optional<fuv_ViewRef> view_ref) { FML_CHECK(valid_views_.count(view_id) == 0); auto [_, success] = valid_views_.try_emplace( view_id, registry_, host_view_ref_, std::move(view_ref)); FML_CHECK(success); } fup_Event PointerInjectorDelegate::ExtractPointerEvent( PointerInjectorRequest request) { fup_Event event; event.set_timestamp(request.timestamp); event.set_trace_flow_id(request.trace_flow_id); fup_PointerSample pointer_sample; pointer_sample.set_pointer_id(request.pointer_id); pointer_sample.set_phase(request.phase); pointer_sample.set_position_in_viewport({request.x, request.y}); fup_Data data; data.set_pointer_sample(std::move(pointer_sample)); event.set_data(std::move(data)); return event; } void PointerInjectorDelegate::Complete( fml::RefPtr<flutter::PlatformMessageResponse> response, std::string value) { if (response) { response->Complete(std::make_unique<fml::DataMapping>( std::vector<uint8_t>(value.begin(), value.end()))); } } void PointerInjectorDelegate::PointerInjectorEndpoint::InjectEvent( PointerInjectorRequest request) { if (!registered_) { RegisterInjector(request); } auto event = ExtractPointerEvent(std::move(request)); // Add the event to |injector_events_| and dispatch it to the view. EnqueueEvent(std::move(event)); DispatchPendingEvents(); } void PointerInjectorDelegate::PointerInjectorEndpoint::DispatchPendingEvents() { // Return if there is already a |fuchsia.ui.pointerinjector.Device.Inject| // call in flight. The new pointer events will be dispatched once the // in-progress call terminates. if (injection_in_flight_) { return; } // Dispatch the events present in |injector_events_|. Note that we recursively // call |DispatchPendingEvents| in the callback passed to the // |f.u.p.Device.Inject| call. This ensures that there is only one // |f.u.p.Device.Inject| call at a time. If a new pointer event comes when // there is a |f.u.p.Device.Inject| call in progress, it gets buffered in // |injector_events_| and is picked up later. if (!injector_events_.empty()) { auto events = std::move(injector_events_.front()); injector_events_.pop(); injection_in_flight_ = true; FML_CHECK(device_.is_bound()); FML_CHECK(events.size() <= fup_MAX_INJECT); device_->Inject(std::move(events), [weak = weak_factory_.GetWeakPtr()] { if (!weak) { FML_LOG(WARNING) << "Use after free attempted."; return; } weak->injection_in_flight_ = false; weak->DispatchPendingEvents(); }); } } void PointerInjectorDelegate::PointerInjectorEndpoint::EnqueueEvent( fup_Event event) { // Add |event| in |injector_events_| keeping in mind that the vector size does // not exceed |fup_MAX_INJECT|. if (!injector_events_.empty() && injector_events_.back().size() < fup_MAX_INJECT) { injector_events_.back().push_back(std::move(event)); } else { std::vector<fup_Event> vec; vec.reserve(fup_MAX_INJECT); vec.push_back(std::move(event)); injector_events_.push(std::move(vec)); } } void PointerInjectorDelegate::PointerInjectorEndpoint::RegisterInjector( const PointerInjectorRequest& request) { if (registered_) { return; } fup_Config config; config.set_device_id(1); config.set_device_type(fup_DeviceType::TOUCH); config.set_dispatch_policy(fup_DispatchPolicy::EXCLUSIVE_TARGET); fup_Context context; fuv_ViewRef context_clone; fidl::Clone(*host_view_ref_, &context_clone); context.set_view(std::move(context_clone)); config.set_context(std::move(context)); FML_CHECK(request.view_ref.has_value() || view_ref_.has_value()); fup_Target target; fuv_ViewRef target_clone; // GFX. if (request.view_ref.has_value()) { fidl::Clone(*request.view_ref, &target_clone); } // Flatland. else { fidl::Clone(*view_ref_, &target_clone); } target.set_view(std::move(target_clone)); config.set_target(std::move(target)); fup_Viewport viewport; viewport.set_viewport_to_context_transform(kIdentityMatrix); std::array<std::array<float, 2>, 2> extents{ {/*min*/ {0, 0}, /*max*/ {request.logical_size[0], request.logical_size[1]}}}; viewport.set_extents(std::move(extents)); config.set_viewport(std::move(viewport)); FML_CHECK(registry_->is_bound()); (*registry_)->Register(std::move(config), device_.NewRequest(), [] {}); registered_ = true; } } // namespace flutter_runner <commit_msg>[fuchsia][scenic] Accept Uint64 values in timestamp for pointerinjector. (#34888)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "pointer_injector_delegate.h" #include "flutter/fml/logging.h" namespace flutter_runner { using fup_Config = fuchsia::ui::pointerinjector::Config; using fup_Context = fuchsia::ui::pointerinjector::Context; using fup_Data = fuchsia::ui::pointerinjector::Data; using fup_DeviceType = fuchsia::ui::pointerinjector::DeviceType; using fup_DispatchPolicy = fuchsia::ui::pointerinjector::DispatchPolicy; using fup_Event = fuchsia::ui::pointerinjector::Event; using fup_EventPhase = fuchsia::ui::pointerinjector::EventPhase; using fup_PointerSample = fuchsia::ui::pointerinjector::PointerSample; using fup_Target = fuchsia::ui::pointerinjector::Target; using fup_Viewport = fuchsia::ui::pointerinjector::Viewport; using fuv_ViewRef = fuchsia::ui::views::ViewRef; const auto fup_MAX_INJECT = fuchsia::ui::pointerinjector::MAX_INJECT; namespace { // clang-format off static constexpr std::array<float, 9> kIdentityMatrix = { 1, 0, 0, // column one 0, 1, 0, // column two 0, 0, 1, // column three }; // clang-format on } // namespace bool PointerInjectorDelegate::HandlePlatformMessage( rapidjson::Value request, fml::RefPtr<flutter::PlatformMessageResponse> response) { if (!registry_->is_bound()) { FML_LOG(WARNING) << "Lost connection to fuchsia.ui.pointerinjector.Registry"; return false; } auto method = request.FindMember("method"); if (method == request.MemberEnd() || !method->value.IsString()) { return false; } if (method->value == kPointerInjectorMethodPrefix) { auto args_it = request.FindMember("args"); if (args_it == request.MemberEnd() || !args_it->value.IsObject()) { FML_LOG(ERROR) << "No arguments found."; return false; } const auto& args = args_it->value; auto view_id = args.FindMember("viewId"); if (!view_id->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'viewId' is not a uint64"; return false; } auto id = view_id->value.GetUint64(); auto phase = args.FindMember("phase"); if (!phase->value.IsInt()) { FML_LOG(ERROR) << "Argument 'phase' is not a int"; return false; } auto pointer_x = args.FindMember("x"); if (!pointer_x->value.IsFloat() && !pointer_x->value.IsInt()) { FML_LOG(ERROR) << "Argument 'Pointer.X' is not a float"; return false; } auto pointer_y = args.FindMember("y"); if (!pointer_y->value.IsFloat() && !pointer_y->value.IsInt()) { FML_LOG(ERROR) << "Argument 'Pointer.Y' is not a float"; return false; } auto pointer_id = args.FindMember("pointerId"); if (!pointer_id->value.IsUint()) { FML_LOG(ERROR) << "Argument 'pointerId' is not a uint32"; return false; } auto trace_flow_id = args.FindMember("traceFlowId"); if (!trace_flow_id->value.IsInt()) { FML_LOG(ERROR) << "Argument 'traceFlowId' is not a int"; return false; } // For GFX, the viewRef for the view is provided through the platform // message. For flatland, the viewRef is provided through |OnCreateView|. std::optional<fuv_ViewRef> view_ref; if (!is_flatland_) { auto view_ref_arg = args.FindMember("viewRef"); if (!view_ref_arg->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'viewRef' is not a uint64"; return false; } zx_handle_t handle = view_ref_arg->value.GetUint64(); zx_handle_t out_handle; zx_status_t status = zx_handle_duplicate(handle, ZX_RIGHT_SAME_RIGHTS, &out_handle); if (status != ZX_OK) { FML_LOG(ERROR) << "Argument 'viewRef' is not valid"; return false; } auto ref = fuv_ViewRef({ .reference = zx::eventpair(out_handle), }); view_ref = std::move(ref); } auto width = args.FindMember("logicalWidth"); if (!width->value.IsFloat() && !width->value.IsInt()) { FML_LOG(ERROR) << "Argument 'logicalWidth' is not a float"; return false; } auto height = args.FindMember("logicalHeight"); if (!height->value.IsFloat() && !height->value.IsInt()) { FML_LOG(ERROR) << "Argument 'logicalHeight' is not a float"; return false; } auto timestamp = args.FindMember("timestamp"); if (!timestamp->value.IsInt() && !timestamp->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'timestamp' is not a int"; return false; } PointerInjectorRequest request = { .x = pointer_x->value.GetFloat(), .y = pointer_y->value.GetFloat(), .pointer_id = pointer_id->value.GetUint(), .phase = static_cast<fup_EventPhase>(phase->value.GetInt()), .trace_flow_id = trace_flow_id->value.GetUint64(), .view_ref = std::move(view_ref), .logical_size = {width->value.GetFloat(), height->value.GetFloat()}, .timestamp = timestamp->value.GetInt()}; // Inject the pointer event if the view has been created. if (valid_views_.count(id) > 0) { valid_views_.at(id).InjectEvent(std::move(request)); Complete(std::move(response), "[0]"); } else { return false; } } else { return false; } // All of our methods complete the platform message response. return true; } void PointerInjectorDelegate::OnCreateView( uint64_t view_id, std::optional<fuv_ViewRef> view_ref) { FML_CHECK(valid_views_.count(view_id) == 0); auto [_, success] = valid_views_.try_emplace( view_id, registry_, host_view_ref_, std::move(view_ref)); FML_CHECK(success); } fup_Event PointerInjectorDelegate::ExtractPointerEvent( PointerInjectorRequest request) { fup_Event event; event.set_timestamp(request.timestamp); event.set_trace_flow_id(request.trace_flow_id); fup_PointerSample pointer_sample; pointer_sample.set_pointer_id(request.pointer_id); pointer_sample.set_phase(request.phase); pointer_sample.set_position_in_viewport({request.x, request.y}); fup_Data data; data.set_pointer_sample(std::move(pointer_sample)); event.set_data(std::move(data)); return event; } void PointerInjectorDelegate::Complete( fml::RefPtr<flutter::PlatformMessageResponse> response, std::string value) { if (response) { response->Complete(std::make_unique<fml::DataMapping>( std::vector<uint8_t>(value.begin(), value.end()))); } } void PointerInjectorDelegate::PointerInjectorEndpoint::InjectEvent( PointerInjectorRequest request) { if (!registered_) { RegisterInjector(request); } auto event = ExtractPointerEvent(std::move(request)); // Add the event to |injector_events_| and dispatch it to the view. EnqueueEvent(std::move(event)); DispatchPendingEvents(); } void PointerInjectorDelegate::PointerInjectorEndpoint::DispatchPendingEvents() { // Return if there is already a |fuchsia.ui.pointerinjector.Device.Inject| // call in flight. The new pointer events will be dispatched once the // in-progress call terminates. if (injection_in_flight_) { return; } // Dispatch the events present in |injector_events_|. Note that we recursively // call |DispatchPendingEvents| in the callback passed to the // |f.u.p.Device.Inject| call. This ensures that there is only one // |f.u.p.Device.Inject| call at a time. If a new pointer event comes when // there is a |f.u.p.Device.Inject| call in progress, it gets buffered in // |injector_events_| and is picked up later. if (!injector_events_.empty()) { auto events = std::move(injector_events_.front()); injector_events_.pop(); injection_in_flight_ = true; FML_CHECK(device_.is_bound()); FML_CHECK(events.size() <= fup_MAX_INJECT); device_->Inject(std::move(events), [weak = weak_factory_.GetWeakPtr()] { if (!weak) { FML_LOG(WARNING) << "Use after free attempted."; return; } weak->injection_in_flight_ = false; weak->DispatchPendingEvents(); }); } } void PointerInjectorDelegate::PointerInjectorEndpoint::EnqueueEvent( fup_Event event) { // Add |event| in |injector_events_| keeping in mind that the vector size does // not exceed |fup_MAX_INJECT|. if (!injector_events_.empty() && injector_events_.back().size() < fup_MAX_INJECT) { injector_events_.back().push_back(std::move(event)); } else { std::vector<fup_Event> vec; vec.reserve(fup_MAX_INJECT); vec.push_back(std::move(event)); injector_events_.push(std::move(vec)); } } void PointerInjectorDelegate::PointerInjectorEndpoint::RegisterInjector( const PointerInjectorRequest& request) { if (registered_) { return; } fup_Config config; config.set_device_id(1); config.set_device_type(fup_DeviceType::TOUCH); config.set_dispatch_policy(fup_DispatchPolicy::EXCLUSIVE_TARGET); fup_Context context; fuv_ViewRef context_clone; fidl::Clone(*host_view_ref_, &context_clone); context.set_view(std::move(context_clone)); config.set_context(std::move(context)); FML_CHECK(request.view_ref.has_value() || view_ref_.has_value()); fup_Target target; fuv_ViewRef target_clone; // GFX. if (request.view_ref.has_value()) { fidl::Clone(*request.view_ref, &target_clone); } // Flatland. else { fidl::Clone(*view_ref_, &target_clone); } target.set_view(std::move(target_clone)); config.set_target(std::move(target)); fup_Viewport viewport; viewport.set_viewport_to_context_transform(kIdentityMatrix); std::array<std::array<float, 2>, 2> extents{ {/*min*/ {0, 0}, /*max*/ {request.logical_size[0], request.logical_size[1]}}}; viewport.set_extents(std::move(extents)); config.set_viewport(std::move(viewport)); FML_CHECK(registry_->is_bound()); (*registry_)->Register(std::move(config), device_.NewRequest(), [] {}); registered_ = true; } } // namespace flutter_runner <|endoftext|>
<commit_before>//===-- RegisterContextPOSIX_arm.cpp --------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <cstring> #include <errno.h> #include <stdint.h> #include "lldb/Core/DataBufferHeap.h" #include "lldb/Core/DataExtractor.h" #include "lldb/Core/RegisterValue.h" #include "lldb/Core/Scalar.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Host/Endian.h" #include "llvm/Support/Compiler.h" #include "RegisterContextPOSIX_arm.h" #include "Plugins/Process/elf-core/ProcessElfCore.h" using namespace lldb; using namespace lldb_private; // arm general purpose registers. const uint32_t g_gpr_regnums_arm[] = { gpr_r0_arm, gpr_r1_arm, gpr_r2_arm, gpr_r3_arm, gpr_r4_arm, gpr_r5_arm, gpr_r6_arm, gpr_r7_arm, gpr_r8_arm, gpr_r9_arm, gpr_r10_arm, gpr_r11_arm, gpr_r12_arm, gpr_sp_arm, gpr_lr_arm, gpr_pc_arm, gpr_cpsr_arm, LLDB_INVALID_REGNUM // register sets need to end with this flag }; static_assert(((sizeof g_gpr_regnums_arm / sizeof g_gpr_regnums_arm[0]) - 1) == k_num_gpr_registers_arm, \ "g_gpr_regnums_arm has wrong number of register infos"); // arm floating point registers. static const uint32_t g_fpu_regnums_arm[] = { fpu_s0_arm, fpu_s1_arm, fpu_s2_arm, fpu_s3_arm, fpu_s4_arm, fpu_s5_arm, fpu_s6_arm, fpu_s7_arm, fpu_s8_arm, fpu_s9_arm, fpu_s10_arm, fpu_s11_arm, fpu_s12_arm, fpu_s13_arm, fpu_s14_arm, fpu_s15_arm, fpu_s16_arm, fpu_s17_arm, fpu_s18_arm, fpu_s19_arm, fpu_s20_arm, fpu_s21_arm, fpu_s22_arm, fpu_s23_arm, fpu_s24_arm, fpu_s25_arm, fpu_s26_arm, fpu_s27_arm, fpu_s28_arm, fpu_s29_arm, fpu_s30_arm, fpu_s31_arm, fpu_fpscr_arm, LLDB_INVALID_REGNUM // register sets need to end with this flag }; static_assert(((sizeof g_fpu_regnums_arm / sizeof g_fpu_regnums_arm[0]) - 1) == k_num_fpr_registers_arm, \ "g_fpu_regnums_arm has wrong number of register infos"); // Number of register sets provided by this context. enum { k_num_register_sets = 2 }; // Register sets for arm. static const lldb_private::RegisterSet g_reg_sets_arm[k_num_register_sets] = { { "General Purpose Registers", "gpr", k_num_gpr_registers_arm, g_gpr_regnums_arm }, { "Floating Point Registers", "fpu", k_num_fpr_registers_arm, g_fpu_regnums_arm } }; bool RegisterContextPOSIX_arm::IsGPR(unsigned reg) { return reg <= m_reg_info.last_gpr; // GPR's come first. } bool RegisterContextPOSIX_arm::IsFPR(unsigned reg) { return (m_reg_info.first_fpr <= reg && reg <= m_reg_info.last_fpr); } RegisterContextPOSIX_arm::RegisterContextPOSIX_arm(lldb_private::Thread &thread, uint32_t concrete_frame_idx, lldb_private::RegisterInfoInterface *register_info) : lldb_private::RegisterContext(thread, concrete_frame_idx) { m_register_info_ap.reset(register_info); switch (register_info->m_target_arch.GetMachine()) { case llvm::Triple::arm: m_reg_info.num_registers = k_num_registers_arm; m_reg_info.num_gpr_registers = k_num_gpr_registers_arm; m_reg_info.num_fpr_registers = k_num_fpr_registers_arm; m_reg_info.last_gpr = k_last_gpr_arm; m_reg_info.first_fpr = k_first_fpr_arm; m_reg_info.last_fpr = k_last_fpr_arm; m_reg_info.first_fpr_v = fpu_s0_arm; m_reg_info.last_fpr_v = fpu_s31_arm; m_reg_info.gpr_flags = gpr_cpsr_arm; break; default: assert(false && "Unhandled target architecture."); break; } ::memset(&m_fpr, 0, sizeof m_fpr); // elf-core yet to support ReadFPR() lldb::ProcessSP base = CalculateProcess(); if (base.get()->GetPluginName() == ProcessElfCore::GetPluginNameStatic()) return; } RegisterContextPOSIX_arm::~RegisterContextPOSIX_arm() { } void RegisterContextPOSIX_arm::Invalidate() { } void RegisterContextPOSIX_arm::InvalidateAllRegisters() { } unsigned RegisterContextPOSIX_arm::GetRegisterOffset(unsigned reg) { assert(reg < m_reg_info.num_registers && "Invalid register number."); return GetRegisterInfo()[reg].byte_offset; } unsigned RegisterContextPOSIX_arm::GetRegisterSize(unsigned reg) { assert(reg < m_reg_info.num_registers && "Invalid register number."); return GetRegisterInfo()[reg].byte_size; } size_t RegisterContextPOSIX_arm::GetRegisterCount() { size_t num_registers = m_reg_info.num_gpr_registers + m_reg_info.num_fpr_registers; return num_registers; } size_t RegisterContextPOSIX_arm::GetGPRSize() { return m_register_info_ap->GetGPRSize (); } const lldb_private::RegisterInfo * RegisterContextPOSIX_arm::GetRegisterInfo() { // Commonly, this method is overridden and g_register_infos is copied and specialized. // So, use GetRegisterInfo() rather than g_register_infos in this scope. return m_register_info_ap->GetRegisterInfo (); } const lldb_private::RegisterInfo * RegisterContextPOSIX_arm::GetRegisterInfoAtIndex(size_t reg) { if (reg < m_reg_info.num_registers) return &GetRegisterInfo()[reg]; else return NULL; } size_t RegisterContextPOSIX_arm::GetRegisterSetCount() { size_t sets = 0; for (size_t set = 0; set < k_num_register_sets; ++set) { if (IsRegisterSetAvailable(set)) ++sets; } return sets; } const lldb_private::RegisterSet * RegisterContextPOSIX_arm::GetRegisterSet(size_t set) { if (IsRegisterSetAvailable(set)) { switch (m_register_info_ap->m_target_arch.GetMachine()) { case llvm::Triple::aarch64: return &g_reg_sets_arm[set]; default: assert(false && "Unhandled target architecture."); return NULL; } } return NULL; } const char * RegisterContextPOSIX_arm::GetRegisterName(unsigned reg) { assert(reg < m_reg_info.num_registers && "Invalid register offset."); return GetRegisterInfo()[reg].name; } lldb::ByteOrder RegisterContextPOSIX_arm::GetByteOrder() { // Get the target process whose privileged thread was used for the register read. lldb::ByteOrder byte_order = lldb::eByteOrderInvalid; lldb_private::Process *process = CalculateProcess().get(); if (process) byte_order = process->GetByteOrder(); return byte_order; } bool RegisterContextPOSIX_arm::IsRegisterSetAvailable(size_t set_index) { return set_index < k_num_register_sets; } // Used when parsing DWARF and EH frame information and any other // object file sections that contain register numbers in them. uint32_t RegisterContextPOSIX_arm::ConvertRegisterKindToRegisterNumber(lldb::RegisterKind kind, uint32_t num) { const uint32_t num_regs = GetRegisterCount(); assert (kind < lldb::kNumRegisterKinds); for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) { const lldb_private::RegisterInfo *reg_info = GetRegisterInfoAtIndex (reg_idx); if (reg_info->kinds[kind] == num) return reg_idx; } return LLDB_INVALID_REGNUM; } <commit_msg>Correct machine type for 32-bit arm<commit_after>//===-- RegisterContextPOSIX_arm.cpp --------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <cstring> #include <errno.h> #include <stdint.h> #include "lldb/Core/DataBufferHeap.h" #include "lldb/Core/DataExtractor.h" #include "lldb/Core/RegisterValue.h" #include "lldb/Core/Scalar.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Host/Endian.h" #include "llvm/Support/Compiler.h" #include "RegisterContextPOSIX_arm.h" #include "Plugins/Process/elf-core/ProcessElfCore.h" using namespace lldb; using namespace lldb_private; // arm general purpose registers. const uint32_t g_gpr_regnums_arm[] = { gpr_r0_arm, gpr_r1_arm, gpr_r2_arm, gpr_r3_arm, gpr_r4_arm, gpr_r5_arm, gpr_r6_arm, gpr_r7_arm, gpr_r8_arm, gpr_r9_arm, gpr_r10_arm, gpr_r11_arm, gpr_r12_arm, gpr_sp_arm, gpr_lr_arm, gpr_pc_arm, gpr_cpsr_arm, LLDB_INVALID_REGNUM // register sets need to end with this flag }; static_assert(((sizeof g_gpr_regnums_arm / sizeof g_gpr_regnums_arm[0]) - 1) == k_num_gpr_registers_arm, \ "g_gpr_regnums_arm has wrong number of register infos"); // arm floating point registers. static const uint32_t g_fpu_regnums_arm[] = { fpu_s0_arm, fpu_s1_arm, fpu_s2_arm, fpu_s3_arm, fpu_s4_arm, fpu_s5_arm, fpu_s6_arm, fpu_s7_arm, fpu_s8_arm, fpu_s9_arm, fpu_s10_arm, fpu_s11_arm, fpu_s12_arm, fpu_s13_arm, fpu_s14_arm, fpu_s15_arm, fpu_s16_arm, fpu_s17_arm, fpu_s18_arm, fpu_s19_arm, fpu_s20_arm, fpu_s21_arm, fpu_s22_arm, fpu_s23_arm, fpu_s24_arm, fpu_s25_arm, fpu_s26_arm, fpu_s27_arm, fpu_s28_arm, fpu_s29_arm, fpu_s30_arm, fpu_s31_arm, fpu_fpscr_arm, LLDB_INVALID_REGNUM // register sets need to end with this flag }; static_assert(((sizeof g_fpu_regnums_arm / sizeof g_fpu_regnums_arm[0]) - 1) == k_num_fpr_registers_arm, \ "g_fpu_regnums_arm has wrong number of register infos"); // Number of register sets provided by this context. enum { k_num_register_sets = 2 }; // Register sets for arm. static const lldb_private::RegisterSet g_reg_sets_arm[k_num_register_sets] = { { "General Purpose Registers", "gpr", k_num_gpr_registers_arm, g_gpr_regnums_arm }, { "Floating Point Registers", "fpu", k_num_fpr_registers_arm, g_fpu_regnums_arm } }; bool RegisterContextPOSIX_arm::IsGPR(unsigned reg) { return reg <= m_reg_info.last_gpr; // GPR's come first. } bool RegisterContextPOSIX_arm::IsFPR(unsigned reg) { return (m_reg_info.first_fpr <= reg && reg <= m_reg_info.last_fpr); } RegisterContextPOSIX_arm::RegisterContextPOSIX_arm(lldb_private::Thread &thread, uint32_t concrete_frame_idx, lldb_private::RegisterInfoInterface *register_info) : lldb_private::RegisterContext(thread, concrete_frame_idx) { m_register_info_ap.reset(register_info); switch (register_info->m_target_arch.GetMachine()) { case llvm::Triple::arm: m_reg_info.num_registers = k_num_registers_arm; m_reg_info.num_gpr_registers = k_num_gpr_registers_arm; m_reg_info.num_fpr_registers = k_num_fpr_registers_arm; m_reg_info.last_gpr = k_last_gpr_arm; m_reg_info.first_fpr = k_first_fpr_arm; m_reg_info.last_fpr = k_last_fpr_arm; m_reg_info.first_fpr_v = fpu_s0_arm; m_reg_info.last_fpr_v = fpu_s31_arm; m_reg_info.gpr_flags = gpr_cpsr_arm; break; default: assert(false && "Unhandled target architecture."); break; } ::memset(&m_fpr, 0, sizeof m_fpr); // elf-core yet to support ReadFPR() lldb::ProcessSP base = CalculateProcess(); if (base.get()->GetPluginName() == ProcessElfCore::GetPluginNameStatic()) return; } RegisterContextPOSIX_arm::~RegisterContextPOSIX_arm() { } void RegisterContextPOSIX_arm::Invalidate() { } void RegisterContextPOSIX_arm::InvalidateAllRegisters() { } unsigned RegisterContextPOSIX_arm::GetRegisterOffset(unsigned reg) { assert(reg < m_reg_info.num_registers && "Invalid register number."); return GetRegisterInfo()[reg].byte_offset; } unsigned RegisterContextPOSIX_arm::GetRegisterSize(unsigned reg) { assert(reg < m_reg_info.num_registers && "Invalid register number."); return GetRegisterInfo()[reg].byte_size; } size_t RegisterContextPOSIX_arm::GetRegisterCount() { size_t num_registers = m_reg_info.num_gpr_registers + m_reg_info.num_fpr_registers; return num_registers; } size_t RegisterContextPOSIX_arm::GetGPRSize() { return m_register_info_ap->GetGPRSize (); } const lldb_private::RegisterInfo * RegisterContextPOSIX_arm::GetRegisterInfo() { // Commonly, this method is overridden and g_register_infos is copied and specialized. // So, use GetRegisterInfo() rather than g_register_infos in this scope. return m_register_info_ap->GetRegisterInfo (); } const lldb_private::RegisterInfo * RegisterContextPOSIX_arm::GetRegisterInfoAtIndex(size_t reg) { if (reg < m_reg_info.num_registers) return &GetRegisterInfo()[reg]; else return NULL; } size_t RegisterContextPOSIX_arm::GetRegisterSetCount() { size_t sets = 0; for (size_t set = 0; set < k_num_register_sets; ++set) { if (IsRegisterSetAvailable(set)) ++sets; } return sets; } const lldb_private::RegisterSet * RegisterContextPOSIX_arm::GetRegisterSet(size_t set) { if (IsRegisterSetAvailable(set)) { switch (m_register_info_ap->m_target_arch.GetMachine()) { case llvm::Triple::arm: return &g_reg_sets_arm[set]; default: assert(false && "Unhandled target architecture."); return NULL; } } return NULL; } const char * RegisterContextPOSIX_arm::GetRegisterName(unsigned reg) { assert(reg < m_reg_info.num_registers && "Invalid register offset."); return GetRegisterInfo()[reg].name; } lldb::ByteOrder RegisterContextPOSIX_arm::GetByteOrder() { // Get the target process whose privileged thread was used for the register read. lldb::ByteOrder byte_order = lldb::eByteOrderInvalid; lldb_private::Process *process = CalculateProcess().get(); if (process) byte_order = process->GetByteOrder(); return byte_order; } bool RegisterContextPOSIX_arm::IsRegisterSetAvailable(size_t set_index) { return set_index < k_num_register_sets; } // Used when parsing DWARF and EH frame information and any other // object file sections that contain register numbers in them. uint32_t RegisterContextPOSIX_arm::ConvertRegisterKindToRegisterNumber(lldb::RegisterKind kind, uint32_t num) { const uint32_t num_regs = GetRegisterCount(); assert (kind < lldb::kNumRegisterKinds); for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) { const lldb_private::RegisterInfo *reg_info = GetRegisterInfoAtIndex (reg_idx); if (reg_info->kinds[kind] == num) return reg_idx; } return LLDB_INVALID_REGNUM; } <|endoftext|>
<commit_before>/* Copyright 2009 Klarälvdalens Datakonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "importjob.h" #include "kmfolder.h" #include "folderutil.h" #include <kdebug.h> #include <kzip.h> #include <ktar.h> #include <klocale.h> #include <kmessagebox.h> #include <kmimetype.h> #include <qwidget.h> #include <qtimer.h> using namespace KMail; ImportJob::ImportJob( QWidget *parentWidget ) : QObject( parentWidget ), mArchive( 0 ), mRootFolder( 0 ), mParentWidget( parentWidget ), mNumberOfImportedMessages( 0 ), mCurrentFolder( 0 ) { } ImportJob::~ImportJob() { if ( mArchive && mArchive->isOpen() ) { mArchive->close(); } delete mArchive; mArchive = 0; } void ImportJob::setFile( const KUrl &archiveFile ) { mArchiveFile = archiveFile; } void ImportJob::setRootFolder( KMFolder *rootFolder ) { mRootFolder = rootFolder; } void ImportJob::finish() { kDebug(5006) << "Finished import job."; QString text = i18n( "Importing the archive file '%1' into the folder '%2' succeeded.", mArchiveFile.path(), mRootFolder->name() ); text += '\n' + i18n( "%1 messages were imported.", mNumberOfImportedMessages ); KMessageBox::information( mParentWidget, text, i18n( "Import finished." ) ); deleteLater(); } void ImportJob::abort( const QString &errorMessage ) { QString text = i18n( "Failed to import the archive into folder '%1'.", mRootFolder->name() ); text += '\n' + errorMessage; KMessageBox::sorry( mParentWidget, text, i18n( "Importing archive failed." ) ); deleteLater(); } KMFolder * ImportJob::createSubFolder( KMFolder *parent, const QString &folderName ) { if ( !parent->createChildFolder() ) { abort( i18n( "Unable to create subfolder for folder '%1'.", parent->name() ) ); return 0; } KMFolder *newFolder = FolderUtil::createSubFolder( parent, parent->child(), folderName, QString(), KMFolderTypeMaildir ); if ( !newFolder ) { abort( i18n( "Unable to create subfolder for folder '%1'.", parent->name() ) ); return 0; } else return newFolder; } void ImportJob::enqueueMessages( const KArchiveDirectory *dir, KMFolder *folder ) { const KArchiveDirectory *messageDir = dynamic_cast<const KArchiveDirectory*>( dir->entry( "cur" ) ); if ( messageDir ) { Messages messagesToQueue; messagesToQueue.parent = folder; const QStringList entries = messageDir->entries(); for ( int i = 0; i < entries.size(); i++ ) { const KArchiveEntry *entry = messageDir->entry( entries[i] ); Q_ASSERT( entry ); if ( entry->isDirectory() ) { kWarning(5006) << "Unexpected subdirectory in archive folder " << dir->name(); } else { kDebug(5006) << "Queueing message " << entry->name(); const KArchiveFile *file = static_cast<const KArchiveFile*>( entry ); messagesToQueue.files.append( file ); } } mQueuedMessages.append( messagesToQueue ); } else { kWarning(5006) << "No 'cur' subdirectory for archive directory " << dir->name(); } } void ImportJob::importNextMessage() { if ( mQueuedMessages.isEmpty() ) { kDebug(5006) << "Processed all messages in the queue."; if ( mCurrentFolder ) { mCurrentFolder->close( "ImportJob" ); } mCurrentFolder = 0; importNextDirectory(); return; } Messages &messages = mQueuedMessages.front(); if ( messages.files.isEmpty() ) { mQueuedMessages.pop_front(); importNextMessage(); return; } KMFolder *folder = messages.parent; if ( folder != mCurrentFolder ) { kDebug(5006) << "Processed all messages in the current folder of the queue."; if ( mCurrentFolder ) { mCurrentFolder->close( "ImportJob" ); } mCurrentFolder = folder; if ( mCurrentFolder->open( "ImportJob" ) != 0 ) { abort( i18n( "Unable to open folder '%1'.", mCurrentFolder->name() ) ); return; } kDebug(5006) << "Current folder of queue is now: " << mCurrentFolder->name(); } const KArchiveFile *file = messages.files.first(); Q_ASSERT( file ); messages.files.removeFirst(); KMMessage *newMessage = new KMMessage(); newMessage->fromString( file->data() ); int retIndex; if ( mCurrentFolder->addMsg( newMessage, &retIndex ) != 0 ) { abort( i18n( "Failed to add a message to the folder '%1'.", mCurrentFolder->name() ) ); return; } else { mNumberOfImportedMessages++; kDebug(5006) << "Added message with subject " /*<< newMessage->subject()*/ // < this causes a pure virtual method to be called... << " to folder " << mCurrentFolder->name() << " at index " << retIndex; } QTimer::singleShot( 0, this, SLOT( importNextMessage() ) ); } void ImportJob::importNextDirectory() { if ( mQueuedDirectories.isEmpty() ) { finish(); return; } Folder folder = mQueuedDirectories.first(); KMFolder *currentFolder = folder.parent; mQueuedDirectories.pop_front(); kDebug(5006) << "Working on directory " << folder.archiveDir->name(); QStringList entries = folder.archiveDir->entries(); for ( int i = 0; i < entries.size(); i++ ) { const KArchiveEntry *entry = folder.archiveDir->entry( entries[i] ); Q_ASSERT( entry ); kDebug(5006) << "Queueing entry " << entry->name(); if ( entry->isDirectory() ) { const KArchiveDirectory *dir = static_cast<const KArchiveDirectory*>( entry ); if ( !dir->name().startsWith( QLatin1String( "." ) ) ) { kDebug(5006) << "Queueing messages in folder " << entry->name(); KMFolder *subFolder = createSubFolder( currentFolder, entry->name() ); if ( !subFolder ) return; enqueueMessages( dir, subFolder ); const QString dirName = '.' + entries[i] + ".directory"; if ( entries.contains( dirName ) ) { Q_ASSERT( folder.archiveDir->entry( dirName )->isDirectory() ); Q_ASSERT( folder.archiveDir->entry( dirName )->name() == dirName ); Folder newFolder; newFolder.archiveDir = static_cast<const KArchiveDirectory*>( folder.archiveDir->entry( dirName ) ); newFolder.parent = subFolder; kDebug(5006) << "Enqueueing directory " << newFolder.archiveDir->name(); mQueuedDirectories.push_back( newFolder ); } } } } importNextMessage(); } // TODO: // BUGS: // Online IMAP can fail spectacular, for example when cancelling upload // Online IMAP: Inform that messages are still being uploaded on finish()! void ImportJob::start() { Q_ASSERT( mRootFolder ); Q_ASSERT( mArchiveFile.isValid() ); KMimeType::Ptr mimeType = KMimeType::findByUrl( mArchiveFile, 0, true /* local file */ ); if ( !mimeType->patterns().filter( "tar", Qt::CaseInsensitive ).isEmpty() ) mArchive = new KTar( mArchiveFile.path() ); else if ( !mimeType->patterns().filter( "zip", Qt::CaseInsensitive ).isEmpty() ) mArchive = new KZip( mArchiveFile.path() ); else { abort( i18n( "The file '%1' does not appear to be a valid archive.", mArchiveFile.path() ) ); return; } if ( !mArchive->open( QIODevice::ReadOnly ) ) { abort( i18n( "Unable to open archive file '%1'", mArchiveFile.path() ) ); return; } Folder nextFolder; nextFolder.archiveDir = mArchive->directory(); nextFolder.parent = mRootFolder; mQueuedDirectories.push_back( nextFolder ); importNextDirectory(); } #include "importjob.moc" <commit_msg>SVN_MERGE Merged revisions 1045943 via svnmerge from svn+ssh://tmcguire@svn.kde.org/home/kde/branches/kdepim/enterprise4/kdepim<commit_after>/* Copyright 2009 Klarälvdalens Datakonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "importjob.h" #include "kmfolder.h" #include "folderutil.h" #include <kdebug.h> #include <kzip.h> #include <ktar.h> #include <klocale.h> #include <kmessagebox.h> #include <kmimetype.h> #include <qwidget.h> #include <qtimer.h> using namespace KMail; ImportJob::ImportJob( QWidget *parentWidget ) : QObject( parentWidget ), mArchive( 0 ), mRootFolder( 0 ), mParentWidget( parentWidget ), mNumberOfImportedMessages( 0 ), mCurrentFolder( 0 ) { } ImportJob::~ImportJob() { if ( mArchive && mArchive->isOpen() ) { mArchive->close(); } delete mArchive; mArchive = 0; } void ImportJob::setFile( const KUrl &archiveFile ) { mArchiveFile = archiveFile; } void ImportJob::setRootFolder( KMFolder *rootFolder ) { mRootFolder = rootFolder; } void ImportJob::finish() { kDebug(5006) << "Finished import job."; QString text = i18n( "Importing the archive file '%1' into the folder '%2' succeeded.", mArchiveFile.path(), mRootFolder->name() ); text += '\n' + i18n( "%1 messages were imported.", mNumberOfImportedMessages ); KMessageBox::information( mParentWidget, text, i18n( "Import finished." ) ); deleteLater(); } void ImportJob::abort( const QString &errorMessage ) { QString text = i18n( "Failed to import the archive into folder '%1'.", mRootFolder->name() ); text += '\n' + errorMessage; KMessageBox::sorry( mParentWidget, text, i18n( "Importing archive failed." ) ); deleteLater(); } KMFolder * ImportJob::createSubFolder( KMFolder *parent, const QString &folderName ) { if ( !parent->createChildFolder() ) { abort( i18n( "Unable to create subfolder for folder '%1'.", parent->name() ) ); return 0; } KMFolder *newFolder = FolderUtil::createSubFolder( parent, parent->child(), folderName, QString(), KMFolderTypeMaildir ); if ( !newFolder ) { abort( i18n( "Unable to create subfolder for folder '%1'.", parent->name() ) ); return 0; } else return newFolder; } void ImportJob::enqueueMessages( const KArchiveDirectory *dir, KMFolder *folder ) { const KArchiveDirectory *messageDir = dynamic_cast<const KArchiveDirectory*>( dir->entry( "cur" ) ); if ( messageDir ) { Messages messagesToQueue; messagesToQueue.parent = folder; const QStringList entries = messageDir->entries(); for ( int i = 0; i < entries.size(); i++ ) { const KArchiveEntry *entry = messageDir->entry( entries[i] ); Q_ASSERT( entry ); if ( entry->isDirectory() ) { kWarning(5006) << "Unexpected subdirectory in archive folder " << dir->name(); } else { kDebug(5006) << "Queueing message " << entry->name(); const KArchiveFile *file = static_cast<const KArchiveFile*>( entry ); messagesToQueue.files.append( file ); } } mQueuedMessages.append( messagesToQueue ); } else { kWarning(5006) << "No 'cur' subdirectory for archive directory " << dir->name(); } } void ImportJob::importNextMessage() { if ( mQueuedMessages.isEmpty() ) { kDebug(5006) << "Processed all messages in the queue."; if ( mCurrentFolder ) { mCurrentFolder->close( "ImportJob" ); } mCurrentFolder = 0; importNextDirectory(); return; } Messages &messages = mQueuedMessages.front(); if ( messages.files.isEmpty() ) { mQueuedMessages.pop_front(); importNextMessage(); return; } KMFolder *folder = messages.parent; if ( folder != mCurrentFolder ) { kDebug(5006) << "Processed all messages in the current folder of the queue."; if ( mCurrentFolder ) { mCurrentFolder->close( "ImportJob" ); } mCurrentFolder = folder; if ( mCurrentFolder->open( "ImportJob" ) != 0 ) { abort( i18n( "Unable to open folder '%1'.", mCurrentFolder->name() ) ); return; } kDebug(5006) << "Current folder of queue is now: " << mCurrentFolder->name(); } const KArchiveFile *file = messages.files.first(); Q_ASSERT( file ); messages.files.removeFirst(); KMMessage *newMessage = new KMMessage(); newMessage->fromString( file->data(), true /* setStatus */ ); int retIndex; if ( mCurrentFolder->addMsg( newMessage, &retIndex ) != 0 ) { abort( i18n( "Failed to add a message to the folder '%1'.", mCurrentFolder->name() ) ); return; } else { mNumberOfImportedMessages++; kDebug(5006) << "Added message with subject " /*<< newMessage->subject()*/ // < this causes a pure virtual method to be called... << " to folder " << mCurrentFolder->name() << " at index " << retIndex; } QTimer::singleShot( 0, this, SLOT( importNextMessage() ) ); } void ImportJob::importNextDirectory() { if ( mQueuedDirectories.isEmpty() ) { finish(); return; } Folder folder = mQueuedDirectories.first(); KMFolder *currentFolder = folder.parent; mQueuedDirectories.pop_front(); kDebug(5006) << "Working on directory " << folder.archiveDir->name(); QStringList entries = folder.archiveDir->entries(); for ( int i = 0; i < entries.size(); i++ ) { const KArchiveEntry *entry = folder.archiveDir->entry( entries[i] ); Q_ASSERT( entry ); kDebug(5006) << "Queueing entry " << entry->name(); if ( entry->isDirectory() ) { const KArchiveDirectory *dir = static_cast<const KArchiveDirectory*>( entry ); if ( !dir->name().startsWith( QLatin1String( "." ) ) ) { kDebug(5006) << "Queueing messages in folder " << entry->name(); KMFolder *subFolder = createSubFolder( currentFolder, entry->name() ); if ( !subFolder ) return; enqueueMessages( dir, subFolder ); const QString dirName = '.' + entries[i] + ".directory"; if ( entries.contains( dirName ) ) { Q_ASSERT( folder.archiveDir->entry( dirName )->isDirectory() ); Q_ASSERT( folder.archiveDir->entry( dirName )->name() == dirName ); Folder newFolder; newFolder.archiveDir = static_cast<const KArchiveDirectory*>( folder.archiveDir->entry( dirName ) ); newFolder.parent = subFolder; kDebug(5006) << "Enqueueing directory " << newFolder.archiveDir->name(); mQueuedDirectories.push_back( newFolder ); } } } } importNextMessage(); } // TODO: // BUGS: // Online IMAP can fail spectacular, for example when cancelling upload // Online IMAP: Inform that messages are still being uploaded on finish()! void ImportJob::start() { Q_ASSERT( mRootFolder ); Q_ASSERT( mArchiveFile.isValid() ); KMimeType::Ptr mimeType = KMimeType::findByUrl( mArchiveFile, 0, true /* local file */ ); if ( !mimeType->patterns().filter( "tar", Qt::CaseInsensitive ).isEmpty() ) mArchive = new KTar( mArchiveFile.path() ); else if ( !mimeType->patterns().filter( "zip", Qt::CaseInsensitive ).isEmpty() ) mArchive = new KZip( mArchiveFile.path() ); else { abort( i18n( "The file '%1' does not appear to be a valid archive.", mArchiveFile.path() ) ); return; } if ( !mArchive->open( QIODevice::ReadOnly ) ) { abort( i18n( "Unable to open archive file '%1'", mArchiveFile.path() ) ); return; } Folder nextFolder; nextFolder.archiveDir = mArchive->directory(); nextFolder.parent = mRootFolder; mQueuedDirectories.push_back( nextFolder ); importNextDirectory(); } #include "importjob.moc" <|endoftext|>
<commit_before>#include "Board.h" #include "Pawn.h" #include "Rook.h" #include "Knight.h" #include "Bishop.h" #include "Queen.h" #include "King.h" namespace Chess { Board::Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { pieces[x][y] = nullptr; } } // Black pawns for (int x = 0; x < 8; x++) { pieces[x][6] = new Pawn(Position(x, 6), false); } // White pawns for (int x = 0; x < 8; x++) { pieces[x][1] = new Pawn(Position(x, 1), true); } // Rooks pieces[0][7] = new Rook(Position(0, 7), false); pieces[7][7] = new Rook(Position(7, 7), false); pieces[0][0] = new Rook(Position(0, 0), true); pieces[7][0] = new Rook(Position(7, 0), true); // Knights pieces[1][7] = new Knight(Position(1, 7), false); pieces[6][7] = new Knight(Position(6, 7), false); pieces[1][0] = new Knight(Position(1, 0), true); pieces[6][0] = new Knight(Position(6, 0), true); // Bishops pieces[2][7] = new Bishop(Position(2, 7), false); pieces[5][7] = new Bishop(Position(5, 7), false); pieces[2][0] = new Bishop(Position(2, 0), true); pieces[5][0] = new Bishop(Position(5, 0), true); // Queens pieces[3][7] = new Queen(Position(3, 7), false); pieces[3][0] = new Queen(Position(3, 0), true); // Kings blackKing = new King(Position(4, 7), false); pieces[4][7] = blackKing; whiteKing = new King(Position(4, 0), true); pieces[4][0] = whiteKing; } Board::~Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { if (pieces[x][y] != nullptr) delete pieces[x][y]; } } } Piece* Board::getPiece(const Position& position) const { return pieces[position.x][position.y]; } bool Board::move(const Position& oldPosition, const Position& newPosition) { Piece* piece = getPiece(oldPosition); if (piece != nullptr) { // Check if the piece is of the right color. if (piece->isWhite() == (turn % 2 == 0)) { // Check if the move is legal. if (piece->isLegal(*this, newPosition)) { pieces[oldPosition.x][oldPosition.y] = nullptr; // Delete captured piece. if (pieces[newPosition.x][newPosition.y] != nullptr) delete pieces[newPosition.x][newPosition.y]; // TODO: En passant. pieces[newPosition.x][newPosition.y] = piece; piece->move(newPosition); // TODO: Castling, promotion, pawn double move. turn++; return true; } } } return false; } }<commit_msg>Added state transition.<commit_after>#include "Board.h" #include "Pawn.h" #include "Rook.h" #include "Knight.h" #include "Bishop.h" #include "Queen.h" #include "King.h" namespace Chess { Board::Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { pieces[x][y] = nullptr; } } // Black pawns for (int x = 0; x < 8; x++) { pieces[x][6] = new Pawn(Position(x, 6), false); } // White pawns for (int x = 0; x < 8; x++) { pieces[x][1] = new Pawn(Position(x, 1), true); } // Rooks pieces[0][7] = new Rook(Position(0, 7), false); pieces[7][7] = new Rook(Position(7, 7), false); pieces[0][0] = new Rook(Position(0, 0), true); pieces[7][0] = new Rook(Position(7, 0), true); // Knights pieces[1][7] = new Knight(Position(1, 7), false); pieces[6][7] = new Knight(Position(6, 7), false); pieces[1][0] = new Knight(Position(1, 0), true); pieces[6][0] = new Knight(Position(6, 0), true); // Bishops pieces[2][7] = new Bishop(Position(2, 7), false); pieces[5][7] = new Bishop(Position(5, 7), false); pieces[2][0] = new Bishop(Position(2, 0), true); pieces[5][0] = new Bishop(Position(5, 0), true); // Queens pieces[3][7] = new Queen(Position(3, 7), false); pieces[3][0] = new Queen(Position(3, 0), true); // Kings blackKing = new King(Position(4, 7), false); pieces[4][7] = blackKing; whiteKing = new King(Position(4, 0), true); pieces[4][0] = whiteKing; } Board::~Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { if (pieces[x][y] != nullptr) delete pieces[x][y]; } } } Piece* Board::getPiece(const Position& position) const { return pieces[position.x][position.y]; } bool Board::move(const Position& oldPosition, const Position& newPosition) { Piece* piece = getPiece(oldPosition); if (piece != nullptr) { // Check if the piece is of the right color. if (piece->isWhite() == (turn % 2 == 0)) { state = GameState::WHITEPLAYS; // Check if the move is legal. if (piece->isLegal(*this, newPosition)) { pieces[oldPosition.x][oldPosition.y] = nullptr; // Delete captured piece. if (pieces[newPosition.x][newPosition.y] != nullptr) delete pieces[newPosition.x][newPosition.y]; // TODO: En passant. pieces[newPosition.x][newPosition.y] = piece; piece->move(newPosition); // TODO: Castling, promotion, pawn double move. turn++; return true; } } else state = GameState::BLACKPLAYS; } return false; } }<|endoftext|>
<commit_before>#include "Board.h" #include "Pawn.h" #include "Rook.h" #include "Knight.h" #include "Bishop.h" #include "Queen.h" #include "King.h" #include <iostream> #include <sstream> namespace Chess { Board::Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { pieces[x][y] = nullptr; } } // Black pawns for (int x = 0; x < 8; x++) { pieces[x][6] = new Pawn(Position(x, 6), false); } // White pawns for (int x = 0; x < 8; x++) { pieces[x][1] = new Pawn(Position(x, 1), true); } // Rooks pieces[0][7] = new Rook(Position(0, 7), false); pieces[7][7] = new Rook(Position(7, 7), false); pieces[0][0] = new Rook(Position(0, 0), true); pieces[7][0] = new Rook(Position(7, 0), true); // Knights pieces[1][7] = new Knight(Position(1, 7), false); pieces[6][7] = new Knight(Position(6, 7), false); pieces[1][0] = new Knight(Position(1, 0), true); pieces[6][0] = new Knight(Position(6, 0), true); // Bishops pieces[2][7] = new Bishop(Position(2, 7), false); pieces[5][7] = new Bishop(Position(5, 7), false); pieces[2][0] = new Bishop(Position(2, 0), true); pieces[5][0] = new Bishop(Position(5, 0), true); // Queens pieces[3][7] = new Queen(Position(3, 7), false); pieces[3][0] = new Queen(Position(3, 0), true); // Kings pieces[4][7] = new King(Position(4, 7), false); pieces[4][0] = new King(Position(4, 0), true); addBoardToMap(); } Board::~Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { if (pieces[x][y] != nullptr) delete pieces[x][y]; } } } GameState Board::getState() const { return state; } Piece* Board::getPiece(const Position& position) const { return pieces[position.x][position.y]; } bool Board::mustPromote() { return needsToPromote; } bool Board::move(const Position& oldPosition, const Position& newPosition) { Piece* piece = getPiece(oldPosition); Piece* targetPiece = getPiece(newPosition); if (piece != nullptr) { // Check if the piece is of the right color. if (piece->isWhite() == (turn % 2 == 0)) { halfMovesSinceCapture++; // Check if the move is legal. if (piece->isLegal(*this, newPosition)) { pieces[oldPosition.x][oldPosition.y] = nullptr; // En passant. if (newPosition == enPassantPossible && (piece->notation() == 'p' || piece->notation() == 'P')){ if (piece->isWhite()) { delete pieces[newPosition.x][newPosition.y - 1]; pieces[newPosition.x][newPosition.y - 1] = nullptr; halfMovesSinceCapture = 0; } else { delete pieces[newPosition.x][newPosition.y + 1]; pieces[newPosition.x][newPosition.y + 1] = nullptr; halfMovesSinceCapture = 0; } } // Castling if (piece->notation() == 'k' || piece->notation() == 'K') { if (newPosition.x - oldPosition.x == 2){ Piece* tempPiece = getPiece(Position(7, newPosition.y)); pieces[7][newPosition.y] = nullptr; pieces[5][newPosition.y] = tempPiece; tempPiece->move(Position(5, newPosition.y)); } else if (newPosition.x - oldPosition.x == -2) { Piece* tempPiece = getPiece(Position(0, newPosition.y)); pieces[0][newPosition.y] = nullptr; pieces[3][newPosition.y] = tempPiece; tempPiece->move(Position(3, newPosition.y)); } } // Delete captured enemy piece. if (pieces[newPosition.x][newPosition.y] != nullptr){ delete pieces[newPosition.x][newPosition.y]; halfMovesSinceCapture = 0; } // Update pieces and piece position pieces[newPosition.x][newPosition.y] = piece; if (piece->notation() == 'p' || piece->notation() == 'P') halfMovesSinceCapture = 0; piece->move(newPosition); // Promote pawns if(newPosition.y == 7 || newPosition.y == 0){ if (piece->notation() == 'p' || piece->notation() == 'P'){ needsToPromote = true; } } if ( (piece->notation() == 'p' || piece->notation() == 'P') ){ if (abs(oldPosition.y - newPosition.y) == 2) { if (piece->notation() == 'p') enPassantPossible = Position(newPosition.x, newPosition.y + 1); else if (piece->notation() == 'P') enPassantPossible = Position(newPosition.x, newPosition.y - 1); } } else { enPassantPossible = Position(-1, -1); } printf("En passant possible at:\n X:%d, Y:%d\n", enPassantPossible.x, enPassantPossible.y); turn++; if (state == GameState::BLACKPLAYS) state = GameState::WHITEPLAYS; else state = GameState::BLACKPLAYS; std::string tempstring = toFENString(true); std::cout << tempstring << '\n'; addBoardToMap(); if(isThreeFoldRepitition()) state = GameState::DRAW; if (isFiftyMoveSincePawnOrCapture()) state = GameState::DRAW; if (!sufficientMaterial()) state = GameState::DRAW; checkWin(); return true; } } } return false; } bool Board::willLeaveKingChecked(const Position& oldPosition, const Position& newPosition) { Piece* oldPiece = getPiece(oldPosition); Piece* newPiece = getPiece(newPosition); Piece* piece; switch (oldPiece->notation()) { case 'Q': case 'q': piece = new Queen(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'K': case 'k': piece = new King(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'P': case 'p': piece = new Pawn(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'R': case 'r': piece = new Rook(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'B': case 'b': piece = new Bishop(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'N': case 'n': piece = new Knight(oldPiece->getPosition(), oldPiece->isWhite()); break; } pieces[newPosition.x][newPosition.y] = piece; piece->move(newPosition); pieces[oldPosition.x][oldPosition.y] = nullptr; King* king = getKing((turn % 2 == 0)); bool checked = king->isChecked(*this); delete piece; pieces[newPosition.x][newPosition.y] = newPiece; pieces[oldPosition.x][oldPosition.y] = oldPiece; return checked; } void Board::promotePawn(Piece* pawn, PromoteTypes type) { Position position = pawn->getPosition(); bool white = pawn->isWhite(); delete pawn; switch (type) { case PromoteTypes::QUEEN: pieces[position.x][position.y] = new Queen(position, white); break; case PromoteTypes::ROOK: pieces[position.x][position.y] = new Rook(position, white); break; case PromoteTypes::BISHOP: pieces[position.x][position.y] = new Bishop(position, white); break; case PromoteTypes::KNIGHT: pieces[position.x][position.y] = new Knight(position, white); break; } checkWin(); needsToPromote = false; } void Board::addBoardToMap() { std::string tempstring = toFENString(false); if (previousBoards.find(tempstring) == previousBoards.end()) { previousBoards[tempstring] = 0; } else{ previousBoards[tempstring] += 1; } } std::string Board::toFENString(bool addExtraData) const { std::string tempstring; int emptyCounter = 0; for (int y = 7; y >= 0; y--) { for (int x = 0; x < 8; x++){ if (pieces[x][y] == nullptr) emptyCounter++; else { if (emptyCounter != 0) tempstring += std::to_string(emptyCounter); tempstring.append(1, pieces[x][y]->notation()); emptyCounter = 0; } } if (emptyCounter != 0) { tempstring += std::to_string(emptyCounter); emptyCounter = 0; } tempstring += '/'; } tempstring += ' '; // Who played the turn? if (state == GameState::BLACKPLAYS) tempstring += "w"; else tempstring += "b"; tempstring += ' ' + std::to_string(enPassantPossible.x) + '.' + std::to_string(enPassantPossible.y); if (addExtraData) { // Number of half turns since last capture or pawn move. tempstring += ' ' + std::to_string(halfMovesSinceCapture) + ' '; // Number of full moves. tempstring += std::to_string((turn+1) / 2); tempstring += '#'; } return tempstring; } bool Board::isThreeFoldRepitition() { return previousBoards[toFENString(false)] == 3; } bool Board::isFiftyMoveSincePawnOrCapture() const { return halfMovesSinceCapture >= 100; } void Board::checkWin() { bool white = (state == GameState::WHITEPLAYS); bool canMove = false; for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { Piece* piece = getPiece(Position(x, y)); if (piece != nullptr && piece->isWhite() == white) { if (!piece->legalMoves(*this).empty()) { canMove = true; break; } } } } if (!canMove) { if (getKing(white)->isChecked(*this)) { if (white) state = GameState::BLACKWIN; else state = GameState::WHITEWIN; } else { state = GameState::DRAW; } } } bool Board::sufficientMaterial() const { // Get the material on the board. int pieceTypes[6] = { 0 }; for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { Piece* piece = getPiece(Position(x, y)); if (piece != nullptr) { switch (piece->notation()) { case 'Q': case 'q': pieceTypes[0]++; break; case 'P': case 'p': pieceTypes[1]++; break; case 'R': case 'r': pieceTypes[2]++; break; case 'N': case 'n': pieceTypes[3]++; break; case 'B': case 'b': pieceTypes[((x + y) % 2 == 0) ? 4 : 5]++; break; } } } } // If there's a queen, pawn or rook on the board, there is sufficient material. if (pieceTypes[0] > 0 || pieceTypes[1] > 0 || pieceTypes[2] > 0) return true; // If there are 2 or more knights on the board, there is sufficient material. if (pieceTypes[3] > 1) return true; // If there are pieces from 2 or more categories (knight, bishop on light square, bishop on dark square), there is sufficient material. if ((pieceTypes[3] > 0) + (pieceTypes[4] > 0) + (pieceTypes[5] > 0) >= 2) return true; return false; } King* Board::getKing(bool white) const { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { Piece* piece = getPiece(Position(x, y)); if (piece != nullptr && piece->notation() == (white ? 'K' : 'k')) return dynamic_cast<King*>(piece); } } return nullptr; } Position Board::getEnPassantPossible()const{ return enPassantPossible; } }<commit_msg>Removed console printouts<commit_after>#include "Board.h" #include "Pawn.h" #include "Rook.h" #include "Knight.h" #include "Bishop.h" #include "Queen.h" #include "King.h" #include <iostream> #include <sstream> namespace Chess { Board::Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { pieces[x][y] = nullptr; } } // Black pawns for (int x = 0; x < 8; x++) { pieces[x][6] = new Pawn(Position(x, 6), false); } // White pawns for (int x = 0; x < 8; x++) { pieces[x][1] = new Pawn(Position(x, 1), true); } // Rooks pieces[0][7] = new Rook(Position(0, 7), false); pieces[7][7] = new Rook(Position(7, 7), false); pieces[0][0] = new Rook(Position(0, 0), true); pieces[7][0] = new Rook(Position(7, 0), true); // Knights pieces[1][7] = new Knight(Position(1, 7), false); pieces[6][7] = new Knight(Position(6, 7), false); pieces[1][0] = new Knight(Position(1, 0), true); pieces[6][0] = new Knight(Position(6, 0), true); // Bishops pieces[2][7] = new Bishop(Position(2, 7), false); pieces[5][7] = new Bishop(Position(5, 7), false); pieces[2][0] = new Bishop(Position(2, 0), true); pieces[5][0] = new Bishop(Position(5, 0), true); // Queens pieces[3][7] = new Queen(Position(3, 7), false); pieces[3][0] = new Queen(Position(3, 0), true); // Kings pieces[4][7] = new King(Position(4, 7), false); pieces[4][0] = new King(Position(4, 0), true); addBoardToMap(); } Board::~Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { if (pieces[x][y] != nullptr) delete pieces[x][y]; } } } GameState Board::getState() const { return state; } Piece* Board::getPiece(const Position& position) const { return pieces[position.x][position.y]; } bool Board::mustPromote() { return needsToPromote; } bool Board::move(const Position& oldPosition, const Position& newPosition) { Piece* piece = getPiece(oldPosition); Piece* targetPiece = getPiece(newPosition); if (piece != nullptr) { // Check if the piece is of the right color. if (piece->isWhite() == (turn % 2 == 0)) { halfMovesSinceCapture++; // Check if the move is legal. if (piece->isLegal(*this, newPosition)) { pieces[oldPosition.x][oldPosition.y] = nullptr; // En passant. if (newPosition == enPassantPossible && (piece->notation() == 'p' || piece->notation() == 'P')){ if (piece->isWhite()) { delete pieces[newPosition.x][newPosition.y - 1]; pieces[newPosition.x][newPosition.y - 1] = nullptr; halfMovesSinceCapture = 0; } else { delete pieces[newPosition.x][newPosition.y + 1]; pieces[newPosition.x][newPosition.y + 1] = nullptr; halfMovesSinceCapture = 0; } } // Castling if (piece->notation() == 'k' || piece->notation() == 'K') { if (newPosition.x - oldPosition.x == 2){ Piece* tempPiece = getPiece(Position(7, newPosition.y)); pieces[7][newPosition.y] = nullptr; pieces[5][newPosition.y] = tempPiece; tempPiece->move(Position(5, newPosition.y)); } else if (newPosition.x - oldPosition.x == -2) { Piece* tempPiece = getPiece(Position(0, newPosition.y)); pieces[0][newPosition.y] = nullptr; pieces[3][newPosition.y] = tempPiece; tempPiece->move(Position(3, newPosition.y)); } } // Delete captured enemy piece. if (pieces[newPosition.x][newPosition.y] != nullptr){ delete pieces[newPosition.x][newPosition.y]; halfMovesSinceCapture = 0; } // Update pieces and piece position pieces[newPosition.x][newPosition.y] = piece; if (piece->notation() == 'p' || piece->notation() == 'P') halfMovesSinceCapture = 0; piece->move(newPosition); // Promote pawns if(newPosition.y == 7 || newPosition.y == 0){ if (piece->notation() == 'p' || piece->notation() == 'P'){ needsToPromote = true; } } if ( (piece->notation() == 'p' || piece->notation() == 'P') ){ if (abs(oldPosition.y - newPosition.y) == 2) { if (piece->notation() == 'p') enPassantPossible = Position(newPosition.x, newPosition.y + 1); else if (piece->notation() == 'P') enPassantPossible = Position(newPosition.x, newPosition.y - 1); } } else { enPassantPossible = Position(-1, -1); } turn++; if (state == GameState::BLACKPLAYS) state = GameState::WHITEPLAYS; else state = GameState::BLACKPLAYS; addBoardToMap(); if(isThreeFoldRepitition()) state = GameState::DRAW; if (isFiftyMoveSincePawnOrCapture()) state = GameState::DRAW; if (!sufficientMaterial()) state = GameState::DRAW; checkWin(); return true; } } } return false; } bool Board::willLeaveKingChecked(const Position& oldPosition, const Position& newPosition) { Piece* oldPiece = getPiece(oldPosition); Piece* newPiece = getPiece(newPosition); Piece* piece; switch (oldPiece->notation()) { case 'Q': case 'q': piece = new Queen(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'K': case 'k': piece = new King(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'P': case 'p': piece = new Pawn(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'R': case 'r': piece = new Rook(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'B': case 'b': piece = new Bishop(oldPiece->getPosition(), oldPiece->isWhite()); break; case 'N': case 'n': piece = new Knight(oldPiece->getPosition(), oldPiece->isWhite()); break; } pieces[newPosition.x][newPosition.y] = piece; piece->move(newPosition); pieces[oldPosition.x][oldPosition.y] = nullptr; King* king = getKing((turn % 2 == 0)); bool checked = king->isChecked(*this); delete piece; pieces[newPosition.x][newPosition.y] = newPiece; pieces[oldPosition.x][oldPosition.y] = oldPiece; return checked; } void Board::promotePawn(Piece* pawn, PromoteTypes type) { Position position = pawn->getPosition(); bool white = pawn->isWhite(); delete pawn; switch (type) { case PromoteTypes::QUEEN: pieces[position.x][position.y] = new Queen(position, white); break; case PromoteTypes::ROOK: pieces[position.x][position.y] = new Rook(position, white); break; case PromoteTypes::BISHOP: pieces[position.x][position.y] = new Bishop(position, white); break; case PromoteTypes::KNIGHT: pieces[position.x][position.y] = new Knight(position, white); break; } checkWin(); needsToPromote = false; } void Board::addBoardToMap() { std::string tempstring = toFENString(false); if (previousBoards.find(tempstring) == previousBoards.end()) { previousBoards[tempstring] = 0; } else{ previousBoards[tempstring] += 1; } } std::string Board::toFENString(bool addExtraData) const { std::string tempstring; int emptyCounter = 0; for (int y = 7; y >= 0; y--) { for (int x = 0; x < 8; x++){ if (pieces[x][y] == nullptr) emptyCounter++; else { if (emptyCounter != 0) tempstring += std::to_string(emptyCounter); tempstring.append(1, pieces[x][y]->notation()); emptyCounter = 0; } } if (emptyCounter != 0) { tempstring += std::to_string(emptyCounter); emptyCounter = 0; } tempstring += '/'; } tempstring += ' '; // Who played the turn? if (state == GameState::BLACKPLAYS) tempstring += "w"; else tempstring += "b"; tempstring += ' ' + std::to_string(enPassantPossible.x) + '.' + std::to_string(enPassantPossible.y); if (addExtraData) { // Number of half turns since last capture or pawn move. tempstring += ' ' + std::to_string(halfMovesSinceCapture) + ' '; // Number of full moves. tempstring += std::to_string((turn+1) / 2); tempstring += '#'; } return tempstring; } bool Board::isThreeFoldRepitition() { return previousBoards[toFENString(false)] == 3; } bool Board::isFiftyMoveSincePawnOrCapture() const { return halfMovesSinceCapture >= 100; } void Board::checkWin() { bool white = (state == GameState::WHITEPLAYS); bool canMove = false; for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { Piece* piece = getPiece(Position(x, y)); if (piece != nullptr && piece->isWhite() == white) { if (!piece->legalMoves(*this).empty()) { canMove = true; break; } } } } if (!canMove) { if (getKing(white)->isChecked(*this)) { if (white) state = GameState::BLACKWIN; else state = GameState::WHITEWIN; } else { state = GameState::DRAW; } } } bool Board::sufficientMaterial() const { // Get the material on the board. int pieceTypes[6] = { 0 }; for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { Piece* piece = getPiece(Position(x, y)); if (piece != nullptr) { switch (piece->notation()) { case 'Q': case 'q': pieceTypes[0]++; break; case 'P': case 'p': pieceTypes[1]++; break; case 'R': case 'r': pieceTypes[2]++; break; case 'N': case 'n': pieceTypes[3]++; break; case 'B': case 'b': pieceTypes[((x + y) % 2 == 0) ? 4 : 5]++; break; } } } } // If there's a queen, pawn or rook on the board, there is sufficient material. if (pieceTypes[0] > 0 || pieceTypes[1] > 0 || pieceTypes[2] > 0) return true; // If there are 2 or more knights on the board, there is sufficient material. if (pieceTypes[3] > 1) return true; // If there are pieces from 2 or more categories (knight, bishop on light square, bishop on dark square), there is sufficient material. if ((pieceTypes[3] > 0) + (pieceTypes[4] > 0) + (pieceTypes[5] > 0) >= 2) return true; return false; } King* Board::getKing(bool white) const { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { Piece* piece = getPiece(Position(x, y)); if (piece != nullptr && piece->notation() == (white ? 'K' : 'k')) return dynamic_cast<King*>(piece); } } return nullptr; } Position Board::getEnPassantPossible()const{ return enPassantPossible; } }<|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN #include "passes/pmgen/ice40_dsp_pm.h" void create_ice40_dsp(ice40_dsp_pm &pm) { auto &st = pm.st_ice40_dsp; #if 1 log("\n"); log("ffA: %s %s %s\n", log_id(st.ffA, "--"), log_id(st.ffAholdmux, "--"), log_id(st.ffArstmux, "--")); log("ffB: %s %s %s\n", log_id(st.ffB, "--"), log_id(st.ffBholdmux, "--"), log_id(st.ffBrstmux, "--")); log("ffCD: %s %s\n", log_id(st.ffCD, "--"), log_id(st.ffCDholdmux, "--")); log("mul: %s\n", log_id(st.mul, "--")); log("ffFJKG: %s\n", log_id(st.ffFJKG, "--")); log("ffH: %s\n", log_id(st.ffH, "--")); log("add: %s\n", log_id(st.add, "--")); log("mux: %s\n", log_id(st.mux, "--")); log("ffO: %s %s %s\n", log_id(st.ffO, "--"), log_id(st.ffOholdmux, "--"), log_id(st.ffOrstmux, "--")); #endif log("Checking %s.%s for iCE40 DSP inference.\n", log_id(pm.module), log_id(st.mul)); if (GetSize(st.sigA) > 16) { log(" input A (%s) is too large (%d > 16).\n", log_signal(st.sigA), GetSize(st.sigA)); return; } if (GetSize(st.sigB) > 16) { log(" input B (%s) is too large (%d > 16).\n", log_signal(st.sigB), GetSize(st.sigB)); return; } if (GetSize(st.sigO) > 33) { log(" adder/accumulator (%s) is too large (%d > 33).\n", log_signal(st.sigO), GetSize(st.sigO)); return; } if (GetSize(st.sigH) > 32) { log(" output (%s) is too large (%d > 32).\n", log_signal(st.sigH), GetSize(st.sigH)); return; } Cell *cell = st.mul; if (cell->type == "$mul") { log(" replacing %s with SB_MAC16 cell.\n", log_id(st.mul->type)); cell = pm.module->addCell(NEW_ID, "\\SB_MAC16"); pm.module->swap_names(cell, st.mul); } else log_assert(cell->type == "\\SB_MAC16"); // SB_MAC16 Input Interface SigSpec A = st.sigA; A.extend_u0(16, st.mul->getParam("\\A_SIGNED").as_bool()); log_assert(GetSize(A) == 16); SigSpec B = st.sigB; B.extend_u0(16, st.mul->getParam("\\B_SIGNED").as_bool()); log_assert(GetSize(B) == 16); SigSpec CD = st.sigCD; if (CD.empty()) CD = RTLIL::Const(0, 32); else log_assert(GetSize(CD) == 32); cell->setPort("\\A", A); cell->setPort("\\B", B); cell->setPort("\\C", CD.extract(16, 16)); cell->setPort("\\D", CD.extract(0, 16)); cell->setParam("\\A_REG", st.ffA ? State::S1 : State::S0); cell->setParam("\\B_REG", st.ffB ? State::S1 : State::S0); cell->setParam("\\C_REG", st.ffCD ? State::S1 : State::S0); cell->setParam("\\D_REG", st.ffCD ? State::S1 : State::S0); SigSpec AHOLD, BHOLD, CDHOLD; if (st.ffAholdmux) AHOLD = st.ffAholdpol ? st.ffAholdmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffAholdmux->getPort("\\S")); else AHOLD = State::S0; if (st.ffBholdmux) BHOLD = st.ffBholdpol ? st.ffBholdmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffBholdmux->getPort("\\S")); else BHOLD = State::S0; if (st.ffCDholdmux) CDHOLD = st.ffCDholdpol ? st.ffCDholdmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffCDholdmux->getPort("\\S")); else CDHOLD = State::S0; cell->setPort("\\AHOLD", AHOLD); cell->setPort("\\BHOLD", BHOLD); cell->setPort("\\CHOLD", CDHOLD); cell->setPort("\\DHOLD", CDHOLD); SigSpec IRSTTOP, IRSTBOT; if (st.ffArstmux) IRSTTOP = st.ffArstpol ? st.ffArstmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffArstmux->getPort("\\S")); else IRSTTOP = State::S0; if (st.ffBrstmux) IRSTBOT = st.ffBrstpol ? st.ffBrstmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffBrstmux->getPort("\\S")); else IRSTBOT = State::S0; cell->setPort("\\IRSTTOP", IRSTTOP); cell->setPort("\\IRSTBOT", IRSTBOT); if (st.clock != SigBit()) { cell->setPort("\\CLK", st.clock); cell->setPort("\\CE", State::S1); cell->setParam("\\NEG_TRIGGER", st.clock_pol ? State::S0 : State::S1); log(" clock: %s (%s)", log_signal(st.clock), st.clock_pol ? "posedge" : "negedge"); if (st.ffA) log(" ffA:%s", log_id(st.ffA)); if (st.ffB) log(" ffB:%s", log_id(st.ffB)); if (st.ffCD) log(" ffCD:%s", log_id(st.ffCD)); if (st.ffFJKG) log(" ffFJKG:%s", log_id(st.ffFJKG)); if (st.ffH) log(" ffH:%s", log_id(st.ffH)); if (st.ffO) log(" ffO:%s", log_id(st.ffO)); log("\n"); } else { cell->setPort("\\CLK", State::S0); cell->setPort("\\CE", State::S0); cell->setParam("\\NEG_TRIGGER", State::S0); } // SB_MAC16 Cascade Interface cell->setPort("\\SIGNEXTIN", State::Sx); cell->setPort("\\SIGNEXTOUT", pm.module->addWire(NEW_ID)); cell->setPort("\\CI", State::Sx); cell->setPort("\\ACCUMCI", State::Sx); cell->setPort("\\ACCUMCO", pm.module->addWire(NEW_ID)); // SB_MAC16 Output Interface SigSpec O = st.sigO; int O_width = GetSize(O); if (O_width == 33) { log_assert(st.add); // If we have a signed multiply-add, then perform sign extension // TODO: Need to check CD[31:16] is sign extension of CD[15:0]? if (st.add->getParam("\\A_SIGNED").as_bool() && st.add->getParam("\\B_SIGNED").as_bool()) pm.module->connect(O[32], O[31]); else cell->setPort("\\CO", O[32]); O.remove(O_width-1); } else cell->setPort("\\CO", pm.module->addWire(NEW_ID)); log_assert(GetSize(O) <= 32); if (GetSize(O) < 32) O.append(pm.module->addWire(NEW_ID, 32-GetSize(O))); cell->setPort("\\O", O); bool accum = false; if (st.add) { accum = (st.ffO && st.add->getPort(st.addAB == "\\A" ? "\\B" : "\\A") == st.sigO); if (accum) log(" accumulator %s (%s)\n", log_id(st.add), log_id(st.add->type)); else log(" adder %s (%s)\n", log_id(st.add), log_id(st.add->type)); cell->setPort("\\ADDSUBTOP", st.add->type == "$add" ? State::S0 : State::S1); cell->setPort("\\ADDSUBBOT", st.add->type == "$add" ? State::S0 : State::S1); } else { cell->setPort("\\ADDSUBTOP", State::S0); cell->setPort("\\ADDSUBBOT", State::S0); } SigSpec OHOLD; if (st.ffOholdmux) OHOLD = st.ffOholdpol ? st.ffOholdmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffOholdmux->getPort("\\S")); else OHOLD = State::S0; cell->setPort("\\OHOLDTOP", OHOLD); cell->setPort("\\OHOLDBOT", OHOLD); SigSpec ORST; if (st.ffOrstmux) ORST = st.ffOrstpol ? st.ffOrstmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffOrstmux->getPort("\\S")); else ORST = State::S0; cell->setPort("\\ORSTTOP", ORST); cell->setPort("\\ORSTBOT", ORST); SigSpec acc_reset = State::S0; if (st.mux) { if (st.muxAB == "\\A") acc_reset = st.mux->getPort("\\S"); else acc_reset = pm.module->Not(NEW_ID, st.mux->getPort("\\S")); } cell->setPort("\\OLOADTOP", acc_reset); cell->setPort("\\OLOADBOT", acc_reset); // SB_MAC16 Remaining Parameters cell->setParam("\\TOP_8x8_MULT_REG", st.ffFJKG ? State::S1 : State::S0); cell->setParam("\\BOT_8x8_MULT_REG", st.ffFJKG ? State::S1 : State::S0); cell->setParam("\\PIPELINE_16x16_MULT_REG1", st.ffFJKG ? State::S1 : State::S0); cell->setParam("\\PIPELINE_16x16_MULT_REG2", st.ffH ? State::S1 : State::S0); cell->setParam("\\TOPADDSUB_LOWERINPUT", Const(2, 2)); cell->setParam("\\TOPADDSUB_UPPERINPUT", accum ? State::S0 : State::S1); cell->setParam("\\TOPADDSUB_CARRYSELECT", Const(3, 2)); cell->setParam("\\BOTADDSUB_LOWERINPUT", Const(2, 2)); cell->setParam("\\BOTADDSUB_UPPERINPUT", accum ? State::S0 : State::S1); cell->setParam("\\BOTADDSUB_CARRYSELECT", Const(0, 2)); cell->setParam("\\MODE_8x8", State::S0); cell->setParam("\\A_SIGNED", st.mul->getParam("\\A_SIGNED").as_bool()); cell->setParam("\\B_SIGNED", st.mul->getParam("\\B_SIGNED").as_bool()); if (st.ffO) { if (st.o_lo) cell->setParam("\\TOPOUTPUT_SELECT", Const(st.add ? 0 : 3, 2)); else cell->setParam("\\TOPOUTPUT_SELECT", Const(1, 2)); st.ffO->connections_.at("\\Q").replace(O, pm.module->addWire(NEW_ID, GetSize(O))); cell->setParam("\\BOTOUTPUT_SELECT", Const(1, 2)); } else { cell->setParam("\\TOPOUTPUT_SELECT", Const(st.add ? 0 : 3, 2)); cell->setParam("\\BOTOUTPUT_SELECT", Const(st.add ? 0 : 3, 2)); } if (cell != st.mul) pm.autoremove(st.mul); else pm.blacklist(st.mul); pm.autoremove(st.ffFJKG); pm.autoremove(st.add); } struct Ice40DspPass : public Pass { Ice40DspPass() : Pass("ice40_dsp", "iCE40: map multipliers") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" ice40_dsp [options] [selection]\n"); log("\n"); log("Map multipliers and multiply-accumulate blocks to iCE40 DSP resources.\n"); log("Currently, only the 16x16 multiply mode is supported and not the 2 x 8x8 mode.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing ICE40_DSP pass (map multipliers).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) ice40_dsp_pm(module, module->selected_cells()).run_ice40_dsp(create_ice40_dsp); } } Ice40DspPass; PRIVATE_NAMESPACE_END <commit_msg>Remove TODO as check should not be necessary<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN #include "passes/pmgen/ice40_dsp_pm.h" void create_ice40_dsp(ice40_dsp_pm &pm) { auto &st = pm.st_ice40_dsp; #if 1 log("\n"); log("ffA: %s %s %s\n", log_id(st.ffA, "--"), log_id(st.ffAholdmux, "--"), log_id(st.ffArstmux, "--")); log("ffB: %s %s %s\n", log_id(st.ffB, "--"), log_id(st.ffBholdmux, "--"), log_id(st.ffBrstmux, "--")); log("ffCD: %s %s\n", log_id(st.ffCD, "--"), log_id(st.ffCDholdmux, "--")); log("mul: %s\n", log_id(st.mul, "--")); log("ffFJKG: %s\n", log_id(st.ffFJKG, "--")); log("ffH: %s\n", log_id(st.ffH, "--")); log("add: %s\n", log_id(st.add, "--")); log("mux: %s\n", log_id(st.mux, "--")); log("ffO: %s %s %s\n", log_id(st.ffO, "--"), log_id(st.ffOholdmux, "--"), log_id(st.ffOrstmux, "--")); #endif log("Checking %s.%s for iCE40 DSP inference.\n", log_id(pm.module), log_id(st.mul)); if (GetSize(st.sigA) > 16) { log(" input A (%s) is too large (%d > 16).\n", log_signal(st.sigA), GetSize(st.sigA)); return; } if (GetSize(st.sigB) > 16) { log(" input B (%s) is too large (%d > 16).\n", log_signal(st.sigB), GetSize(st.sigB)); return; } if (GetSize(st.sigO) > 33) { log(" adder/accumulator (%s) is too large (%d > 33).\n", log_signal(st.sigO), GetSize(st.sigO)); return; } if (GetSize(st.sigH) > 32) { log(" output (%s) is too large (%d > 32).\n", log_signal(st.sigH), GetSize(st.sigH)); return; } Cell *cell = st.mul; if (cell->type == "$mul") { log(" replacing %s with SB_MAC16 cell.\n", log_id(st.mul->type)); cell = pm.module->addCell(NEW_ID, "\\SB_MAC16"); pm.module->swap_names(cell, st.mul); } else log_assert(cell->type == "\\SB_MAC16"); // SB_MAC16 Input Interface SigSpec A = st.sigA; A.extend_u0(16, st.mul->getParam("\\A_SIGNED").as_bool()); log_assert(GetSize(A) == 16); SigSpec B = st.sigB; B.extend_u0(16, st.mul->getParam("\\B_SIGNED").as_bool()); log_assert(GetSize(B) == 16); SigSpec CD = st.sigCD; if (CD.empty()) CD = RTLIL::Const(0, 32); else log_assert(GetSize(CD) == 32); cell->setPort("\\A", A); cell->setPort("\\B", B); cell->setPort("\\C", CD.extract(16, 16)); cell->setPort("\\D", CD.extract(0, 16)); cell->setParam("\\A_REG", st.ffA ? State::S1 : State::S0); cell->setParam("\\B_REG", st.ffB ? State::S1 : State::S0); cell->setParam("\\C_REG", st.ffCD ? State::S1 : State::S0); cell->setParam("\\D_REG", st.ffCD ? State::S1 : State::S0); SigSpec AHOLD, BHOLD, CDHOLD; if (st.ffAholdmux) AHOLD = st.ffAholdpol ? st.ffAholdmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffAholdmux->getPort("\\S")); else AHOLD = State::S0; if (st.ffBholdmux) BHOLD = st.ffBholdpol ? st.ffBholdmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffBholdmux->getPort("\\S")); else BHOLD = State::S0; if (st.ffCDholdmux) CDHOLD = st.ffCDholdpol ? st.ffCDholdmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffCDholdmux->getPort("\\S")); else CDHOLD = State::S0; cell->setPort("\\AHOLD", AHOLD); cell->setPort("\\BHOLD", BHOLD); cell->setPort("\\CHOLD", CDHOLD); cell->setPort("\\DHOLD", CDHOLD); SigSpec IRSTTOP, IRSTBOT; if (st.ffArstmux) IRSTTOP = st.ffArstpol ? st.ffArstmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffArstmux->getPort("\\S")); else IRSTTOP = State::S0; if (st.ffBrstmux) IRSTBOT = st.ffBrstpol ? st.ffBrstmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffBrstmux->getPort("\\S")); else IRSTBOT = State::S0; cell->setPort("\\IRSTTOP", IRSTTOP); cell->setPort("\\IRSTBOT", IRSTBOT); if (st.clock != SigBit()) { cell->setPort("\\CLK", st.clock); cell->setPort("\\CE", State::S1); cell->setParam("\\NEG_TRIGGER", st.clock_pol ? State::S0 : State::S1); log(" clock: %s (%s)", log_signal(st.clock), st.clock_pol ? "posedge" : "negedge"); if (st.ffA) log(" ffA:%s", log_id(st.ffA)); if (st.ffB) log(" ffB:%s", log_id(st.ffB)); if (st.ffCD) log(" ffCD:%s", log_id(st.ffCD)); if (st.ffFJKG) log(" ffFJKG:%s", log_id(st.ffFJKG)); if (st.ffH) log(" ffH:%s", log_id(st.ffH)); if (st.ffO) log(" ffO:%s", log_id(st.ffO)); log("\n"); } else { cell->setPort("\\CLK", State::S0); cell->setPort("\\CE", State::S0); cell->setParam("\\NEG_TRIGGER", State::S0); } // SB_MAC16 Cascade Interface cell->setPort("\\SIGNEXTIN", State::Sx); cell->setPort("\\SIGNEXTOUT", pm.module->addWire(NEW_ID)); cell->setPort("\\CI", State::Sx); cell->setPort("\\ACCUMCI", State::Sx); cell->setPort("\\ACCUMCO", pm.module->addWire(NEW_ID)); // SB_MAC16 Output Interface SigSpec O = st.sigO; int O_width = GetSize(O); if (O_width == 33) { log_assert(st.add); // If we have a signed multiply-add, then perform sign extension if (st.add->getParam("\\A_SIGNED").as_bool() && st.add->getParam("\\B_SIGNED").as_bool()) pm.module->connect(O[32], O[31]); else cell->setPort("\\CO", O[32]); O.remove(O_width-1); } else cell->setPort("\\CO", pm.module->addWire(NEW_ID)); log_assert(GetSize(O) <= 32); if (GetSize(O) < 32) O.append(pm.module->addWire(NEW_ID, 32-GetSize(O))); cell->setPort("\\O", O); bool accum = false; if (st.add) { accum = (st.ffO && st.add->getPort(st.addAB == "\\A" ? "\\B" : "\\A") == st.sigO); if (accum) log(" accumulator %s (%s)\n", log_id(st.add), log_id(st.add->type)); else log(" adder %s (%s)\n", log_id(st.add), log_id(st.add->type)); cell->setPort("\\ADDSUBTOP", st.add->type == "$add" ? State::S0 : State::S1); cell->setPort("\\ADDSUBBOT", st.add->type == "$add" ? State::S0 : State::S1); } else { cell->setPort("\\ADDSUBTOP", State::S0); cell->setPort("\\ADDSUBBOT", State::S0); } SigSpec OHOLD; if (st.ffOholdmux) OHOLD = st.ffOholdpol ? st.ffOholdmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffOholdmux->getPort("\\S")); else OHOLD = State::S0; cell->setPort("\\OHOLDTOP", OHOLD); cell->setPort("\\OHOLDBOT", OHOLD); SigSpec ORST; if (st.ffOrstmux) ORST = st.ffOrstpol ? st.ffOrstmux->getPort("\\S") : pm.module->Not(NEW_ID, st.ffOrstmux->getPort("\\S")); else ORST = State::S0; cell->setPort("\\ORSTTOP", ORST); cell->setPort("\\ORSTBOT", ORST); SigSpec acc_reset = State::S0; if (st.mux) { if (st.muxAB == "\\A") acc_reset = st.mux->getPort("\\S"); else acc_reset = pm.module->Not(NEW_ID, st.mux->getPort("\\S")); } cell->setPort("\\OLOADTOP", acc_reset); cell->setPort("\\OLOADBOT", acc_reset); // SB_MAC16 Remaining Parameters cell->setParam("\\TOP_8x8_MULT_REG", st.ffFJKG ? State::S1 : State::S0); cell->setParam("\\BOT_8x8_MULT_REG", st.ffFJKG ? State::S1 : State::S0); cell->setParam("\\PIPELINE_16x16_MULT_REG1", st.ffFJKG ? State::S1 : State::S0); cell->setParam("\\PIPELINE_16x16_MULT_REG2", st.ffH ? State::S1 : State::S0); cell->setParam("\\TOPADDSUB_LOWERINPUT", Const(2, 2)); cell->setParam("\\TOPADDSUB_UPPERINPUT", accum ? State::S0 : State::S1); cell->setParam("\\TOPADDSUB_CARRYSELECT", Const(3, 2)); cell->setParam("\\BOTADDSUB_LOWERINPUT", Const(2, 2)); cell->setParam("\\BOTADDSUB_UPPERINPUT", accum ? State::S0 : State::S1); cell->setParam("\\BOTADDSUB_CARRYSELECT", Const(0, 2)); cell->setParam("\\MODE_8x8", State::S0); cell->setParam("\\A_SIGNED", st.mul->getParam("\\A_SIGNED").as_bool()); cell->setParam("\\B_SIGNED", st.mul->getParam("\\B_SIGNED").as_bool()); if (st.ffO) { if (st.o_lo) cell->setParam("\\TOPOUTPUT_SELECT", Const(st.add ? 0 : 3, 2)); else cell->setParam("\\TOPOUTPUT_SELECT", Const(1, 2)); st.ffO->connections_.at("\\Q").replace(O, pm.module->addWire(NEW_ID, GetSize(O))); cell->setParam("\\BOTOUTPUT_SELECT", Const(1, 2)); } else { cell->setParam("\\TOPOUTPUT_SELECT", Const(st.add ? 0 : 3, 2)); cell->setParam("\\BOTOUTPUT_SELECT", Const(st.add ? 0 : 3, 2)); } if (cell != st.mul) pm.autoremove(st.mul); else pm.blacklist(st.mul); pm.autoremove(st.ffFJKG); pm.autoremove(st.add); } struct Ice40DspPass : public Pass { Ice40DspPass() : Pass("ice40_dsp", "iCE40: map multipliers") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" ice40_dsp [options] [selection]\n"); log("\n"); log("Map multipliers and multiply-accumulate blocks to iCE40 DSP resources.\n"); log("Currently, only the 16x16 multiply mode is supported and not the 2 x 8x8 mode.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing ICE40_DSP pass (map multipliers).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) ice40_dsp_pm(module, module->selected_cells()).run_ice40_dsp(create_ice40_dsp); } } Ice40DspPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com> // SYSTEM INCLUDES // APPLICATION INCLUDES #include "mp/MpBridgeAlgSimple.h" #include "mp/MpMisc.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // TYPEDEFS // DEFINES #define DEBUG_AGC #undef DEBUG_AGC // MACROS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////////// PUBLIC //////////////////////////////// */ /* =============================== CREATORS =============================== */ MpBridgeAlgSimple::MpBridgeAlgSimple(int inputs, int outputs, UtlBoolean mixSilence, int samplesPerFrame) : MpBridgeAlgBase(inputs, outputs, mixSilence) , mpGainMatrix(NULL) , mpMixAccumulator(NULL) { // Allocate mix matrix. mpGainMatrix = new MpBridgeGain[maxInputs()*maxOutputs()]; assert(mpGainMatrix != NULL); // Initially set matrix to inversed unity matrix, with zeros along // main diagonal. MpBridgeGain *pGain = mpGainMatrix; *pGain = MP_BRIDGE_GAIN_MUTED; pGain++; for (int row=0; row<maxOutputs()-1; row++) { for (int i=0; i<maxInputs(); i++) { *pGain = MP_BRIDGE_GAIN_PASSTHROUGH; pGain++; } *pGain = MP_BRIDGE_GAIN_MUTED; pGain++; } // Allocate temporary storage for mixing data. mpMixAccumulator = new MpBridgeAccum[samplesPerFrame]; assert(mpMixAccumulator != NULL); } MpBridgeAlgSimple::~MpBridgeAlgSimple() { delete[] mpGainMatrix; delete[] mpMixAccumulator; } /* ============================= MANIPULATORS ============================= */ UtlBoolean MpBridgeAlgSimple::doMix(MpBufPtr inBufs[], int inBufsSize, MpBufPtr outBufs[], int outBufsSize, int samplesPerFrame) { // Initialize amplitudes if they haven't been initialized yet. for (int i=0; i<inBufsSize; i++) { if (mpPrevAmplitudes[i] < 0 && inBufs[i].isValid()) { MpAudioBufPtr pAudioBuf = inBufs[i]; mpPrevAmplitudes[i] = pAudioBuf->getAmplitude(); } } #ifdef DEBUG_AGC static int debugCounter = 0; debugCounter++; if (debugCounter % 50 == 0) { printf("\nInput: "); for (int inputNum=0; inputNum<inBufsSize; inputNum++) { if (inBufs[inputNum].isValid()) { MpAudioBufPtr pFrame = inBufs[inputNum]; printf("%d ", pFrame->getAmplitude()); } else { printf("- "); } } printf("\n"); printf("Output: "); } #endif // Loop over all outputs and mix for (int outputNum=0; outputNum<outBufsSize; outputNum++) { MpBridgeGain *pInputGains = &mpGainMatrix[outputNum*maxInputs()]; int32_t amplitude = 0; // Initialize accumulator for (int i=0; i<samplesPerFrame; i++) { mpMixAccumulator[i] = MPF_BRIDGE_FLOAT(0.0f); } // Get buffer for output data. MpAudioBufPtr pOutBuf = MpMisc.RawAudioPool->getBuffer(); assert(pOutBuf.isValid()); pOutBuf->setSamplesNumber(samplesPerFrame); pOutBuf->setSpeechType(MP_SPEECH_SILENT); // Mix input data to accumulator for (int inputNum=0; inputNum<inBufsSize; inputNum++) { if (inBufs[inputNum].isValid() && pInputGains[inputNum] != MP_BRIDGE_GAIN_MUTED) { MpAudioBufPtr pFrame = inBufs[inputNum]; assert(pFrame->getSamplesNumber() == samplesPerFrame); // Do not mix muted audio. if (pFrame->getSpeechType() == MP_SPEECH_MUTED) { continue; } MpAudioSample prevAmplitude = mpPrevAmplitudes[inputNum]; MpAudioSample curAmplitude = pFrame->getAmplitude(); if ( pInputGains[inputNum] == MP_BRIDGE_GAIN_PASSTHROUGH && prevAmplitude == MpSpeechParams::MAX_AMPLITUDE && curAmplitude == MpSpeechParams::MAX_AMPLITUDE) { MpDspUtils::add_IGain(pFrame->getSamplesPtr(), mpMixAccumulator, samplesPerFrame, MP_BRIDGE_FRAC_LENGTH); // Update output amplitude value. amplitude += MpSpeechParams::MAX_AMPLITUDE; #ifdef DEBUG_AGC if ( debugCounter % 50 == 0 && (outputNum==0 || outputNum==3) ) { printf("P"); } #endif } else if (curAmplitude == prevAmplitude) { // Calculate gain taking into account input amplitude. MpBridgeGain scaledGain = (MpBridgeGain) ((pInputGains[inputNum]*MAX_AMPLITUDE_ROUND)/curAmplitude); MpDspUtils::addMul_I(pFrame->getSamplesPtr(), scaledGain, mpMixAccumulator, samplesPerFrame); // Update output amplitude value. amplitude += (curAmplitude*scaledGain)>>MP_BRIDGE_FRAC_LENGTH; #ifdef DEBUG_AGC if ( debugCounter % 50 == 0 && (outputNum==0 || outputNum==3) ) { printf("F %d", scaledGain); } #endif } else { // Calculate gain start and end taking into account previous // and current input amplitudes. MpBridgeGain scaledGainStart = (MpBridgeGain) ((pInputGains[inputNum]*MAX_AMPLITUDE_ROUND)/prevAmplitude); MpBridgeGain scaledGainEnd = (MpBridgeGain) ((pInputGains[inputNum]*MAX_AMPLITUDE_ROUND)/curAmplitude); MpDspUtils::addMulLinear_I(pFrame->getSamplesPtr(), scaledGainStart, scaledGainEnd, mpMixAccumulator, samplesPerFrame); // Update output amplitude value. MpBridgeGain scaledGainMax = MpDspUtils::maximum(scaledGainStart, scaledGainEnd); amplitude += (curAmplitude*scaledGainMax) >> MP_BRIDGE_FRAC_LENGTH; #ifdef DEBUG_AGC if ( debugCounter % 50 == 0 && (outputNum==0 || outputNum==3) ) { printf("V %d %d", scaledGainStart, scaledGainEnd); } #endif } // Update output frame speech type. pOutBuf->setSpeechType(mixSpeechTypes(pOutBuf->getSpeechType(), pFrame->getSpeechType())); } } // Set amplitude of the output frame. pOutBuf->setAmplitude(MPF_SATURATE16(amplitude)); #ifdef DEBUG_AGC if ( debugCounter % 50 == 0 && (outputNum==0 || outputNum==3) ) { printf(" * %d ", MPF_SATURATE16(amplitude)); } #endif // Move data from accumulator to output. MpDspUtils::convert_Att(mpMixAccumulator, pOutBuf->getSamplesWritePtr(), samplesPerFrame, MP_BRIDGE_FRAC_LENGTH); outBufs[outputNum].swap(pOutBuf); } #ifdef DEBUG_AGC if (debugCounter % 50 == 0) { printf("\n"); } #endif // Save input amplitudes for later use. saveAmplitudes(inBufs, inBufsSize); return TRUE; } void MpBridgeAlgSimple::setGainMatrixValue(int column, int row, MpBridgeGain val) { mpGainMatrix[row*maxInputs() + column] = val; } void MpBridgeAlgSimple::setGainMatrixRow(int row, int numValues, const MpBridgeGain val[]) { // Copy gain data to mix matrix row. MpBridgeGain *pCurGain = &mpGainMatrix[row*maxInputs()]; for (int i=0; i<numValues; i++) { if (val[i] != MP_BRIDGE_GAIN_UNDEFINED) { *pCurGain = val[i]; } pCurGain++; } } void MpBridgeAlgSimple::setGainMatrixColumn(int column, int numValues, const MpBridgeGain val[]) { // Copy gain data to mix matrix column. MpBridgeGain *pCurGain = &mpGainMatrix[column]; for (int i=0; i<numValues; i++) { if (val[i] != MP_BRIDGE_GAIN_UNDEFINED) { *pCurGain = val[i]; } pCurGain += maxInputs(); } } /* ============================== ACCESSORS =============================== */ /* =============================== INQUIRY ================================ */ /* ////////////////////////////// PROTECTED /////////////////////////////// */ /* /////////////////////////////// PRIVATE //////////////////////////////// */ /* ============================== FUNCTIONS =============================== */ <commit_msg>Set clipping flag on the output frame in MpBridgeAlgSimple.<commit_after>// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com> // SYSTEM INCLUDES // APPLICATION INCLUDES #include "mp/MpBridgeAlgSimple.h" #include "mp/MpMisc.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // TYPEDEFS // DEFINES #define DEBUG_AGC #undef DEBUG_AGC // MACROS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////////// PUBLIC //////////////////////////////// */ /* =============================== CREATORS =============================== */ MpBridgeAlgSimple::MpBridgeAlgSimple(int inputs, int outputs, UtlBoolean mixSilence, int samplesPerFrame) : MpBridgeAlgBase(inputs, outputs, mixSilence) , mpGainMatrix(NULL) , mpMixAccumulator(NULL) { // Allocate mix matrix. mpGainMatrix = new MpBridgeGain[maxInputs()*maxOutputs()]; assert(mpGainMatrix != NULL); // Initially set matrix to inversed unity matrix, with zeros along // main diagonal. MpBridgeGain *pGain = mpGainMatrix; *pGain = MP_BRIDGE_GAIN_MUTED; pGain++; for (int row=0; row<maxOutputs()-1; row++) { for (int i=0; i<maxInputs(); i++) { *pGain = MP_BRIDGE_GAIN_PASSTHROUGH; pGain++; } *pGain = MP_BRIDGE_GAIN_MUTED; pGain++; } // Allocate temporary storage for mixing data. mpMixAccumulator = new MpBridgeAccum[samplesPerFrame]; assert(mpMixAccumulator != NULL); } MpBridgeAlgSimple::~MpBridgeAlgSimple() { delete[] mpGainMatrix; delete[] mpMixAccumulator; } /* ============================= MANIPULATORS ============================= */ UtlBoolean MpBridgeAlgSimple::doMix(MpBufPtr inBufs[], int inBufsSize, MpBufPtr outBufs[], int outBufsSize, int samplesPerFrame) { // Initialize amplitudes if they haven't been initialized yet. for (int i=0; i<inBufsSize; i++) { if (mpPrevAmplitudes[i] < 0 && inBufs[i].isValid()) { MpAudioBufPtr pAudioBuf = inBufs[i]; mpPrevAmplitudes[i] = pAudioBuf->getAmplitude(); } } #ifdef DEBUG_AGC static int debugCounter = 0; debugCounter++; if (debugCounter % 50 == 0) { printf("\nInput: "); for (int inputNum=0; inputNum<inBufsSize; inputNum++) { if (inBufs[inputNum].isValid()) { MpAudioBufPtr pFrame = inBufs[inputNum]; printf("%d ", pFrame->getAmplitude()); } else { printf("- "); } } printf("\n"); printf("Output: "); } #endif // Loop over all outputs and mix for (int outputNum=0; outputNum<outBufsSize; outputNum++) { MpBridgeGain *pInputGains = &mpGainMatrix[outputNum*maxInputs()]; int32_t amplitude = 0; // Initialize accumulator for (int i=0; i<samplesPerFrame; i++) { mpMixAccumulator[i] = MPF_BRIDGE_FLOAT(0.0f); } // Get buffer for output data. MpAudioBufPtr pOutBuf = MpMisc.RawAudioPool->getBuffer(); assert(pOutBuf.isValid()); pOutBuf->setSamplesNumber(samplesPerFrame); pOutBuf->setSpeechType(MP_SPEECH_SILENT); // Mix input data to accumulator for (int inputNum=0; inputNum<inBufsSize; inputNum++) { if (inBufs[inputNum].isValid() && pInputGains[inputNum] != MP_BRIDGE_GAIN_MUTED) { MpAudioBufPtr pFrame = inBufs[inputNum]; assert(pFrame->getSamplesNumber() == samplesPerFrame); // Do not mix muted audio. if (pFrame->getSpeechType() == MP_SPEECH_MUTED) { continue; } MpAudioSample prevAmplitude = mpPrevAmplitudes[inputNum]; MpAudioSample curAmplitude = pFrame->getAmplitude(); if ( pInputGains[inputNum] == MP_BRIDGE_GAIN_PASSTHROUGH && prevAmplitude == MpSpeechParams::MAX_AMPLITUDE && curAmplitude == MpSpeechParams::MAX_AMPLITUDE) { MpDspUtils::add_IGain(pFrame->getSamplesPtr(), mpMixAccumulator, samplesPerFrame, MP_BRIDGE_FRAC_LENGTH); // Update output amplitude value. amplitude += MpSpeechParams::MAX_AMPLITUDE; #ifdef DEBUG_AGC if ( debugCounter % 50 == 0 && (outputNum==0 || outputNum==3) ) { printf("P"); } #endif } else if (curAmplitude == prevAmplitude) { // Calculate gain taking into account input amplitude. MpBridgeGain scaledGain = (MpBridgeGain) ((pInputGains[inputNum]*MAX_AMPLITUDE_ROUND)/curAmplitude); MpDspUtils::addMul_I(pFrame->getSamplesPtr(), scaledGain, mpMixAccumulator, samplesPerFrame); // Update output amplitude value. amplitude += (curAmplitude*scaledGain)>>MP_BRIDGE_FRAC_LENGTH; #ifdef DEBUG_AGC if ( debugCounter % 50 == 0 && (outputNum==0 || outputNum==3) ) { printf("F %d", scaledGain); } #endif } else { // Calculate gain start and end taking into account previous // and current input amplitudes. MpBridgeGain scaledGainStart = (MpBridgeGain) ((pInputGains[inputNum]*MAX_AMPLITUDE_ROUND)/prevAmplitude); MpBridgeGain scaledGainEnd = (MpBridgeGain) ((pInputGains[inputNum]*MAX_AMPLITUDE_ROUND)/curAmplitude); MpDspUtils::addMulLinear_I(pFrame->getSamplesPtr(), scaledGainStart, scaledGainEnd, mpMixAccumulator, samplesPerFrame); // Update output amplitude value. MpBridgeGain scaledGainMax = MpDspUtils::maximum(scaledGainStart, scaledGainEnd); amplitude += (curAmplitude*scaledGainMax) >> MP_BRIDGE_FRAC_LENGTH; #ifdef DEBUG_AGC if ( debugCounter % 50 == 0 && (outputNum==0 || outputNum==3) ) { printf("V %d %d", scaledGainStart, scaledGainEnd); } #endif } // Update output frame speech type. pOutBuf->setSpeechType(mixSpeechTypes(pOutBuf->getSpeechType(), pFrame->getSpeechType())); } } // Set amplitude and clipping flag of the output frame. pOutBuf->setAmplitude(MPF_SATURATE16(amplitude)); if (amplitude >= MpSpeechParams::MAX_AMPLITUDE) { pOutBuf->setClipping(TRUE); } #ifdef DEBUG_AGC if ( debugCounter % 50 == 0 && (outputNum==0 || outputNum==3) ) { printf(" * %d ", MPF_SATURATE16(amplitude)); } #endif // Move data from accumulator to output. MpDspUtils::convert_Att(mpMixAccumulator, pOutBuf->getSamplesWritePtr(), samplesPerFrame, MP_BRIDGE_FRAC_LENGTH); outBufs[outputNum].swap(pOutBuf); } #ifdef DEBUG_AGC if (debugCounter % 50 == 0) { printf("\n"); } #endif // Save input amplitudes for later use. saveAmplitudes(inBufs, inBufsSize); return TRUE; } void MpBridgeAlgSimple::setGainMatrixValue(int column, int row, MpBridgeGain val) { mpGainMatrix[row*maxInputs() + column] = val; } void MpBridgeAlgSimple::setGainMatrixRow(int row, int numValues, const MpBridgeGain val[]) { // Copy gain data to mix matrix row. MpBridgeGain *pCurGain = &mpGainMatrix[row*maxInputs()]; for (int i=0; i<numValues; i++) { if (val[i] != MP_BRIDGE_GAIN_UNDEFINED) { *pCurGain = val[i]; } pCurGain++; } } void MpBridgeAlgSimple::setGainMatrixColumn(int column, int numValues, const MpBridgeGain val[]) { // Copy gain data to mix matrix column. MpBridgeGain *pCurGain = &mpGainMatrix[column]; for (int i=0; i<numValues; i++) { if (val[i] != MP_BRIDGE_GAIN_UNDEFINED) { *pCurGain = val[i]; } pCurGain += maxInputs(); } } /* ============================== ACCESSORS =============================== */ /* =============================== INQUIRY ================================ */ /* ////////////////////////////// PROTECTED /////////////////////////////// */ /* /////////////////////////////// PRIVATE //////////////////////////////// */ /* ============================== FUNCTIONS =============================== */ <|endoftext|>
<commit_before>// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "nf_networking_sntp.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp = { "nanoFramework.Networking.Sntp", 0x733B4551, method_lookup, { 1, 0, 2, 48 } }; <commit_msg>Update nanoFramework.Networking.Sntp version to 1.0.2-preview-049 ***NO_CI***<commit_after>// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "nf_networking_sntp.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp = { "nanoFramework.Networking.Sntp", 0x733B4551, method_lookup, { 1, 0, 2, 49 } }; <|endoftext|>
<commit_before>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Author: Josh Faust #ifndef SMCONSOLE_SMCONSOLE_H #define SMCONSOLE_SMCONSOLE_H #include <cstdio> #include <sstream> #include <cstdarg> #include <sm/logging/macros.h> #include <sm/logging/Levels.hpp> #include <sm/logging/LoggingGlobals.hpp> #include <boost/interprocess/streams/vectorstream.hpp> namespace boost { template<typename T> class shared_array; } namespace sm { namespace logging { class Logger; } // namespace logging namespace logging { } // namespace logging } // namespace sm #define SMCONSOLE_DEFINE_LOCATION(cond, level, name) \ static ::sm::logging::LogLocation loc; \ if (SM_UNLIKELY(!loc._initialized)) \ { \ ::sm::logging::g_logging_globals.initializeLogLocation(&loc, name, level); \ } \ if (SM_UNLIKELY(loc._level != level)) \ { \ ::sm::logging::g_logging_globals.setLogLocationLevel(&loc, level); \ ::sm::logging::g_logging_globals.checkLogLocationEnabled(&loc); \ } \ bool enabled = loc._loggerEnabled && (cond); #define SMCONSOLE_PRINT_AT_LOCATION(...) \ ::sm::logging::g_logging_globals.print(loc._streamName.c_str(), loc._level, __FILE__, __LINE__, __SMCONSOLE_FUNCTION__, __VA_ARGS__) #define SMCONSOLE_PRINT_STREAM_AT_LOCATION(args) \ do \ { \ ::sm::logging::vectorstream ss; \ ss << args; \ ::sm::logging::g_logging_globals.print(loc._streamName.c_str(), loc._level, ss, __FILE__, __LINE__, __SMCONSOLE_FUNCTION__); \ } while (0) /** * \brief Log to a given named logger at a given verbosity level, only if a given condition has been met, with printf-style formatting * * \note The condition will only be evaluated if this logging statement is enabled * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_COND(cond, level, name, ...) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(cond, level, name); \ \ if (SM_UNLIKELY(enabled)) \ { \ SMCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, only if a given condition has been met, with stream-style formatting * * \note The condition will only be evaluated if this logging statement is enabled * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_STREAM_COND(cond, level, name, args) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(cond, level, name); \ if (SM_UNLIKELY(enabled)) \ { \ SMCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, only the first time it is hit when enabled, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_ONCE(level, name, ...) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ static bool hit = false; \ if (SM_UNLIKELY(enabled) && SM_UNLIKELY(!hit)) \ { \ hit = true; \ SMCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, only the first time it is hit when enabled, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_STREAM_ONCE(level, name, args) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ static bool hit = false; \ if (SM_UNLIKELY(enabled) && SM_UNLIKELY(!hit)) \ { \ hit = true; \ SMCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, limited to a specific rate of printing, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. * \param rate The rate it should actually trigger at */ #define SM_LOG_THROTTLE(rate, level, name, ...) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ static double last_hit = 0.0; \ double now = ::sm::logging::g_logging_globals._logger->currentTimeSecondsUtc(); \ if (SM_UNLIKELY(enabled) && SM_UNLIKELY(last_hit + rate <= now)) \ { \ last_hit = now; \ SMCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, limited to a specific rate of printing, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. * \param rate The rate it should actually trigger at */ #define SM_LOG_STREAM_THROTTLE(rate, level, name, args) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ static double last_hit = 0.0; \ double now = ::sm::logging::g_logging_globals._logger->currentTimeSecondsUtc(); \ if (SM_UNLIKELY(enabled) && SM_UNLIKELY(last_hit + rate <= now)) \ { \ last_hit = now; \ SMCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, with user-defined filtering, with stream-style formatting * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_STREAM_NAME(name, level, args) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ if (SM_UNLIKELY(enabled) ) \ { \ SMCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG(level, name, ...) SM_LOG_COND(true, level, name, __VA_ARGS__) /** * \brief Log to a given named logger at a given verbosity level, with stream-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_STREAM(level, name, args) SM_LOG_STREAM_COND(true, level, name, args) #include "macros_generated.hpp" #endif // SMCONSOLE_SMCONSOLE_H <commit_msg>Remove ss - symobol from local scope in SMCONSOLE_PRINT_STREAM_AT_LOCATION<commit_after>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Author: Josh Faust #ifndef SMCONSOLE_SMCONSOLE_H #define SMCONSOLE_SMCONSOLE_H #include <cstdio> #include <sstream> #include <cstdarg> #include <sm/logging/macros.h> #include <sm/logging/Levels.hpp> #include <sm/logging/LoggingGlobals.hpp> #include <boost/interprocess/streams/vectorstream.hpp> namespace boost { template<typename T> class shared_array; } namespace sm { namespace logging { class Logger; } // namespace logging namespace logging { } // namespace logging } // namespace sm #define SMCONSOLE_DEFINE_LOCATION(cond, level, name) \ static ::sm::logging::LogLocation loc; \ if (SM_UNLIKELY(!loc._initialized)) \ { \ ::sm::logging::g_logging_globals.initializeLogLocation(&loc, name, level); \ } \ if (SM_UNLIKELY(loc._level != level)) \ { \ ::sm::logging::g_logging_globals.setLogLocationLevel(&loc, level); \ ::sm::logging::g_logging_globals.checkLogLocationEnabled(&loc); \ } \ bool enabled = loc._loggerEnabled && (cond); #define SMCONSOLE_PRINT_AT_LOCATION(...) \ ::sm::logging::g_logging_globals.print(loc._streamName.c_str(), loc._level, __FILE__, __LINE__, __SMCONSOLE_FUNCTION__, __VA_ARGS__) #define SMCONSOLE_PRINT_STREAM_AT_LOCATION(args) \ do \ { \ ::sm::logging::vectorstream ss___; \ ss___ << args; \ ::sm::logging::g_logging_globals.print(loc._streamName.c_str(), loc._level, ss___, __FILE__, __LINE__, __SMCONSOLE_FUNCTION__); \ } while (0) /** * \brief Log to a given named logger at a given verbosity level, only if a given condition has been met, with printf-style formatting * * \note The condition will only be evaluated if this logging statement is enabled * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_COND(cond, level, name, ...) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(cond, level, name); \ \ if (SM_UNLIKELY(enabled)) \ { \ SMCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, only if a given condition has been met, with stream-style formatting * * \note The condition will only be evaluated if this logging statement is enabled * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_STREAM_COND(cond, level, name, args) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(cond, level, name); \ if (SM_UNLIKELY(enabled)) \ { \ SMCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, only the first time it is hit when enabled, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_ONCE(level, name, ...) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ static bool hit = false; \ if (SM_UNLIKELY(enabled) && SM_UNLIKELY(!hit)) \ { \ hit = true; \ SMCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, only the first time it is hit when enabled, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_STREAM_ONCE(level, name, args) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ static bool hit = false; \ if (SM_UNLIKELY(enabled) && SM_UNLIKELY(!hit)) \ { \ hit = true; \ SMCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, limited to a specific rate of printing, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. * \param rate The rate it should actually trigger at */ #define SM_LOG_THROTTLE(rate, level, name, ...) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ static double last_hit = 0.0; \ double now = ::sm::logging::g_logging_globals._logger->currentTimeSecondsUtc(); \ if (SM_UNLIKELY(enabled) && SM_UNLIKELY(last_hit + rate <= now)) \ { \ last_hit = now; \ SMCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, limited to a specific rate of printing, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. * \param rate The rate it should actually trigger at */ #define SM_LOG_STREAM_THROTTLE(rate, level, name, args) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ static double last_hit = 0.0; \ double now = ::sm::logging::g_logging_globals._logger->currentTimeSecondsUtc(); \ if (SM_UNLIKELY(enabled) && SM_UNLIKELY(last_hit + rate <= now)) \ { \ last_hit = now; \ SMCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, with user-defined filtering, with stream-style formatting * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_STREAM_NAME(name, level, args) \ do \ { \ SMCONSOLE_DEFINE_LOCATION(true, level, name); \ if (SM_UNLIKELY(enabled) ) \ { \ SMCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, with printf-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG(level, name, ...) SM_LOG_COND(true, level, name, __VA_ARGS__) /** * \brief Log to a given named logger at a given verbosity level, with stream-style formatting * * \param level One of the levels specified in ::sm::logging::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "sm.<package_name>". Use SMCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define SM_LOG_STREAM(level, name, args) SM_LOG_STREAM_COND(true, level, name, args) #include "macros_generated.hpp" #endif // SMCONSOLE_SMCONSOLE_H <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <vector> #include <deque> #include <list> #include <array> #include <string> #include <sstream> #include <algorithm> const int field_size = 32; const int stone_size = 8; const int empty_val = 256; const int filled_val = 257; const int normal = 0, rot90 = 1, rot180 = 2, rot270 = 3, fliped = 4; std::istream& in = std::cin; std::ostream& out = std::cout; std::ostream& err = std::cerr; struct Position { int y, x; bool operator==(const Position& obj) const { return y == obj.y && x == obj.x; } bool operator<(const Position& obj) const { if (y == obj.y) return x < obj.x; return y < obj.y; } }; struct OperatedStone { int i, j; Position p; }; struct Field { std::array<std::array<int, field_size>, field_size> raw; std::map<Position, std::list<OperatedStone>> candidates; std::vector<std::string> answer; void print_answer(int, int); void dump(); void dump(std::list<Position>&); void dump(std::list<Position>&, Position p); }; struct Stone { std::array<std::array<int, stone_size>, stone_size> raw; std::deque<Position> zks; void dump(); }; int get(); void br(); void parse_input(); void parse_field(); void parse_stones(); void parse_stone(int); void get_candidates(); void solve(); void dfs(int, int, int, int, Position, Field, std::list<Position>); int put_stone(Field&, int, int, Position, std::list<Position>&); bool check_pos(int y, int x); std::string answer_format(Position, int); std::string to_s(int); void operate(int); int stone_number; Field initial_field; std::list<Position> initial_empties; std::array<std::array<Stone, 8>, 256> stones; void solve() { std::list<Position> empty_list; empty_list.clear(); for (auto p : initial_empties) { for (auto s : initial_field.candidates[p]) { dfs(1, 0, s.i, s.j, s.p, initial_field, empty_list); } } } void dfs(int c, int nowscore, int n, int m, Position p, Field f, std::list<Position> candidates) { int score = 0; if ((score = put_stone(f, n, m, p, candidates)) == 0) { return; } f.answer[n] = answer_format(p, m); score += nowscore; f.print_answer(score, c); err << "score:" << score << std::endl; for (auto np : candidates) { for (auto s : initial_field.candidates[np]) { if (s.i > n) { dfs(c+1, score, s.i, s.j, s.p, f, candidates); } } } } int put_stone(Field& f, int n, int m, Position p1, std::list<Position>& next) { Field backup = f; int score = 0; for (auto p2 : stones[n][m].zks) { int y = p1.y + p2.y, x = p1.x + p2.x; if (f.raw[y][x] != empty_val) { f = backup; next.clear(); return 0; } f.raw[y][x] = n; score += 1; auto exist = std::find(next.begin(), next.end(), Position{y, x}); if (exist != next.end()) { next.erase(exist); } int dy[] = {-1, 0, 0, 1}, dx[] = {0, -1, 1, 0}; for (int i = 0; i < 4; ++i) { int ny = y+dy[i], nx = x+dx[i]; if (check_pos(ny, nx) && f.raw[ny][nx] == empty_val) { next.emplace_back(Position{ny, nx}); } } } return score; } bool check_pos(int y, int x) { return (0<= y && y < field_size) && (0 <= x && x < field_size); } int main() { parse_input(); get_candidates(); solve(); return 0; } // ------- void Field::dump() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] == empty_val) out.put('.'); else if (raw[i][j] < stone_number) out.put('@'); else out.put('#'); } out.put('\n'); } } void Field::dump(std::list<Position>& ps) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] < stone_number) out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) out.put('_'); else if (raw[i][j] == empty_val) out.put('.'); else out.put('#'); } out.put('\n'); } } void Field::dump(std::list<Position>& ps, Position p) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (Position{i, j} == p) out.put('*'); else if (raw[i][j] < stone_number) out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) out.put('_'); else if (raw[i][j] == empty_val) out.put('.'); else out.put('#'); } out.put('\n'); } } void Stone::dump() { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if (raw[i][j] == empty_val) out.put('.'); else out.put('@'); } out.put('\n'); } } int get() { int c = in.get() - '0'; if (c == 0) return empty_val; return filled_val; } void br() { in.get(), in.get(); } void parse_input() { parse_field(); in >> stone_number; br(); parse_stones(); initial_field.answer.resize(stone_number); } void parse_field() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if ((initial_field.raw[i][j] = get()) == empty_val) initial_empties.emplace_back(Position{i, j}); } br(); } } void parse_stones() { for (int i = 0; i < stone_number; ++i) { parse_stone(i); br(); operate(i); } } void parse_stone(int n) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if ((stones[n][normal].raw[i][j] = get()) != empty_val) stones[n][normal].zks.emplace_back(Position{i, j}); } br(); } } void operate(int n) { auto rotate_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+1].raw[j][7-i] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+1].zks.push_back(Position{p.x, 7-p.y}); } }; auto flip_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+4].raw[i][7-j] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+4].zks.push_back(Position{p.y, 7-p.x}); } }; rotate_impl(n, 0); rotate_impl(n, 1); rotate_impl(n, 2); flip_impl(n, 0); flip_impl(n, 1); flip_impl(n, 2); flip_impl(n, 3); } void get_candidates() { for (auto f_p : initial_empties) { for (int i = 0; i < stone_number; ++i) { for (int j = 0; j < 8; ++j) { int y = f_p.y - stones[i][j].zks[0].y, x = f_p.x - stones[i][j].zks[0].x; bool flag = true; for (auto s_p : stones[i][j].zks) { if (initial_field.raw[y + s_p.y][x + s_p.x] != empty_val) { flag = false; break; } } if (flag) { for (auto s_p : stones[i][j].zks) { initial_field.candidates[Position{f_p.y, f_p.x}].push_back(OperatedStone{i, j, Position{f_p.y - s_p.y, f_p.x - s_p.x}}); } } } } } } std::string to_s(int n) { std::stringstream ss; ss << n; return ss.str(); } std::string answer_format(Position p, int n) { std::string base = to_s(p.x) + " " + to_s(p.y)+ " "; base += (n & fliped) ? "H " : "T "; base += to_s((3 & fliped)*90); return base; } void Field::print_answer(int score, int c) { out << initial_empties.size() - score << " " << c << " " << stone_number << "\r\n"; for (int i = 0; i < stone_number; ++i) { out << answer[i] << "\r\n"; } } <commit_msg>added mode switches and shuffle<commit_after>#include <iostream> #include <map> #include <vector> #include <deque> #include <list> #include <array> #include <string> #include <sstream> #include <algorithm> #include <random> const int field_size = 32; const int stone_size = 8; const int empty_val = 256; const int filled_val = 257; const int normal = 0, rot90 = 1, rot180 = 2, rot270 = 3, fliped = 4; std::istream& in = std::cin; std::ostream& out = std::cout; std::ostream& err = std::cerr; bool shuffle_flag = true; bool dump_flag = true; struct Position { int y, x; bool operator==(const Position& obj) const { return y == obj.y && x == obj.x; } bool operator<(const Position& obj) const { if (y == obj.y) return x < obj.x; return y < obj.y; } }; struct OperatedStone { int i, j; Position p; }; struct Field { std::array<std::array<int, field_size>, field_size> raw; std::map<Position, std::deque<OperatedStone>> candidates; std::vector<std::string> answer; void print_answer(int, int); void dump(); void dump(std::deque<Position>&); void dump(std::deque<Position>&, Position p); }; struct Stone { std::array<std::array<int, stone_size>, stone_size> raw; std::deque<Position> zks; void dump(); }; int get(); void br(); void parse_input(); void parse_field(); void parse_stones(); void parse_stone(int); void get_candidates(); void solve(); int dfs(int, int, int, int, Position, Field, std::deque<Position>); int put_stone(Field&, int, int, Position, std::deque<Position>&); bool check_pos(int y, int x); std::string answer_format(Position, int); std::string to_s(int); void operate(int); int stone_number; Field initial_field; std::deque<Position> initial_empties; std::array<std::array<Stone, 8>, 256> stones; void solve() { if (shuffle_flag) { std::shuffle(initial_empties.begin(), initial_empties.end(), std::default_random_engine{}); } std::deque<Position> empty_list; empty_list.clear(); for (auto p : initial_empties) { for (auto s : initial_field.candidates[p]) { if (dfs(1, 0, s.i, s.j, s.p, initial_field, empty_list) != 0) { break; } } } } int dfs(int c, int nowscore, int n, int m, Position p, Field f, std::deque<Position> candidates) { int score = 0; if ((score = put_stone(f, n, m, p, candidates)) == 0) { return 1; } if (dump_flag) { f.dump(candidates); } f.answer[n] = answer_format(p, m); score += nowscore; f.print_answer(score, c); err << "score:" << score << ", "; for (auto np : candidates) { for (auto s : initial_field.candidates[np]) { if (s.i > n) { if (dfs(c+1, score, s.i, s.j, s.p, f, candidates) != 0) { break; } } } } return 0; } int put_stone(Field& f, int n, int m, Position p1, std::deque<Position>& next) { Field backup = f; int score = 0; for (auto p2 : stones[n][m].zks) { int y = p1.y + p2.y, x = p1.x + p2.x; if (f.raw[y][x] != empty_val) { f = backup; next.clear(); return 0; } f.raw[y][x] = n; score += 1; auto exist = std::find(next.begin(), next.end(), Position{y, x}); if (exist != next.end()) { next.erase(exist); } int dy[] = {-1, 0, 0, 1}, dx[] = {0, -1, 1, 0}; for (int i = 0; i < 4; ++i) { int ny = y+dy[i], nx = x+dx[i]; if (check_pos(ny, nx) && f.raw[ny][nx] == empty_val) { next.emplace_back(Position{ny, nx}); } } } return score; } bool check_pos(int y, int x) { return (0<= y && y < field_size) && (0 <= x && x < field_size); } int main() { parse_input(); get_candidates(); solve(); return 0; } // ------- void Field::dump() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] == empty_val) out.put('.'); else if (raw[i][j] < stone_number) out.put('@'); else out.put('#'); } out.put('\n'); } } void Field::dump(std::deque<Position>& ps) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] < stone_number) out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) out.put('_'); else if (raw[i][j] == empty_val) out.put('.'); else out.put('#'); } out.put('\n'); } } void Field::dump(std::deque<Position>& ps, Position p) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (Position{i, j} == p) out.put('*'); else if (raw[i][j] < stone_number) out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) out.put('_'); else if (raw[i][j] == empty_val) out.put('.'); else out.put('#'); } out.put('\n'); } } void Stone::dump() { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if (raw[i][j] == empty_val) out.put('.'); else out.put('@'); } out.put('\n'); } } int get() { int c = in.get() - '0'; if (c == 0) return empty_val; return filled_val; } void br() { in.get(), in.get(); } void parse_input() { parse_field(); in >> stone_number; br(); parse_stones(); initial_field.answer.resize(stone_number); } void parse_field() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if ((initial_field.raw[i][j] = get()) == empty_val) initial_empties.emplace_back(Position{i, j}); } br(); } } void parse_stones() { for (int i = 0; i < stone_number; ++i) { parse_stone(i); br(); operate(i); } } void parse_stone(int n) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if ((stones[n][normal].raw[i][j] = get()) != empty_val) stones[n][normal].zks.emplace_back(Position{i, j}); } br(); } } void operate(int n) { auto rotate_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+1].raw[j][7-i] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+1].zks.push_back(Position{p.x, 7-p.y}); } }; auto flip_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+4].raw[i][7-j] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+4].zks.push_back(Position{p.y, 7-p.x}); } }; rotate_impl(n, 0); rotate_impl(n, 1); rotate_impl(n, 2); flip_impl(n, 0); flip_impl(n, 1); flip_impl(n, 2); flip_impl(n, 3); } void get_candidates() { for (auto f_p : initial_empties) { for (int i = 0; i < stone_number; ++i) { for (int j = 0; j < 8; ++j) { int y = f_p.y - stones[i][j].zks[0].y, x = f_p.x - stones[i][j].zks[0].x; bool flag = true; for (auto s_p : stones[i][j].zks) { if (initial_field.raw[y + s_p.y][x + s_p.x] != empty_val) { flag = false; break; } } if (flag) { for (auto s_p : stones[i][j].zks) { initial_field.candidates[Position{f_p.y, f_p.x}].push_back(OperatedStone{i, j, Position{f_p.y - s_p.y, f_p.x - s_p.x}}); } } } } } } std::string to_s(int n) { std::stringstream ss; ss << n; return ss.str(); } std::string answer_format(Position p, int n) { std::string base = to_s(p.x) + " " + to_s(p.y)+ " "; base += (n & fliped) ? "H " : "T "; base += to_s((3 & fliped)*90); return base; } void Field::print_answer(int score, int c) { out << initial_empties.size() - score << " " << c << " " << stone_number << "\r\n"; for (int i = 0; i < stone_number; ++i) { out << answer[i] << "\r\n"; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60videowidget.h" #include <QtGui/private/qwidget_p.h> class QBlackWidget : public QWidget { public: QBlackWidget(QWidget *parent = 0) : QWidget(parent) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); setAttribute(Qt::WA_OpaquePaintEvent, true); setAttribute(Qt::WA_NoSystemBackground, true); setAutoFillBackground(false); #if QT_VERSION >= 0x040601 qt_widget_private(this)->extraData()->nativePaintMode = QWExtra::ZeroFill; qt_widget_private(this)->extraData()->receiveNativePaintEvents = true; #endif } protected: void paintEvent(QPaintEvent *) { if (!updatesEnabled()) return; QPainter painter(this); painter.fillRect(rect(), Qt::black); } }; S60VideoWidgetControl::S60VideoWidgetControl(QObject *parent) : QVideoWidgetControl(parent) , m_widget(0) , m_windowId(0) , m_aspectRatioMode(QVideoWidget::KeepAspectRatio) { m_widget = new QBlackWidget(); m_windowId = m_widget->winId(); m_widget->installEventFilter(this); } S60VideoWidgetControl::~S60VideoWidgetControl() { delete m_widget; } QWidget *S60VideoWidgetControl::videoWidget() { return m_widget; } QVideoWidget::AspectRatioMode S60VideoWidgetControl::aspectRatioMode() const { return m_aspectRatioMode; } void S60VideoWidgetControl::setAspectRatioMode(QVideoWidget::AspectRatioMode ratio) { if (m_aspectRatioMode != ratio) m_aspectRatioMode = ratio; } bool S60VideoWidgetControl::isFullScreen() const { return m_widget->isFullScreen(); } void S60VideoWidgetControl::setFullScreen(bool fullScreen) { emit fullScreenChanged(fullScreen); } int S60VideoWidgetControl::brightness() const { return 0; } void S60VideoWidgetControl::setBrightness(int brightness) { Q_UNUSED(brightness); } int S60VideoWidgetControl::contrast() const { return 0; } void S60VideoWidgetControl::setContrast(int contrast) { Q_UNUSED(contrast); } int S60VideoWidgetControl::hue() const { return 0; } void S60VideoWidgetControl::setHue(int hue) { Q_UNUSED(hue); } int S60VideoWidgetControl::saturation() const { return 0; } void S60VideoWidgetControl::setSaturation(int saturation) { Q_UNUSED(saturation); } bool S60VideoWidgetControl::eventFilter(QObject *object, QEvent *e) { if (object == m_widget) { if ((e->type() == QEvent::ParentChange || e->type() == QEvent::Show) && m_widget->winId() != m_windowId) { m_windowId = m_widget->winId(); emit widgetUpdated(); } if (e->type() == QEvent::Resize || e->type() == QEvent::Move) emit widgetUpdated(); } return QVideoWidgetControl::eventFilter(object, e); } void S60VideoWidgetControl::videoStateChanged(QMediaPlayer::State state) { if (state == QMediaPlayer::StoppedState) { #if QT_VERSION <= 0x040600 qt_widget_private(m_widget)->extraData()->disableBlit = false; #endif m_widget->setUpdatesEnabled(true); m_widget->repaint(); } else if (state == QMediaPlayer::PlayingState) { #if QT_VERSION <= 0x040600 qt_widget_private(m_widget)->extraData()->disableBlit = true; #endif m_widget->setUpdatesEnabled(false); } } <commit_msg>Fix winscw videowidget widgets private flags not usable on winscw<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60videowidget.h" #include <QtGui/private/qwidget_p.h> class QBlackWidget : public QWidget { public: QBlackWidget(QWidget *parent = 0) : QWidget(parent) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); setAttribute(Qt::WA_OpaquePaintEvent, true); setAttribute(Qt::WA_NoSystemBackground, true); setAutoFillBackground(false); #if QT_VERSION >= 0x040601 && !defined(__WINSCW__) qt_widget_private(this)->extraData()->nativePaintMode = QWExtra::ZeroFill; qt_widget_private(this)->extraData()->receiveNativePaintEvents = true; #endif } protected: void paintEvent(QPaintEvent *) { if (!updatesEnabled()) return; QPainter painter(this); painter.fillRect(rect(), Qt::black); } }; S60VideoWidgetControl::S60VideoWidgetControl(QObject *parent) : QVideoWidgetControl(parent) , m_widget(0) , m_windowId(0) , m_aspectRatioMode(QVideoWidget::KeepAspectRatio) { m_widget = new QBlackWidget(); m_windowId = m_widget->winId(); m_widget->installEventFilter(this); } S60VideoWidgetControl::~S60VideoWidgetControl() { delete m_widget; } QWidget *S60VideoWidgetControl::videoWidget() { return m_widget; } QVideoWidget::AspectRatioMode S60VideoWidgetControl::aspectRatioMode() const { return m_aspectRatioMode; } void S60VideoWidgetControl::setAspectRatioMode(QVideoWidget::AspectRatioMode ratio) { if (m_aspectRatioMode != ratio) m_aspectRatioMode = ratio; } bool S60VideoWidgetControl::isFullScreen() const { return m_widget->isFullScreen(); } void S60VideoWidgetControl::setFullScreen(bool fullScreen) { emit fullScreenChanged(fullScreen); } int S60VideoWidgetControl::brightness() const { return 0; } void S60VideoWidgetControl::setBrightness(int brightness) { Q_UNUSED(brightness); } int S60VideoWidgetControl::contrast() const { return 0; } void S60VideoWidgetControl::setContrast(int contrast) { Q_UNUSED(contrast); } int S60VideoWidgetControl::hue() const { return 0; } void S60VideoWidgetControl::setHue(int hue) { Q_UNUSED(hue); } int S60VideoWidgetControl::saturation() const { return 0; } void S60VideoWidgetControl::setSaturation(int saturation) { Q_UNUSED(saturation); } bool S60VideoWidgetControl::eventFilter(QObject *object, QEvent *e) { if (object == m_widget) { if ((e->type() == QEvent::ParentChange || e->type() == QEvent::Show) && m_widget->winId() != m_windowId) { m_windowId = m_widget->winId(); emit widgetUpdated(); } if (e->type() == QEvent::Resize || e->type() == QEvent::Move) emit widgetUpdated(); } return QVideoWidgetControl::eventFilter(object, e); } void S60VideoWidgetControl::videoStateChanged(QMediaPlayer::State state) { if (state == QMediaPlayer::StoppedState) { #if QT_VERSION <= 0x040600 qt_widget_private(m_widget)->extraData()->disableBlit = false; #endif m_widget->setUpdatesEnabled(true); m_widget->repaint(); } else if (state == QMediaPlayer::PlayingState) { #if QT_VERSION <= 0x040600 qt_widget_private(m_widget)->extraData()->disableBlit = true; #endif m_widget->setUpdatesEnabled(false); } } <|endoftext|>
<commit_before>#include "console.h" #include "sofa/helper/Utils.h" #ifndef WIN32 # include <unistd.h> // for isatty() #endif namespace sofa { namespace helper { Console::ColorsStatus Console::s_colorsStatus = Console::ColorsDisabled; #ifdef WIN32 static HANDLE s_console = NULL; static Console::ColorType initConsoleAndGetDefaultColor() { s_console = GetStdHandle(STD_OUTPUT_HANDLE); if(s_console == INVALID_HANDLE_VALUE) { std::cerr << "Console::init(): " << Utils::GetLastError() << std::endl; return Console::ColorType(7); } if(s_console == NULL) { std::cerr << "Console::init(): no stdout handle!" << std::endl; return Console::ColorType(7); } else { CONSOLE_SCREEN_BUFFER_INFO currentInfo; GetConsoleScreenBufferInfo(s_console, &currentInfo); return currentInfo.wAttributes; } } const Console::ColorType Console::BLACK = Console::ColorType(0); const Console::ColorType Console::BLUE = Console::ColorType(1); const Console::ColorType Console::GREEN = Console::ColorType(2); const Console::ColorType Console::CYAN = Console::ColorType(3); const Console::ColorType Console::RED = Console::ColorType(4); const Console::ColorType Console::PURPLE = Console::ColorType(5); const Console::ColorType Console::YELLOW = Console::ColorType(6); const Console::ColorType Console::WHITE = Console::ColorType(7); const Console::ColorType Console::BRIGHT_BLACK = Console::ColorType(8); const Console::ColorType Console::BRIGHT_BLUE = Console::ColorType(9); const Console::ColorType Console::BRIGHT_GREEN = Console::ColorType(10); const Console::ColorType Console::BRIGHT_CYAN = Console::ColorType(11); const Console::ColorType Console::BRIGHT_RED = Console::ColorType(12); const Console::ColorType Console::BRIGHT_PURPLE = Console::ColorType(13); const Console::ColorType Console::BRIGHT_YELLOW = Console::ColorType(14); const Console::ColorType Console::BRIGHT_WHITE = Console::ColorType(15); const Console::ColorType Console::DEFAULT_COLOR = initConsoleAndGetDefaultColor(); void Console::setColorsStatus(ColorsStatus status) { s_colorsStatus = status; } bool Console::shouldUseColors(std::ostream& stream) { // On Windows, colors are not handled with control characters, so we can // probably always use them unless explicitely disabled. return getColorsStatus() != ColorsDisabled; } SOFA_HELPER_API std::ostream& operator<<( std::ostream& stream, Console::ColorType color ) { if (Console::shouldUseColors(stream)) SetConsoleTextAttribute(s_console, color.value); return stream; } #else const Console::ColorType Console::BLACK = Console::ColorType("\033[0;30m"); const Console::ColorType Console::RED = Console::ColorType("\033[0;31m"); const Console::ColorType Console::GREEN = Console::ColorType("\033[0;32m"); const Console::ColorType Console::YELLOW = Console::ColorType("\033[0;33m"); const Console::ColorType Console::BLUE = Console::ColorType("\033[0;34m"); const Console::ColorType Console::PURPLE = Console::ColorType("\033[0;35m"); const Console::ColorType Console::CYAN = Console::ColorType("\033[0;36m"); const Console::ColorType Console::WHITE = Console::ColorType("\033[0;37m"); const Console::ColorType Console::BRIGHT_BLACK = Console::ColorType("\033[1;30m"); const Console::ColorType Console::BRIGHT_RED = Console::ColorType("\033[1;31m"); const Console::ColorType Console::BRIGHT_GREEN = Console::ColorType("\033[1;32m"); const Console::ColorType Console::BRIGHT_YELLOW = Console::ColorType("\033[1;33m"); const Console::ColorType Console::BRIGHT_BLUE = Console::ColorType("\033[1;34m"); const Console::ColorType Console::BRIGHT_PURPLE = Console::ColorType("\033[1;35m"); const Console::ColorType Console::BRIGHT_CYAN = Console::ColorType("\033[1;36m"); const Console::ColorType Console::BRIGHT_WHITE = Console::ColorType("\033[1;37m"); const Console::ColorType Console::DEFAULT_COLOR = Console::ColorType("\033[0m"); static bool s_stdoutIsRedirected = false; static bool s_stderrIsRedirected = false; void Console::setColorsStatus(ColorsStatus status) { s_colorsStatus = status; // Check for redirections and save the result. (This assumes that // stdout and stderr won't be redirected in the middle of the execution // of the program, which seems reasonable to me.) s_stdoutIsRedirected = isatty(STDOUT_FILENO) == 0; s_stderrIsRedirected = isatty(STDERR_FILENO) == 0; } bool Console::shouldUseColors(std::ostream& stream) { if (s_colorsStatus == Console::ColorsAuto) return (stream == std::cout && !s_stdoutIsRedirected) || (stream == std::cerr && !s_stderrIsRedirected); else return s_colorsStatus == Console::ColorsEnabled; } std::ostream& operator<<( std::ostream& stream, Console::ColorType color ) { if (Console::shouldUseColors(stream)) return stream << color.value; else return stream; } #endif Console::ColorsStatus Console::getColorsStatus() { return s_colorsStatus; } } } <commit_msg>Fix build on OSX/C++11<commit_after>#include "console.h" #include "sofa/helper/Utils.h" #ifndef WIN32 # include <unistd.h> // for isatty() #endif namespace sofa { namespace helper { Console::ColorsStatus Console::s_colorsStatus = Console::ColorsDisabled; #ifdef WIN32 static HANDLE s_console = NULL; static Console::ColorType initConsoleAndGetDefaultColor() { s_console = GetStdHandle(STD_OUTPUT_HANDLE); if(s_console == INVALID_HANDLE_VALUE) { std::cerr << "Console::init(): " << Utils::GetLastError() << std::endl; return Console::ColorType(7); } if(s_console == NULL) { std::cerr << "Console::init(): no stdout handle!" << std::endl; return Console::ColorType(7); } else { CONSOLE_SCREEN_BUFFER_INFO currentInfo; GetConsoleScreenBufferInfo(s_console, &currentInfo); return currentInfo.wAttributes; } } const Console::ColorType Console::BLACK = Console::ColorType(0); const Console::ColorType Console::BLUE = Console::ColorType(1); const Console::ColorType Console::GREEN = Console::ColorType(2); const Console::ColorType Console::CYAN = Console::ColorType(3); const Console::ColorType Console::RED = Console::ColorType(4); const Console::ColorType Console::PURPLE = Console::ColorType(5); const Console::ColorType Console::YELLOW = Console::ColorType(6); const Console::ColorType Console::WHITE = Console::ColorType(7); const Console::ColorType Console::BRIGHT_BLACK = Console::ColorType(8); const Console::ColorType Console::BRIGHT_BLUE = Console::ColorType(9); const Console::ColorType Console::BRIGHT_GREEN = Console::ColorType(10); const Console::ColorType Console::BRIGHT_CYAN = Console::ColorType(11); const Console::ColorType Console::BRIGHT_RED = Console::ColorType(12); const Console::ColorType Console::BRIGHT_PURPLE = Console::ColorType(13); const Console::ColorType Console::BRIGHT_YELLOW = Console::ColorType(14); const Console::ColorType Console::BRIGHT_WHITE = Console::ColorType(15); const Console::ColorType Console::DEFAULT_COLOR = initConsoleAndGetDefaultColor(); void Console::setColorsStatus(ColorsStatus status) { s_colorsStatus = status; } bool Console::shouldUseColors(std::ostream& stream) { // On Windows, colors are not handled with control characters, so we can // probably always use them unless explicitely disabled. return getColorsStatus() != ColorsDisabled; } SOFA_HELPER_API std::ostream& operator<<( std::ostream& stream, Console::ColorType color ) { if (Console::shouldUseColors(stream)) SetConsoleTextAttribute(s_console, color.value); return stream; } #else const Console::ColorType Console::BLACK = Console::ColorType("\033[0;30m"); const Console::ColorType Console::RED = Console::ColorType("\033[0;31m"); const Console::ColorType Console::GREEN = Console::ColorType("\033[0;32m"); const Console::ColorType Console::YELLOW = Console::ColorType("\033[0;33m"); const Console::ColorType Console::BLUE = Console::ColorType("\033[0;34m"); const Console::ColorType Console::PURPLE = Console::ColorType("\033[0;35m"); const Console::ColorType Console::CYAN = Console::ColorType("\033[0;36m"); const Console::ColorType Console::WHITE = Console::ColorType("\033[0;37m"); const Console::ColorType Console::BRIGHT_BLACK = Console::ColorType("\033[1;30m"); const Console::ColorType Console::BRIGHT_RED = Console::ColorType("\033[1;31m"); const Console::ColorType Console::BRIGHT_GREEN = Console::ColorType("\033[1;32m"); const Console::ColorType Console::BRIGHT_YELLOW = Console::ColorType("\033[1;33m"); const Console::ColorType Console::BRIGHT_BLUE = Console::ColorType("\033[1;34m"); const Console::ColorType Console::BRIGHT_PURPLE = Console::ColorType("\033[1;35m"); const Console::ColorType Console::BRIGHT_CYAN = Console::ColorType("\033[1;36m"); const Console::ColorType Console::BRIGHT_WHITE = Console::ColorType("\033[1;37m"); const Console::ColorType Console::DEFAULT_COLOR = Console::ColorType("\033[0m"); static bool s_stdoutIsRedirected = false; static bool s_stderrIsRedirected = false; void Console::setColorsStatus(ColorsStatus status) { s_colorsStatus = status; // Check for redirections and save the result. (This assumes that // stdout and stderr won't be redirected in the middle of the execution // of the program, which seems reasonable to me.) s_stdoutIsRedirected = isatty(STDOUT_FILENO) == 0; s_stderrIsRedirected = isatty(STDERR_FILENO) == 0; } bool Console::shouldUseColors(std::ostream& stream) { if (s_colorsStatus == Console::ColorsAuto) return (&stream == &std::cout && !s_stdoutIsRedirected) || (&stream == &std::cerr && !s_stderrIsRedirected); else return s_colorsStatus == Console::ColorsEnabled; } std::ostream& operator<<( std::ostream& stream, Console::ColorType color ) { if (Console::shouldUseColors(stream)) return stream << color.value; else return stream; } #endif Console::ColorsStatus Console::getColorsStatus() { return s_colorsStatus; } } } <|endoftext|>
<commit_before>// // George 'papanikge' Papanikolaou // CEID Advance Algorithm Design Course 2014 // Benchmarking of Minimum Spanning Tree algorithms with Boost & LEDA // #include <iostream> #include <vector> #include <map> #include <cstdlib> #include <cmath> #include <cstring> #include <ctime> #include <LEDA/graph/graph.h> #include <LEDA/graph/graph_gen.h> #include <LEDA/graph/min_span.h> #include <LEDA/system/timer.h> #include <boost/array.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/kruskal_min_spanning_tree.hpp> #define MAXIMUM_WEIGHT 10000 /* * Required typedefs to get some meaning out of Boost code */ typedef boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, int, // for the nodes, and for the edges: boost::property<boost::edge_weight_t, int> > BoostGraph; // for the vertex-edge types typedef boost::graph_traits<BoostGraph>::vertex_descriptor BoostVertex; typedef boost::graph_traits<BoostGraph>::edge_descriptor BoostEdge; // for the iterators typedef boost::graph_traits<BoostGraph>::vertex_iterator BoostVertexIt; typedef boost::graph_traits<BoostGraph>::edge_iterator BoostEdgeIt; // for the edge-property-map (aka edge-array) typedef boost::property_map<BoostGraph, boost::edge_weight_t>::type BoostWeightMap; /* * Auxiliary function to assign random weights to an edge array */ static void assign_random_weights(const leda::graph& G, leda::edge_array<int>& weight) { leda::edge e; srand(time(NULL)); weight.init(G, 0); forall_edges(e, G) { weight[e] = rand() % MAXIMUM_WEIGHT + 1; } return; } /* * Wrapper around undirected random graph generation with random edge weights. * Calculates number-of-nodes to be the theoretical maximum so the graph would * be fully connected (aka complete). */ void connected_random_generator(leda::graph& G, const int number_of_nodes, leda::edge_array<int>& weight) { int number_of_edges = 2 * number_of_nodes * log10(number_of_nodes); leda::random_simple_undirected_graph(G, number_of_nodes, number_of_edges); assign_random_weights(G, weight); std::cout << "Graph generated. Nodes: " << number_of_nodes << std::endl; return; } /* * Function to convert an existing LEDA graph to BGL */ void leda2boost(const leda::graph& LG, BoostGraph& BG, const leda::edge_array<int>& weight) { leda::edge e; leda::node n; // a leda node array of boost vertices. wicked. leda::node_array<BoostVertex> BVs(LG); // purge the old contents and start constructing the Boost mirror BG.clear(); forall_nodes(n, LG) BVs[n] = boost::add_vertex(BG); // now attempting to add the edges between the vertices forall_edges(e, LG) { // we also add the coresponding weight every time boost::add_edge(BVs[LG.source(e)], BVs[LG.target(e)], weight[e], BG).first; } return; } /* * My implementation of Kruskal's Minimum Spanning Tree algorithm * with lists & sub-forests using course's directions * TODO: split to another file */ void my_kruskal(BoostGraph& BG, std::vector<BoostEdge> spanning_tree) { typedef boost::indirect_cmp<BoostWeightMap, std::greater<int> > weight_greater; int i = 0; BoostEdge e; BoostVertex u, v; BoostEdgeIt eit_st, eit_end; BoostVertexIt vit_st, vit_end; // we are going to use a map for easy pointer maninpulation of the other // data structures. Every edge maps to something easily changeable that way std::map<BoostVertex, int> mapper; // for the comparison BoostWeightMap Bweights; weight_greater w(Bweights); // sorted queue of edge weights std::priority_queue<BoostEdge, std::vector<BoostEdge>, weight_greater> Queue(w); // static array of dynamic vectors. Initially wee need to have one list for // each edge but then we need the ability to add more to some cells. Weird. std::vector<BoostVertex> L[num_vertices(BG)]; // first push all edges into Queue, so they would be sorted, for (boost::tie(eit_st, eit_end) = edges(BG); eit_st != eit_end; ++eit_st) Queue.push(*eit_st); // then initialize vertices to a counter in the dictionary, // then add it to the required list. We have |edges| number of lists. for (boost::tie(vit_st, vit_end) = vertices(BG); vit_st != vit_end; ++vit_st) { mapper[*vit_st] = i; L[i].push_back(*vit_st); i++; } // iterating over queue while (!Queue.empty()) { e = Queue.top(); Queue.pop(); u = source(e, BG); v = target(e, BG); if (L[mapper[u]].front() == L[mapper[v]].front()) { // There is gonna be a circle if we add this edge // TODO } else { // No circle occuring // all check, add it to the returned vector spanning_tree.push_back(e); } } return; } /* * Main function to run all the MST versions and benchmark their time. * It's responsible for the LEDA2Boost transformation and for the benchmarking. */ static void benchmark_implementations(const leda::graph& G, const leda::edge_array<int>& weight) { float T; BoostGraph BG; std::vector<BoostEdge> spanning_tree; // LEDA T = leda::used_time(); leda::MIN_SPANNING_TREE(G, weight); std::cout << "\t\tLEDA MST calculation time: " << leda::used_time(T) << std::endl; // Transform to Boost std::cout << "\tTransforming LEDA graph... "; leda2boost(G, BG, weight); std::cout << "Done." << std::endl; // Boost leda::used_time(T); kruskal_minimum_spanning_tree(BG, std::back_inserter(spanning_tree)); std::cout << "\t\tBoost MST calculation time: " << leda::used_time(T) << std::endl; // My Boost implementation benchmarking spanning_tree.clear(); my_kruskal(BG, spanning_tree); std::cout << "\t\tMy-Boost MST calculation time: " << leda::used_time(T) << std::endl; return; } int main(int argc, char **argv) { int i, n; leda::graph G; leda::edge_array<int> weight; unsigned int N[] = { 10000, 40000, 70000 }; if (argc > 2 && !strcmp(argv[1], "-n")) { // for custom nodes n = atoi(argv[2]); connected_random_generator(G, n, weight); benchmark_implementations(G, weight); } else { std::cout << "\n-=-=-=-=- Minimum Spanning Tree Benchmarking -=-=-=-=-\n"; std::cout << "Give -n <number of nodes> if you want custom nodes\n"; std::cout << "Moving on with the default number of nodes...\n\n"; std::cout << ">>> Random graphs..." << std::endl; for (i = 0; i < 3; i++) { connected_random_generator(G, N[i], weight); benchmark_implementations(G, weight); // clean up G.clear(); } std::cout << ">>> Grid graphs..." << std::endl; N[0] = 100; N[1] = 200; N[2] = 300; for (i = 0; i < 3; i++) { leda::grid_graph(G, N[i]); // nasty hack, bacause LEDA cannot produce an undirected grid // graph, so we make them bidirectional. G.make_bidirected(); assign_random_weights(G, weight); std::cout << "Graph generated. " << N[i] << "x" << N[i] << " nodes" << std::endl; benchmark_implementations(G, weight); // clean up G.clear(); } } return 0; } <commit_msg>finish implementation. it is *very* slow<commit_after>// // George 'papanikge' Papanikolaou // CEID Advance Algorithm Design Course 2014 // Benchmarking of Minimum Spanning Tree algorithms with Boost & LEDA // #include <iostream> #include <vector> #include <map> #include <cstdlib> #include <cmath> #include <cstring> #include <ctime> #include <LEDA/graph/graph.h> #include <LEDA/graph/graph_gen.h> #include <LEDA/graph/min_span.h> #include <LEDA/system/timer.h> #include <boost/array.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/kruskal_min_spanning_tree.hpp> #define MAXIMUM_WEIGHT 10000 /* * Required typedefs to get some meaning out of Boost code */ typedef boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS, int, // for the nodes, and for the edges: boost::property<boost::edge_weight_t, int> > BoostGraph; // for the vertex-edge types typedef boost::graph_traits<BoostGraph>::vertex_descriptor BoostVertex; typedef boost::graph_traits<BoostGraph>::edge_descriptor BoostEdge; // for the iterators typedef boost::graph_traits<BoostGraph>::vertex_iterator BoostVertexIt; typedef boost::graph_traits<BoostGraph>::edge_iterator BoostEdgeIt; // for the edge-property-map (aka edge-array) typedef boost::property_map<BoostGraph, boost::edge_weight_t>::type BoostWeightMap; /* * Auxiliary function to assign random weights to an edge array */ static void assign_random_weights(const leda::graph& G, leda::edge_array<int>& weight) { leda::edge e; srand(time(NULL)); weight.init(G, 0); forall_edges(e, G) { weight[e] = rand() % MAXIMUM_WEIGHT + 1; } return; } /* * Wrapper around undirected random graph generation with random edge weights. * Calculates number-of-nodes to be the theoretical maximum so the graph would * be fully connected (aka complete). */ void connected_random_generator(leda::graph& G, const int number_of_nodes, leda::edge_array<int>& weight) { int number_of_edges = 2 * number_of_nodes * log10(number_of_nodes); leda::random_simple_undirected_graph(G, number_of_nodes, number_of_edges); assign_random_weights(G, weight); std::cout << "Graph generated. Nodes: " << number_of_nodes << std::endl; return; } /* * Function to convert an existing LEDA graph to BGL */ void leda2boost(const leda::graph& LG, BoostGraph& BG, const leda::edge_array<int>& weight) { leda::edge e; leda::node n; // a leda node array of boost vertices. wicked. leda::node_array<BoostVertex> BVs(LG); // purge the old contents and start constructing the Boost mirror BG.clear(); forall_nodes(n, LG) BVs[n] = boost::add_vertex(BG); // now attempting to add the edges between the vertices forall_edges(e, LG) { // we also add the coresponding weight every time boost::add_edge(BVs[LG.source(e)], BVs[LG.target(e)], weight[e], BG).first; } return; } /* * My implementation of Kruskal's Minimum Spanning Tree algorithm * with lists & sub-forests using course's directions * TODO: split to another file */ void my_kruskal(BoostGraph& BG, std::vector<BoostEdge> spanning_tree) { typedef boost::indirect_cmp<BoostWeightMap, std::greater<int> > weight_greater; int i = 0; BoostEdge e; BoostVertex u, v; BoostEdgeIt eit_st, eit_end; BoostVertexIt vit_st, vit_end; // we are going to use a map for easy pointer maninpulation of the other // data structures. Every edge maps to something easily changeable that way std::map<BoostVertex, int> mapper; // for the comparison BoostWeightMap Bweights; weight_greater w(Bweights); // sorted queue of edge weights std::priority_queue<BoostEdge, std::vector<BoostEdge>, weight_greater> Queue(w); // static array of dynamic vectors. Initially wee need to have one list for // each edge but then we need the ability to add more to some cells. Weird. std::vector<BoostVertex> L[num_vertices(BG)]; // first push all edges into Queue, so they would be sorted, for (boost::tie(eit_st, eit_end) = edges(BG); eit_st != eit_end; ++eit_st) Queue.push(*eit_st); // then initialize vertices to a counter in the dictionary, // then add it to the required list. We have |edges| number of lists. for (boost::tie(vit_st, vit_end) = vertices(BG); vit_st != vit_end; ++vit_st) { mapper[*vit_st] = i; L[i].push_back(*vit_st); i++; } // iterating over queue while (!Queue.empty() && spanning_tree.size() < (num_edges(BG) - 1)) { e = Queue.top(); Queue.pop(); u = source(e, BG); v = target(e, BG); if (L[mapper[u]].front() != L[mapper[v]].front()) { // No circle occuring, we can add the edge to the MST spanning_tree.push_back(e); // merge lists for the next iteration L[mapper[u]].insert(L[mapper[u]].end(), L[mapper[v]].begin(), L[mapper[v]].end()); // and the maps of course mapper[v] = mapper[u]; } } return; } /* * Main function to run all the MST versions and benchmark their time. * It's responsible for the LEDA2Boost transformation and for the benchmarking. */ static void benchmark_implementations(const leda::graph& G, const leda::edge_array<int>& weight) { float T; BoostGraph BG; std::vector<BoostEdge> spanning_tree; // LEDA T = leda::used_time(); leda::MIN_SPANNING_TREE(G, weight); std::cout << "\t\tLEDA MST calculation time: " << leda::used_time(T) << std::endl; // Transform to Boost std::cout << "\tTransforming LEDA graph... "; leda2boost(G, BG, weight); std::cout << "Done." << std::endl; // Boost leda::used_time(T); kruskal_minimum_spanning_tree(BG, std::back_inserter(spanning_tree)); std::cout << "\t\tBoost MST calculation time: " << leda::used_time(T) << std::endl; // My Boost implementation benchmarking spanning_tree.clear(); my_kruskal(BG, spanning_tree); std::cout << "\t\tMy-Boost MST calculation time: " << leda::used_time(T) << std::endl; return; } int main(int argc, char **argv) { int i, n; leda::graph G; leda::edge_array<int> weight; unsigned int N[] = { 10000, 40000, 70000 }; if (argc > 2 && !strcmp(argv[1], "-n")) { // for custom nodes n = atoi(argv[2]); connected_random_generator(G, n, weight); benchmark_implementations(G, weight); } else { std::cout << "\n-=-=-=-=- Minimum Spanning Tree Benchmarking -=-=-=-=-\n"; std::cout << "Give -n <number of nodes> if you want custom nodes\n"; std::cout << "Moving on with the default number of nodes...\n\n"; std::cout << ">>> Random graphs..." << std::endl; for (i = 0; i < 3; i++) { connected_random_generator(G, N[i], weight); benchmark_implementations(G, weight); // clean up G.clear(); } std::cout << ">>> Grid graphs..." << std::endl; N[0] = 100; N[1] = 200; N[2] = 300; for (i = 0; i < 3; i++) { leda::grid_graph(G, N[i]); // nasty hack, bacause LEDA cannot produce an undirected grid // graph, so we make them bidirectional. G.make_bidirected(); assign_random_weights(G, weight); std::cout << "Graph generated. " << N[i] << "x" << N[i] << " nodes" << std::endl; benchmark_implementations(G, weight); // clean up G.clear(); } } return 0; } <|endoftext|>
<commit_before>#include "CounterpointNode.hpp" #include "System.hpp" #include "Conversions.hpp" #include <boost/numeric/ublas/operation.hpp> namespace csound { CounterpointNode::CounterpointNode() : generationMode(GenerateCounterpoint), musicMode(Counterpoint::Aeolian), species(Counterpoint::Two), voices(2), secondsPerPulse(0.5) { FillRhyPat(); Counterpoint::messageCallback = System::getMessageCallback(); } CounterpointNode::~CounterpointNode() { } void CounterpointNode::produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates) { // Make a local copy of the child notes. Score source; source.insert(source.begin(), score.begin() + beginAt, score.begin() + endAt); System::message("Original source notes: %d\n", source.size()); // Remove the child notes from the target. score.erase(score.begin() + beginAt, score.begin() + endAt); // Select the cantus firmus. source.sort(); std::vector<int> cantus; std::vector<int> voicebeginnings(voices); // Take notes in sequence, quantized on time, as the cantus. // If there are chords, pick the best fitting note in the chord and discard the others. std::vector< std::vector<int> > chords; double time = -1; double oldTime = 0; for (size_t i = 0; i < source.size(); i++) { oldTime = time; time = std::floor((source[i].getTime() / secondsPerPulse) + 0.5) * secondsPerPulse; if (oldTime != time) { std::vector<int> newchord; chords.push_back(newchord); } chords.back().push_back(int(source[i].getKey())); } for(size_t i = 0, n = chords.size(); i < n; i++) { int bestfit = chords[i].front(); int oldDifference = 0; for(size_t j = 1; j < chords[i].size(); j++) { int difference = std::abs(bestfit - chords[i][j]); oldDifference = difference; if (difference > 0 && difference < oldDifference) { bestfit = chords[i][j]; } } cantus.push_back(bestfit); } System::message("Cantus firmus notes: %d\n", source.size()); if(voiceBeginnings.size() > 0) { voicebeginnings.resize(voices); for (size_t i = 0; i < voices; i++) { voicebeginnings[i] = voiceBeginnings[i]; System::message("Voice %d begins at key %d\n", (i + 1), voicebeginnings[i]); } } else { voicebeginnings.resize(voices); int range = HighestSemitone - LowestSemitone; int voicerange = range / (voices + 1); System::message("Cantus begins at key %d\n", cantus[0]); int c = cantus[0]; for (size_t i = 0; i < voices; i++) { voicebeginnings[i] = c + ((i + 1) * voicerange); System::message("Voice %d begins at key %d\n", (i + 1), voicebeginnings[i]); } } // Generate the counterpoint. counterpoint(musicMode, &voicebeginnings[0], voices, cantus.size(), species, &cantus[0]); // Translate the counterpoint back to a Score. double duration = 0.; double key = 0.; double velocity = 70.; double phase = 0.; double x = 0.; double y = 0.; double z = 0.; double pcs = 4095.0; Score generated; for(size_t voice = 0; voice <= voices; voice++) { double time = 0; for(int note = 1; note <= TotalNotes[voice]; note++) { time = double(Onset[note][voice]); time *= secondsPerPulse; duration = double(Dur[note][voice]); duration *= secondsPerPulse; key = double(Ctrpt[note][voice]); // Set the exact pitch class so that something of the counterpoint will be preserved if the tessitura is rescaled. pcs = Conversions::midiToPitchClass(key); System::message("%f %f %f %f %f %f %f %f %f %f %f\n", time, duration, double(144), double(voice), key, velocity, phase, x, y, z, pcs); generated.append(time, duration, double(144), double(voice), key, velocity, phase, x, y, z, pcs); } } // Get the right coordinate system going. System::message("Total notes in generated counterpoint: %d\n", generated.size()); ublas::matrix<double> localCoordinates = getLocalCoordinates(); ublas::matrix<double> compositeCoordinates = getLocalCoordinates(); ublas::axpy_prod(globalCoordinates, localCoordinates, compositeCoordinates); Event e; for (int i = 0, n = generated.size(); i < n; i++) { ublas::axpy_prod(compositeCoordinates, generated[i], e); generated[i] = e; } // Put the generated counterpoint (back?) into the target score. score.insert(score.end(), generated.begin(), generated.end()); initialize(1, 1); } } <commit_msg>no message<commit_after>#include "CounterpointNode.hpp" #include "System.hpp" #include "Conversions.hpp" #include <boost/numeric/ublas/operation.hpp> namespace csound { CounterpointNode::CounterpointNode() : generationMode(GenerateCounterpoint), musicMode(Counterpoint::Aeolian), species(Counterpoint::Two), voices(2), secondsPerPulse(0.5) { FillRhyPat(); Counterpoint::messageCallback = System::getMessageCallback(); } CounterpointNode::~CounterpointNode() { } void CounterpointNode::produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates) { // Make a local copy of the child notes. Score source; source.insert(source.begin(), score.begin() + beginAt, score.begin() + endAt); System::message("Original source notes: %d\n", source.size()); // Remove the child notes from the target. score.erase(score.begin() + beginAt, score.begin() + endAt); // Select the cantus firmus. source.sort(); std::vector<int> cantus; std::vector<int> voicebeginnings(voices); // Take notes in sequence, quantized on time, as the cantus. // If there are chords, pick the best fitting note in the chord and discard the others. std::vector< std::vector<int> > chords; double time = -1; double oldTime = 0; for (size_t i = 0; i < source.size(); i++) { oldTime = time; time = std::floor((source[i].getTime() / secondsPerPulse) + 0.5) * secondsPerPulse; if (oldTime != time) { std::vector<int> newchord; chords.push_back(newchord); } chords.back().push_back(int(source[i].getKey())); } for(size_t i = 0, n = chords.size(); i < n; i++) { int bestfit = chords[i].front(); int oldDifference = 0; for(size_t j = 1; j < chords[i].size(); j++) { int difference = std::abs(bestfit - chords[i][j]); oldDifference = difference; if (difference > 0 && difference < oldDifference) { bestfit = chords[i][j]; } } cantus.push_back(bestfit); } System::message("Cantus firmus notes: %d\n", source.size()); if(voiceBeginnings.size() > 0) { voicebeginnings.resize(voices); for (size_t i = 0; i < voices; i++) { voicebeginnings[i] = voiceBeginnings[i]; System::message("Voice %d begins at key %d\n", (i + 1), voicebeginnings[i]); } } else { voicebeginnings.resize(voices); int range = HighestSemitone - LowestSemitone; int voicerange = range / (voices + 1); System::message("Cantus begins at key %d\n", cantus[0]); int c = cantus[0]; for (size_t i = 0; i < voices; i++) { voicebeginnings[i] = c + ((i + 1) * voicerange); System::message("Voice %d begins at key %d\n", (i + 1), voicebeginnings[i]); } } // Generate the counterpoint. counterpoint(musicMode, &voicebeginnings[0], voices, cantus.size(), species, &cantus[0]); // Translate the counterpoint back to a Score. double duration = 0.; double key = 0.; double velocity = 70.; double phase = 0.; double x = 0.; double y = 0.; double z = 0.; double pcs = 4095.0; Score generated; for(size_t voice = 0; voice <= voices; voice++) { double time = 0; for(int note = 1; note <= TotalNotes[voice]; note++) { time = double(Onset[note][voice]); time *= secondsPerPulse; duration = double(Dur[note][voice]); duration *= secondsPerPulse; key = double(Ctrpt[note][voice]); // Set the exact pitch class so that something of the counterpoint will be preserved if the tessitura is rescaled. pcs = Conversions::midiToPitchClass(key); System::message("%f %f %f %f %f %f %f %f %f %f %f\n", time, duration, double(144), double(voice), key, velocity, phase, x, y, z, pcs); generated.append(time, duration, double(144), double(voice), key, velocity, phase, x, y, z, pcs); } } // Get the right coordinate system going. System::message("Total notes in generated counterpoint: %d\n", generated.size()); ublas::matrix<double> localCoordinates = getLocalCoordinates(); ublas::matrix<double> compositeCoordinates = getLocalCoordinates(); ublas::axpy_prod(globalCoordinates, localCoordinates, compositeCoordinates); Event e; for (int i = 0, n = generated.size(); i < n; i++) { ublas::axpy_prod(compositeCoordinates, generated[i], e); generated[i] = e; } // Put the generated counterpoint (back?) into the target score. score.insert(score.end(), generated.begin(), generated.end()); // Free up memory that was used. Counterpoint::clear(); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 noexpandtab: */ /******************************************************************************* * FShell 2 * Copyright 2009 Michael Tautschnig, tautschnig@forsyte.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /*! \file fshell2/command/command_processing.t.cpp * \brief TODO * * $Id$ * \author Michael Tautschnig <tautschnig@forsyte.de> * \date Thu Apr 2 17:29:39 CEST 2009 */ #include <diagnostics/unittest.hpp> #include <fshell2/config/config.hpp> #include <fshell2/config/annotations.hpp> #include <fstream> #include <cbmc/src/util/config.h> #include <cbmc/src/langapi/language_ui.h> #include <fshell2/command/command_processing.hpp> #include <fshell2/exception/command_processing_error.hpp> #define TEST_COMPONENT_NAME Command_Processing #define TEST_COMPONENT_NAMESPACE fshell2::command FSHELL2_NAMESPACE_BEGIN; FSHELL2_COMMAND_NAMESPACE_BEGIN; /** @cond */ TEST_NAMESPACE_BEGIN; TEST_COMPONENT_TEST_NAMESPACE_BEGIN; /** @endcond */ using namespace ::diagnostics::unittest; //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_basic( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::std::ostringstream os; using ::fshell2::command::Command_Processing; TEST_ASSERT(Command_Processing::NO_CONTROL_COMMAND == Command_Processing::get_instance().process(l, os, "quit HELP")); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, " // comment")); TEST_ASSERT(Command_Processing::QUIT == Command_Processing::get_instance().process(l, os, "quit")); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_help( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::std::ostringstream os; using ::fshell2::command::Command_Processing; TEST_ASSERT(Command_Processing::HELP == Command_Processing::get_instance().process(l, os, "help")); TEST_ASSERT(Command_Processing::HELP == Command_Processing::get_instance().process(l, os, " HELP ")); Command_Processing::help(os); TEST_ASSERT(data.compare("command_help", os.str())); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_invalid( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::std::ostringstream os; using ::fshell2::command::Command_Processing; TEST_THROWING_BLOCK_ENTER; Command_Processing::get_instance().process(l, os, "add sourcecode \"no_such_file.c\""); TEST_THROWING_BLOCK_EXIT1(::fshell2::Command_Processing_Error, "Failed to parse no_such_file.c"); TEST_THROWING_BLOCK_ENTER; Command_Processing::get_instance().finalize(l, os); TEST_THROWING_BLOCK_EXIT1(::fshell2::Command_Processing_Error, "No source files loaded!"); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_use_case( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::optionst options; ::goto_functionst cfg; ::std::ostringstream os; using ::fshell2::command::Command_Processing; Command_Processing::get_instance().set_options(options); Command_Processing::get_instance().set_cfg(cfg); char * tempname(::strdup("/tmp/srcXXXXXX")); TEST_CHECK(-1 != ::mkstemp(tempname)); ::std::string tempname_str(tempname); tempname_str += ".c"; ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "int main(int argc, char * argv[])" << ::std::endl << "{" << ::std::endl << "return 0;" << ::std::endl << "}" << ::std::endl; of.close(); ::unlink(tempname); ::free(tempname); ::std::ostringstream cmd_str; cmd_str << "add sourcecode \"" << tempname_str << "\""; TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, cmd_str.str().c_str())); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "show filenames")); TEST_ASSERT(!os.str().empty()); os.str(""); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "show sourcecode all")); TEST_ASSERT(data.compare("tmp_source_show_all", os.str())); cmd_str.str(""); cmd_str << "show sourcecode \"" << tempname_str << "\""; os.str(""); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, cmd_str.str().c_str())); TEST_ASSERT(data.compare("tmp_source_show", os.str())); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set entry main")); TEST_ASSERT(::config.main == "main"); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set limit count 27")); TEST_ASSERT(27 == ::config.fshell.max_test_cases); ::unlink(tempname_str.c_str()); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_use_case_extended_invariants( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::optionst options; ::goto_functionst cfg; ::std::ostringstream os; using ::fshell2::command::Command_Processing; Command_Processing::get_instance().set_options(options); Command_Processing::get_instance().set_cfg(cfg); { char * tempname(::strdup("/tmp/srcXXXXXX")); TEST_CHECK(-1 != ::mkstemp(tempname)); ::std::string tempname_str(tempname); tempname_str += ".c"; ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "int foo();" << ::std::endl << "int main(int argc, char * argv[])" << ::std::endl << "{" << ::std::endl << "return foo();" << ::std::endl << "}" << ::std::endl; of.close(); ::unlink(tempname); ::free(tempname); ::std::ostringstream cmd_str; cmd_str << "add sourcecode \"" << tempname_str << "\""; TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, cmd_str.str().c_str())); ::unlink(tempname_str.c_str()); } TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set entry main")); TEST_ASSERT(::config.main == "main"); // do it once again TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set entry main")); TEST_ASSERT(0 == ::config.fshell.max_test_cases); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set limit count 27")); TEST_ASSERT(27 == ::config.fshell.max_test_cases); TEST_CHECK(cfg.function_map.end() != cfg.function_map.find("c::foo")); TEST_CHECK(!cfg.function_map.find("c::foo")->second.body_available); { char * tempname(::strdup("/tmp/srcXXXXXX")); TEST_CHECK(-1 != ::mkstemp(tempname)); ::std::string tempname_str(tempname); tempname_str += "2.c"; // just to make sure we never ever get the same filename ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "int foo()" << ::std::endl << "{" << ::std::endl << "return 42;" << ::std::endl << "}" << ::std::endl; of.close(); ::unlink(tempname); ::free(tempname); ::std::ostringstream cmd_str; cmd_str << "add sourcecode \"" << tempname_str << "\""; TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, cmd_str.str().c_str())); ::unlink(tempname_str.c_str()); } Command_Processing::get_instance().finalize(l, os); TEST_CHECK(cfg.function_map.end() != cfg.function_map.find("c::foo")); TEST_CHECK(cfg.function_map.find("c::foo")->second.body_available); // should be a no-op Command_Processing::get_instance().finalize(l, os); } /** @cond */ TEST_COMPONENT_TEST_NAMESPACE_END; TEST_NAMESPACE_END; /** @endcond */ FSHELL2_COMMAND_NAMESPACE_END; FSHELL2_NAMESPACE_END; TEST_SUITE_BEGIN; TEST_NORMAL_CASE( &test_basic, LEVEL_PROD ); TEST_NORMAL_CASE( &test_help, LEVEL_PROD ); TEST_NORMAL_CASE( &test_invalid, LEVEL_PROD ); TEST_NORMAL_CASE( &test_use_case, LEVEL_PROD ); TEST_NORMAL_CASE( &test_use_case_extended_invariants, LEVEL_PROD ); TEST_SUITE_END; STREAM_TEST_SYSTEM_MAIN; <commit_msg>Fixed bug in test case<commit_after>/* -*- Mode: C++; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 noexpandtab: */ /******************************************************************************* * FShell 2 * Copyright 2009 Michael Tautschnig, tautschnig@forsyte.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /*! \file fshell2/command/command_processing.t.cpp * \brief TODO * * $Id$ * \author Michael Tautschnig <tautschnig@forsyte.de> * \date Thu Apr 2 17:29:39 CEST 2009 */ #include <diagnostics/unittest.hpp> #include <fshell2/config/config.hpp> #include <fshell2/config/annotations.hpp> #include <fstream> #include <cbmc/src/util/config.h> #include <cbmc/src/langapi/language_ui.h> #include <fshell2/command/command_processing.hpp> #include <fshell2/exception/command_processing_error.hpp> #define TEST_COMPONENT_NAME Command_Processing #define TEST_COMPONENT_NAMESPACE fshell2::command FSHELL2_NAMESPACE_BEGIN; FSHELL2_COMMAND_NAMESPACE_BEGIN; /** @cond */ TEST_NAMESPACE_BEGIN; TEST_COMPONENT_TEST_NAMESPACE_BEGIN; /** @endcond */ using namespace ::diagnostics::unittest; //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_basic( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::std::ostringstream os; using ::fshell2::command::Command_Processing; TEST_ASSERT(Command_Processing::NO_CONTROL_COMMAND == Command_Processing::get_instance().process(l, os, "quit HELP")); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, " // comment")); TEST_ASSERT(Command_Processing::QUIT == Command_Processing::get_instance().process(l, os, "quit")); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_help( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::std::ostringstream os; using ::fshell2::command::Command_Processing; TEST_ASSERT(Command_Processing::HELP == Command_Processing::get_instance().process(l, os, "help")); TEST_ASSERT(Command_Processing::HELP == Command_Processing::get_instance().process(l, os, " HELP ")); Command_Processing::help(os); TEST_ASSERT(data.compare("command_help", os.str())); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_invalid( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::optionst options; ::goto_functionst cfg; ::std::ostringstream os; using ::fshell2::command::Command_Processing; Command_Processing::get_instance().set_options(options); Command_Processing::get_instance().set_cfg(cfg); TEST_THROWING_BLOCK_ENTER; Command_Processing::get_instance().process(l, os, "add sourcecode \"no_such_file.c\""); TEST_THROWING_BLOCK_EXIT1(::fshell2::Command_Processing_Error, "Failed to parse no_such_file.c"); TEST_THROWING_BLOCK_ENTER; Command_Processing::get_instance().finalize(l, os); TEST_THROWING_BLOCK_EXIT1(::fshell2::Command_Processing_Error, "No source files loaded!"); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_use_case( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::optionst options; ::goto_functionst cfg; ::std::ostringstream os; using ::fshell2::command::Command_Processing; Command_Processing::get_instance().set_options(options); Command_Processing::get_instance().set_cfg(cfg); char * tempname(::strdup("/tmp/srcXXXXXX")); TEST_CHECK(-1 != ::mkstemp(tempname)); ::std::string tempname_str(tempname); tempname_str += ".c"; ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "int main(int argc, char * argv[])" << ::std::endl << "{" << ::std::endl << "return 0;" << ::std::endl << "}" << ::std::endl; of.close(); ::unlink(tempname); ::free(tempname); ::std::ostringstream cmd_str; cmd_str << "add sourcecode \"" << tempname_str << "\""; TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, cmd_str.str().c_str())); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "show filenames")); TEST_ASSERT(!os.str().empty()); os.str(""); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "show sourcecode all")); TEST_ASSERT(data.compare("tmp_source_show_all", os.str())); cmd_str.str(""); cmd_str << "show sourcecode \"" << tempname_str << "\""; os.str(""); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, cmd_str.str().c_str())); TEST_ASSERT(data.compare("tmp_source_show", os.str())); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set entry main")); TEST_ASSERT(::config.main == "main"); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set limit count 27")); TEST_ASSERT(27 == ::config.fshell.max_test_cases); ::unlink(tempname_str.c_str()); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of Command_Processing * */ void test_use_case_extended_invariants( Test_Data & data ) { ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l(cmdline); ::optionst options; ::goto_functionst cfg; ::std::ostringstream os; using ::fshell2::command::Command_Processing; Command_Processing::get_instance().set_options(options); Command_Processing::get_instance().set_cfg(cfg); { char * tempname(::strdup("/tmp/srcXXXXXX")); TEST_CHECK(-1 != ::mkstemp(tempname)); ::std::string tempname_str(tempname); tempname_str += ".c"; ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "int foo();" << ::std::endl << "int main(int argc, char * argv[])" << ::std::endl << "{" << ::std::endl << "return foo();" << ::std::endl << "}" << ::std::endl; of.close(); ::unlink(tempname); ::free(tempname); ::std::ostringstream cmd_str; cmd_str << "add sourcecode \"" << tempname_str << "\""; TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, cmd_str.str().c_str())); ::unlink(tempname_str.c_str()); } TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set entry main")); TEST_ASSERT(::config.main == "main"); // do it once again TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set entry main")); TEST_ASSERT(0 == ::config.fshell.max_test_cases); TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, "set limit count 27")); TEST_ASSERT(27 == ::config.fshell.max_test_cases); TEST_CHECK(cfg.function_map.end() != cfg.function_map.find("c::foo")); TEST_CHECK(!cfg.function_map.find("c::foo")->second.body_available); { char * tempname(::strdup("/tmp/srcXXXXXX")); TEST_CHECK(-1 != ::mkstemp(tempname)); ::std::string tempname_str(tempname); tempname_str += "2.c"; // just to make sure we never ever get the same filename ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "int foo()" << ::std::endl << "{" << ::std::endl << "return 42;" << ::std::endl << "}" << ::std::endl; of.close(); ::unlink(tempname); ::free(tempname); ::std::ostringstream cmd_str; cmd_str << "add sourcecode \"" << tempname_str << "\""; TEST_ASSERT(Command_Processing::DONE == Command_Processing::get_instance().process(l, os, cmd_str.str().c_str())); ::unlink(tempname_str.c_str()); } Command_Processing::get_instance().finalize(l, os); TEST_CHECK(cfg.function_map.end() != cfg.function_map.find("c::foo")); TEST_CHECK(cfg.function_map.find("c::foo")->second.body_available); // should be a no-op Command_Processing::get_instance().finalize(l, os); } /** @cond */ TEST_COMPONENT_TEST_NAMESPACE_END; TEST_NAMESPACE_END; /** @endcond */ FSHELL2_COMMAND_NAMESPACE_END; FSHELL2_NAMESPACE_END; TEST_SUITE_BEGIN; TEST_NORMAL_CASE( &test_basic, LEVEL_PROD ); TEST_NORMAL_CASE( &test_help, LEVEL_PROD ); TEST_NORMAL_CASE( &test_invalid, LEVEL_PROD ); TEST_NORMAL_CASE( &test_use_case, LEVEL_PROD ); TEST_NORMAL_CASE( &test_use_case_extended_invariants, LEVEL_PROD ); TEST_SUITE_END; STREAM_TEST_SYSTEM_MAIN; <|endoftext|>
<commit_before>#pragma once #include "IValidator.hpp" #include "../StructuresCommon.hpp" class QString; namespace data{ class TextFieldValidator : public IFieldValidator<String> { public: TextFieldValidator(); TextFieldValidator( size_t minLength, size_t maxLength ); virtual bool isValid(const String &data) const; bool isValid( const QString &data ) const; bool isValid( const char* data) const; bool hasValidLength(const String &data) const; size_t maxNickNameLength() const; void setMaxNickNameLength(const size_t &maxNickNameLength); size_t minNickNameLength() const; void setMinNickNameLength(const size_t &minNickNameLength); private: size_t m_maxNickNameLength; size_t m_minNickNameLength; }; } <commit_msg>refactor text validator<commit_after>#pragma once #include "IValidator.hpp" #include "../StructuresCommon.hpp" class QString; ///TODO add some tests for validator namespace data{ class TextFieldValidator : public IFieldValidator<String> { public: TextFieldValidator(); TextFieldValidator( size_t minLength, size_t maxLength ); virtual bool isValid(const String &data) const; bool isValid( const QString &data ) const; bool isValid( const char* data) const; bool hasValidLength(const String &data) const; size_t maxNickNameLength() const; void setMaxNickNameLength(const size_t &maxNickNameLength); size_t minNickNameLength() const; void setMinNickNameLength(const size_t &minNickNameLength); private: size_t m_maxNickNameLength; size_t m_minNickNameLength; }; } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_LA_SOLVER_STUFF_HH #define DUNE_STUFF_LA_SOLVER_STUFF_HH #include <type_traits> #include <cmath> #if HAVE_DUNE_ISTL # include <dune/istl/operators.hh> # include <dune/istl/preconditioners.hh> # include <dune/istl/solvers.hh> # include <dune/istl/paamg/amg.hh> #endif // HAVE_DUNE_ISTL #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configtree.hh> #include <dune/stuff/la/container/istl.hh> #include "../solver.hh" namespace Dune { namespace Stuff { namespace LA { #if HAVE_DUNE_ISTL template< class S, class CommunicatorType > class Solver< IstlRowMajorSparseMatrix< S >, CommunicatorType > : protected SolverUtils { public: typedef IstlRowMajorSparseMatrix< S > MatrixType; #if !HAVE_MPI Solver(const MatrixType& matrix) : matrix_(matrix) {} #endif // !HAVE_MPI Solver(const MatrixType& matrix, const CommunicatorType& #if HAVE_MPI communicator #else /*communicator*/ #endif ) : matrix_(matrix) #if HAVE_MPI , communicator_(communicator) #endif {} static std::vector< std::string > options() { return { "bicgstab.amg.ilu0" #if !HAVE_MPI , "bicgstab.ilut" #endif }; } // ... options() static Common::ConfigTree options(const std::string& type) { SolverUtils::check_given(type, options()); Common::ConfigTree iterative_options({"max_iter", "precision", "verbose"}, {"10000", "1e-10", "0"}); #if !HAVE_MPI iterative_options.set("post_check_solves_system", "1e-5"); #endif if (type == "bicgstab.amg.ilu0") { iterative_options.set("smoother.iterations", "1"); iterative_options.set("smoother.relaxation_factor", "1"); iterative_options.set("preconditioner.max_level", "100"); iterative_options.set("preconditioner.coarse_target", "1000"); iterative_options.set("preconditioner.min_coarse_rate", "1.2"); iterative_options.set("preconditioner.prolong_damp", "1.6"); iterative_options.set("preconditioner.anisotropy_dim", "2"); iterative_options.set("preconditioner.isotropy_dim", "2"); iterative_options.set("preconditioner.verbose", "1"); iterative_options.set("smoother.verbose", "1"); #if !HAVE_MPI } else if (type == "bicgstab.ilut") { iterative_options.set("preconditioner.iterations", "2"); iterative_options.set("preconditioner.relaxation_factor", "1.0"); #endif // !HAVE_MPI } else DUNE_THROW_COLORFULLY(Exceptions::internal_error, "Given type '" << type << "' is not supported, although it was reported by options()!"); iterative_options.set("type", type); return iterative_options; } // ... options(...) void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution) const { apply(rhs, solution, options()[0]); } void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution, const std::string& type) const { apply(rhs, solution, options(type)); } /** * \note does a copy of the rhs */ void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution, const Common::ConfigTree& opts) const { if (!opts.has_key("type")) DUNE_THROW_COLORFULLY(Exceptions::configuration_error, "Given options (see below) need to have at least the key 'type' set!\n\n" << opts); const auto type = opts.get< std::string >("type"); SolverUtils::check_given(type, options()); const Common::ConfigTree default_opts = options(type); IstlDenseVector< S > writable_rhs = rhs.copy(); // solve if (type == "bicgstab.amg.ilu0") { #if HAVE_MPI typedef typename MatrixType::BackendType IstlMatrixType; typedef typename IstlDenseVector< S >::BackendType IstlVectorType; typedef SeqILU0< IstlMatrixType, IstlVectorType, IstlVectorType, 1 > SequentialSmootherType; typedef BlockPreconditioner< IstlVectorType, IstlVectorType, CommunicatorType, SequentialPreconditionerType> SmootherType; typedef OverlappingSchwarzOperator< IstlMatrixType, IstlVectorType, IstlVectorType, CommunicatorType > MatrixOperatorType; MatrixOperatorType matrix_operator(matrix_.backend(), communicator_); Amg::Parameters criterion_parameters(opts.get("preconditioner.max_level", default_opts.get< size_t >("preconditioner.max_level")), opts.get("preconditioner.coarse_target", default_opts.get< size_t >("preconditioner.coarse_target")), opts.get("preconditioner.min_coarse_rate", default_opts.get< S >("preconditioner.min_coarse_rate")), opts.get("preconditioner.prolong_damp", default_opts.get< S >("preconditioner.prolong_damp"))); criterion_parameters.setDefaultValuesIsotropic(opts.get("preconditioner.isotropy_dim", default_opts.get< size_t >("preconditioner.isotropy_dim"))); criterion_parameters.setDefaultValuesAnisotropic(opts.get("preconditioner.anisotropy_dim", default_opts.get< size_t >("preconditioner.anisotropy_dim"))); // <- dim criterion_parameters.setDebugLevel(opts.get("preconditioner.verbose", default_opts.get< size_t >("preconditioner.verbose"))); typename Amg::SmootherTraits< SmootherType >::Arguments smoother_arguments; smoother_arguments.iterations = opts.get("smoother.iterations", default_opts.get< size_t >("smoother.iterations")); smoother_arguments.relaxationFactor = opts.get("smoother.relaxation_factor", default_opts.get< S >("smoother.relaxation_factor")); Amg::CoarsenCriterion< Amg::SymmetricCriterion< IstlMatrixType, Amg::FirstDiagonal > > smoother_criterion(criterion_parameters); typedef Amg::AMG< MatrixOperatorType, IstlVectorType, SmootherType, CommunicatorType > PreconditionerType; PreconditionerType preconditioner(matrix_operator, smoother_criterion, smoother_arguments, communicator_); OverlappingSchwarzScalarProduct< IstlVectorType, CommunicatorType > scalar_product(communicator_); InverseOperatorResult statistics; BiCGSTABSolver< IstlVectorType > solver(matrix_operator, scalar_product, preconditioner, opts.get("precision", default_opts.get< S >("precision")), opts.get("max_iter", default_opts.get< size_t >("max_iter")), (communicator_.communicator().rank() == 0) ? opts.get("verbose", default_opts.get< int >("verbose")) : 0); solver.apply(solution.backend(), writable_rhs.backend(), statistics); if (!statistics.converged) DUNE_THROW_COLORFULLY(Exceptions::linear_solver_failed_bc_it_did_not_converge, "The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n" << "Those were the given options:\n\n" << opts); #else // HAVE_MPI typedef MatrixAdapter< typename MatrixType::BackendType, typename IstlDenseVector< S >::BackendType, typename IstlDenseVector< S >::BackendType > MatrixOperatorType; MatrixOperatorType matrix_operator(matrix_.backend()); typedef SeqILU0< typename MatrixType::BackendType, typename IstlDenseVector< S >::BackendType, typename IstlDenseVector< S >::BackendType > SmootherType; typedef Dune::Amg::AMG< MatrixOperatorType, typename IstlDenseVector< S >::BackendType, SmootherType > PreconditionerType; Dune::SeqScalarProduct< typename IstlDenseVector< S >::BackendType > scalar_product; typedef typename Dune::Amg::SmootherTraits< SmootherType >::Arguments SmootherArgs; SmootherArgs smootherArgs; smootherArgs.iterations = opts.get("smoother.iterations", default_opts.get< size_t >("smoother.iterations")); smootherArgs.relaxationFactor = opts.get("smoother.relaxation_factor", default_opts.get< S >("smoother.relaxation_factor")); Dune::Amg::Parameters params(opts.get("preconditioner.max_level", default_opts.get< size_t >("preconditioner.max_level")), opts.get("preconditioner.coarse_target", default_opts.get< size_t >("preconditioner.coarse_target")), opts.get("preconditioner.min_coarse_rate", default_opts.get< S >("preconditioner.min_coarse_rate")), opts.get("preconditioner.prolong_damp", default_opts.get< S >("preconditioner.prolong_damp"))); params.setDefaultValuesIsotropic(opts.get("preconditioner.isotropy_dim", default_opts.get< size_t >("preconditioner.isotropy_dim"))); params.setDefaultValuesAnisotropic(opts.get("preconditioner.anisotropy_dim", default_opts.get< size_t >("preconditioner.anisotropy_dim"))); // <- dim typedef Dune::Amg::CoarsenCriterion < Dune::Amg::SymmetricCriterion< typename MatrixType::BackendType, Dune::Amg::FirstDiagonal > > AmgCriterion; AmgCriterion amg_criterion(params); amg_criterion.setDebugLevel(opts.get("preconditioner.verbose", default_opts.get< size_t >("preconditioner.verbose"))); PreconditionerType preconditioner(matrix_operator, amg_criterion, smootherArgs); typedef BiCGSTABSolver< typename IstlDenseVector< S >::BackendType > SolverType; SolverType solver(matrix_operator, scalar_product, preconditioner, opts.get("precision", default_opts.get< S >("precision")), opts.get("max_iter", default_opts.get< size_t >("max_iter")), opts.get("verbose", default_opts.get< size_t >("verbose"))); InverseOperatorResult stat; solver.apply(solution.backend(), writable_rhs.backend(), stat); if (!stat.converged) DUNE_THROW_COLORFULLY(Exceptions::linear_solver_failed_bc_it_did_not_converge, "The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n" << "Those were the given options:\n\n" << opts); #endif // HAVE_MPI #if !HAVE_MPI } else if (type == "bicgstab.ilut") { typedef MatrixAdapter< typename MatrixType::BackendType, typename IstlDenseVector< S >::BackendType, typename IstlDenseVector< S >::BackendType > MatrixOperatorType; MatrixOperatorType matrix_operator(matrix_.backend()); typedef SeqILUn< typename MatrixType::BackendType, typename IstlDenseVector< S >::BackendType, typename IstlDenseVector< S >::BackendType > PreconditionerType; PreconditionerType preconditioner(matrix_.backend(), opts.get("preconditioner.iterations", default_opts.get< size_t >("preconditioner.iterations")), opts.get("preconditioner.relaxation_factor", default_opts.get< S >("preconditioner.relaxation_factor"))); typedef BiCGSTABSolver< typename IstlDenseVector< S >::BackendType > SolverType; SolverType solver(matrix_operator, preconditioner, opts.get("precision", default_opts.get< S >("precision")), opts.get("max_iter", default_opts.get< size_t >("max_iter")), opts.get("verbose", default_opts.get< int >("verbose"))); InverseOperatorResult stat; solver.apply(solution.backend(), writable_rhs.backend(), stat); if (!stat.converged) DUNE_THROW_COLORFULLY(Exceptions::linear_solver_failed_bc_it_did_not_converge, "The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n" << "Those were the given options:\n\n" << opts); #endif // !HAVE_MPI } else DUNE_THROW_COLORFULLY(Exceptions::internal_error, "Given type '" << type << "' is not supported, although it was reported by options()!"); #if !HAVE_MPI // check (use writable_rhs as tmp) const S post_check_solves_system_theshhold = opts.get("post_check_solves_system", default_opts.get< S >("post_check_solves_system")); if (post_check_solves_system_theshhold > 0) { matrix_.mv(solution, writable_rhs); writable_rhs -= rhs; const S sup_norm = writable_rhs.sup_norm(); if (sup_norm > post_check_solves_system_theshhold || std::isnan(sup_norm) || std::isinf(sup_norm)) DUNE_THROW_COLORFULLY(Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system, "The computed solution does not solve the system (although the dune-istl backend " << "reported no error) and you requested checking (see options below)!\n" << "If you want to disable this check, set 'post_check_solves_system = 0' in the options." << "\n\n" << " (A * x - b).sup_norm() = " << writable_rhs.sup_norm() << "\n\n" << "Those were the given options:\n\n" << opts); } #endif // !HAVE_MPI } // ... apply(...) private: const MatrixType& matrix_; #if HAVE_MPI const CommunicatorType& communicator_; #endif }; // class Solver #else // HAVE_DUNE_ISTL template< class S > class Solver< IstlRowMajorSparseMatrix< S > >{ static_assert(Dune::AlwaysFalse< S >::value, "You are missing dune-istl!"); }; #endif // HAVE_DUNE_ISTL } // namespace LA } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_LA_SOLVER_STUFF_HH <commit_msg>fixup! [solver.istl] re-fix more names<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_LA_SOLVER_STUFF_HH #define DUNE_STUFF_LA_SOLVER_STUFF_HH #include <type_traits> #include <cmath> #if HAVE_DUNE_ISTL # include <dune/istl/operators.hh> # include <dune/istl/preconditioners.hh> # include <dune/istl/solvers.hh> # include <dune/istl/paamg/amg.hh> #endif // HAVE_DUNE_ISTL #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configtree.hh> #include <dune/stuff/la/container/istl.hh> #include "../solver.hh" namespace Dune { namespace Stuff { namespace LA { #if HAVE_DUNE_ISTL template< class S, class CommunicatorType > class Solver< IstlRowMajorSparseMatrix< S >, CommunicatorType > : protected SolverUtils { public: typedef IstlRowMajorSparseMatrix< S > MatrixType; #if !HAVE_MPI Solver(const MatrixType& matrix) : matrix_(matrix) {} #endif // !HAVE_MPI Solver(const MatrixType& matrix, const CommunicatorType& #if HAVE_MPI communicator #else /*communicator*/ #endif ) : matrix_(matrix) #if HAVE_MPI , communicator_(communicator) #endif {} static std::vector< std::string > options() { return { "bicgstab.amg.ilu0" #if !HAVE_MPI , "bicgstab.ilut" #endif }; } // ... options() static Common::ConfigTree options(const std::string& type) { SolverUtils::check_given(type, options()); Common::ConfigTree iterative_options({"max_iter", "precision", "verbose"}, {"10000", "1e-10", "0"}); #if !HAVE_MPI iterative_options.set("post_check_solves_system", "1e-5"); #endif if (type == "bicgstab.amg.ilu0") { iterative_options.set("smoother.iterations", "1"); iterative_options.set("smoother.relaxation_factor", "1"); iterative_options.set("preconditioner.max_level", "100"); iterative_options.set("preconditioner.coarse_target", "1000"); iterative_options.set("preconditioner.min_coarse_rate", "1.2"); iterative_options.set("preconditioner.prolong_damp", "1.6"); iterative_options.set("preconditioner.anisotropy_dim", "2"); iterative_options.set("preconditioner.isotropy_dim", "2"); iterative_options.set("preconditioner.verbose", "1"); iterative_options.set("smoother.verbose", "1"); #if !HAVE_MPI } else if (type == "bicgstab.ilut") { iterative_options.set("preconditioner.iterations", "2"); iterative_options.set("preconditioner.relaxation_factor", "1.0"); #endif // !HAVE_MPI } else DUNE_THROW_COLORFULLY(Exceptions::internal_error, "Given type '" << type << "' is not supported, although it was reported by options()!"); iterative_options.set("type", type); return iterative_options; } // ... options(...) void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution) const { apply(rhs, solution, options()[0]); } void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution, const std::string& type) const { apply(rhs, solution, options(type)); } /** * \note does a copy of the rhs */ void apply(const IstlDenseVector< S >& rhs, IstlDenseVector< S >& solution, const Common::ConfigTree& opts) const { if (!opts.has_key("type")) DUNE_THROW_COLORFULLY(Exceptions::configuration_error, "Given options (see below) need to have at least the key 'type' set!\n\n" << opts); const auto type = opts.get< std::string >("type"); SolverUtils::check_given(type, options()); const Common::ConfigTree default_opts = options(type); IstlDenseVector< S > writable_rhs = rhs.copy(); // solve if (type == "bicgstab.amg.ilu0") { #if HAVE_MPI typedef typename MatrixType::BackendType IstlMatrixType; typedef typename IstlDenseVector< S >::BackendType IstlVectorType; typedef SeqILU0< IstlMatrixType, IstlVectorType, IstlVectorType, 1 > SequentialSmootherType; typedef BlockPreconditioner< IstlVectorType, IstlVectorType, CommunicatorType, SequentialSmootherType> SmootherType; typedef OverlappingSchwarzOperator< IstlMatrixType, IstlVectorType, IstlVectorType, CommunicatorType > MatrixOperatorType; MatrixOperatorType matrix_operator(matrix_.backend(), communicator_); Amg::Parameters criterion_parameters(opts.get("preconditioner.max_level", default_opts.get< size_t >("preconditioner.max_level")), opts.get("preconditioner.coarse_target", default_opts.get< size_t >("preconditioner.coarse_target")), opts.get("preconditioner.min_coarse_rate", default_opts.get< S >("preconditioner.min_coarse_rate")), opts.get("preconditioner.prolong_damp", default_opts.get< S >("preconditioner.prolong_damp"))); criterion_parameters.setDefaultValuesIsotropic(opts.get("preconditioner.isotropy_dim", default_opts.get< size_t >("preconditioner.isotropy_dim"))); criterion_parameters.setDefaultValuesAnisotropic(opts.get("preconditioner.anisotropy_dim", default_opts.get< size_t >("preconditioner.anisotropy_dim"))); // <- dim criterion_parameters.setDebugLevel(opts.get("preconditioner.verbose", default_opts.get< size_t >("preconditioner.verbose"))); typename Amg::SmootherTraits< SmootherType >::Arguments smoother_arguments; smoother_arguments.iterations = opts.get("smoother.iterations", default_opts.get< size_t >("smoother.iterations")); smoother_arguments.relaxationFactor = opts.get("smoother.relaxation_factor", default_opts.get< S >("smoother.relaxation_factor")); Amg::CoarsenCriterion< Amg::SymmetricCriterion< IstlMatrixType, Amg::FirstDiagonal > > smoother_criterion(criterion_parameters); typedef Amg::AMG< MatrixOperatorType, IstlVectorType, SmootherType, CommunicatorType > PreconditionerType; PreconditionerType preconditioner(matrix_operator, smoother_criterion, smoother_arguments, communicator_); OverlappingSchwarzScalarProduct< IstlVectorType, CommunicatorType > scalar_product(communicator_); InverseOperatorResult statistics; BiCGSTABSolver< IstlVectorType > solver(matrix_operator, scalar_product, preconditioner, opts.get("precision", default_opts.get< S >("precision")), opts.get("max_iter", default_opts.get< size_t >("max_iter")), (communicator_.communicator().rank() == 0) ? opts.get("verbose", default_opts.get< int >("verbose")) : 0); solver.apply(solution.backend(), writable_rhs.backend(), statistics); if (!statistics.converged) DUNE_THROW_COLORFULLY(Exceptions::linear_solver_failed_bc_it_did_not_converge, "The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n" << "Those were the given options:\n\n" << opts); #else // HAVE_MPI typedef MatrixAdapter< typename MatrixType::BackendType, typename IstlDenseVector< S >::BackendType, typename IstlDenseVector< S >::BackendType > MatrixOperatorType; MatrixOperatorType matrix_operator(matrix_.backend()); typedef SeqILU0< typename MatrixType::BackendType, typename IstlDenseVector< S >::BackendType, typename IstlDenseVector< S >::BackendType > SmootherType; typedef Dune::Amg::AMG< MatrixOperatorType, typename IstlDenseVector< S >::BackendType, SmootherType > PreconditionerType; Dune::SeqScalarProduct< typename IstlDenseVector< S >::BackendType > scalar_product; typedef typename Dune::Amg::SmootherTraits< SmootherType >::Arguments SmootherArgs; SmootherArgs smootherArgs; smootherArgs.iterations = opts.get("smoother.iterations", default_opts.get< size_t >("smoother.iterations")); smootherArgs.relaxationFactor = opts.get("smoother.relaxation_factor", default_opts.get< S >("smoother.relaxation_factor")); Dune::Amg::Parameters params(opts.get("preconditioner.max_level", default_opts.get< size_t >("preconditioner.max_level")), opts.get("preconditioner.coarse_target", default_opts.get< size_t >("preconditioner.coarse_target")), opts.get("preconditioner.min_coarse_rate", default_opts.get< S >("preconditioner.min_coarse_rate")), opts.get("preconditioner.prolong_damp", default_opts.get< S >("preconditioner.prolong_damp"))); params.setDefaultValuesIsotropic(opts.get("preconditioner.isotropy_dim", default_opts.get< size_t >("preconditioner.isotropy_dim"))); params.setDefaultValuesAnisotropic(opts.get("preconditioner.anisotropy_dim", default_opts.get< size_t >("preconditioner.anisotropy_dim"))); // <- dim typedef Dune::Amg::CoarsenCriterion < Dune::Amg::SymmetricCriterion< typename MatrixType::BackendType, Dune::Amg::FirstDiagonal > > AmgCriterion; AmgCriterion amg_criterion(params); amg_criterion.setDebugLevel(opts.get("preconditioner.verbose", default_opts.get< size_t >("preconditioner.verbose"))); PreconditionerType preconditioner(matrix_operator, amg_criterion, smootherArgs); typedef BiCGSTABSolver< typename IstlDenseVector< S >::BackendType > SolverType; SolverType solver(matrix_operator, scalar_product, preconditioner, opts.get("precision", default_opts.get< S >("precision")), opts.get("max_iter", default_opts.get< size_t >("max_iter")), opts.get("verbose", default_opts.get< size_t >("verbose"))); InverseOperatorResult stat; solver.apply(solution.backend(), writable_rhs.backend(), stat); if (!stat.converged) DUNE_THROW_COLORFULLY(Exceptions::linear_solver_failed_bc_it_did_not_converge, "The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n" << "Those were the given options:\n\n" << opts); #endif // HAVE_MPI #if !HAVE_MPI } else if (type == "bicgstab.ilut") { typedef MatrixAdapter< typename MatrixType::BackendType, typename IstlDenseVector< S >::BackendType, typename IstlDenseVector< S >::BackendType > MatrixOperatorType; MatrixOperatorType matrix_operator(matrix_.backend()); typedef SeqILUn< typename MatrixType::BackendType, typename IstlDenseVector< S >::BackendType, typename IstlDenseVector< S >::BackendType > PreconditionerType; PreconditionerType preconditioner(matrix_.backend(), opts.get("preconditioner.iterations", default_opts.get< size_t >("preconditioner.iterations")), opts.get("preconditioner.relaxation_factor", default_opts.get< S >("preconditioner.relaxation_factor"))); typedef BiCGSTABSolver< typename IstlDenseVector< S >::BackendType > SolverType; SolverType solver(matrix_operator, preconditioner, opts.get("precision", default_opts.get< S >("precision")), opts.get("max_iter", default_opts.get< size_t >("max_iter")), opts.get("verbose", default_opts.get< int >("verbose"))); InverseOperatorResult stat; solver.apply(solution.backend(), writable_rhs.backend(), stat); if (!stat.converged) DUNE_THROW_COLORFULLY(Exceptions::linear_solver_failed_bc_it_did_not_converge, "The dune-istl backend reported 'InverseOperatorResult.converged == false'!\n" << "Those were the given options:\n\n" << opts); #endif // !HAVE_MPI } else DUNE_THROW_COLORFULLY(Exceptions::internal_error, "Given type '" << type << "' is not supported, although it was reported by options()!"); #if !HAVE_MPI // check (use writable_rhs as tmp) const S post_check_solves_system_theshhold = opts.get("post_check_solves_system", default_opts.get< S >("post_check_solves_system")); if (post_check_solves_system_theshhold > 0) { matrix_.mv(solution, writable_rhs); writable_rhs -= rhs; const S sup_norm = writable_rhs.sup_norm(); if (sup_norm > post_check_solves_system_theshhold || std::isnan(sup_norm) || std::isinf(sup_norm)) DUNE_THROW_COLORFULLY(Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system, "The computed solution does not solve the system (although the dune-istl backend " << "reported no error) and you requested checking (see options below)!\n" << "If you want to disable this check, set 'post_check_solves_system = 0' in the options." << "\n\n" << " (A * x - b).sup_norm() = " << writable_rhs.sup_norm() << "\n\n" << "Those were the given options:\n\n" << opts); } #endif // !HAVE_MPI } // ... apply(...) private: const MatrixType& matrix_; #if HAVE_MPI const CommunicatorType& communicator_; #endif }; // class Solver #else // HAVE_DUNE_ISTL template< class S > class Solver< IstlRowMajorSparseMatrix< S > >{ static_assert(Dune::AlwaysFalse< S >::value, "You are missing dune-istl!"); }; #endif // HAVE_DUNE_ISTL } // namespace LA } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_LA_SOLVER_STUFF_HH <|endoftext|>
<commit_before>/* * Copyright (c) 2016, Simone Margaritelli <evilsocket at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of ARM Inject nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <getopt.h> #include <ctype.h> #include <algorithm> #include "tracer.h" typedef enum { ACTION_HELP = 0, ACTION_SHOW, ACTION_SEARCH, ACTION_READ, ACTION_DUMP, ACTION_INJECT } action_t; static struct option options[] = { { "pid", required_argument, 0, 'p' }, { "name", required_argument, 0, 'n' }, { "output", required_argument, 0, 'o' }, { "size", required_argument, 0, 's' }, { "help", no_argument, 0, 'H' }, { "show", no_argument, 0, 'S' }, { "search", required_argument, 0, 'X' }, { "read", required_argument, 0, 'R' }, { "dump", required_argument, 0, 'D' }, { "inject", required_argument, 0, 'I' }, {0,0,0,0} }; static pid_t __pid = -1; static string __name = ""; static action_t __action = ACTION_HELP; static Process *__process = NULL; static string __output = ""; static uintptr_t __address = -1; static size_t __size = -1; static string __library = ""; static string __hex_pattern = ""; static unsigned char *__pattern = NULL; void help( const char *name ); void app_init( const char *name ); unsigned char *parsehex( char *hex ); void dumphex( unsigned char *buffer, size_t base, size_t size, const char *padding = "", size_t step = 16 ); void action_show( const char *name ); void action_search( const char *name ); void action_read( const char *name ); void action_dump( const char *name ); void action_inject( const char *name ); int main( int argc, char **argv ) { int c, option_index = 0; while (1) { c = getopt_long( argc, argv, "o:p:n:s:HSX:D:R:I:", options, &option_index ); if( c == -1 ){ break; } switch(c) { case 'p': __pid = strtol( optarg, NULL, 10 ); break; case 'n': __name = optarg; break; case 'o': __output = optarg; break; case 's': __size = strtoul( optarg, NULL, 10 ); break; case 'S': __action = ACTION_SHOW; break; case 'X': __action = ACTION_SEARCH; __hex_pattern = optarg; __pattern = parsehex( optarg ); if( !__pattern ){ help( argv[0] ); } break; case 'R': __action = ACTION_READ; __address = strtoul( optarg, NULL, 16 ); break; case 'D': __action = ACTION_DUMP; __address = strtoul( optarg, NULL, 16 ); break; case 'I': __action = ACTION_INJECT; __library = optarg; break; case 'H': help( argv[0] ); break; default: help( argv[0] ); } } if( __action == ACTION_HELP ){ help( argv[0] ); } app_init( argv[0] ); switch(__action) { case ACTION_SHOW: action_show( argv[0] ); break; case ACTION_READ: action_read( argv[0] ); break; case ACTION_SEARCH: action_search( argv[0] ); break; case ACTION_DUMP: action_dump( argv[0] ); break; case ACTION_INJECT: action_inject( argv[0] ); break; } delete __process; if( __pattern != NULL ){ delete[] __pattern; } return 0; } void help( const char *name ){ printf( "Usage: %s <options> <action>\n\n", name ); printf( "OPTIONS:\n\n" ); printf( " --pid | -p PID : Select process by pid.\n" ); printf( " --name | -n NAME : Select process by name.\n" ); printf( " --size | -s SIZE : Set size.\n" ); printf( " --output | -o FILE : Set output file.\n" ); printf( "\nACTIONS:\n\n" ); printf( " --help | -H : Show help menu.\n" ); printf( " --show | -S : Show process informations.\n" ); printf( " --search | -X HEX : Search for the given pattern ( in hex ) in the process address space.\n" ); printf( " --read | -R ADDRESS : Read SIZE bytes from address and prints them, requires -s option.\n" ); printf( " --dump | -D ADDRESS : Dump memory region containing a specific address to a file, requires -o option.\n" ); printf( " --inject | -I LIBRARY : Inject the shared LIBRARY into the process.\n" ); exit(0); } void app_init( const char *name ) { if( getuid() != 0 ){ fprintf( stderr, "ERROR: This program must be runned as root.\n\n" ); help( name ); } else if( __pid != -1 && __name != "" ){ fprintf( stderr, "ERROR: --pid and --name options are mutually exclusive.\n\n" ); help( name ); } else if( __pid != -1 ){ __process = new Process( __pid ); } else if( __name != "" ){ __process = Process::find( __name.c_str() ); } else { fprintf( stderr, "ERROR: One of --pid or --name options are required.\n\n" ); help( name ); } } unsigned char *parsehex( char *hex ) { size_t len = strlen(hex); if( len % 2 != 0 ){ fprintf( stderr, "ERROR: Invalid hexadecimal pattern.\n\n" ); return NULL; } unsigned char *dst = new unsigned char[ len / 2 ]; int i = 0; for( char *p = hex; p < hex + len; p += 2 ) { unsigned int byte = 0; if( sscanf( p, "%2x", &byte ) != 1 ) { fprintf( stderr, "ERROR: Invalid hexadecimal pattern.\n\n" ); delete[] dst; return NULL; } dst[i++] = byte & 0xff; } return dst; } void dumphex( unsigned char *buffer, size_t base, size_t size, const char *padding, size_t step ) { unsigned char *p = &buffer[0], *end = p + size; while( p < end ) { unsigned int left = end - p; step = std::min( step, left ); printf( "%s%08X | ", padding, base ); for( int i = 0; i < step; ++i ){ printf( "%02x ", p[i] ); } printf( "| "); for( int i = 0; i < step; ++i ){ printf( "%c", isprint(p[i]) ? p[i] : '.' ); } printf( "\n" ); p += step; base += step; } } void action_show( const char *name ) { __process->dump(); } void action_read( const char *name ) { if( __size == -1 ){ fprintf( stderr, "ERROR: --read action require --size option to be set.\n\n" ); help( name ); } const MemoryMap *mem = __process->findRegion(__address); if( mem == NULL ){ FATAL( "Could not find address %p in the process space.\n", __address ); } Tracer tracer( __process ); // align size __size = ( __size % sizeof(long) ? __size + (sizeof(long) - __size % sizeof(long)) : __size ); printf( "Reading %lu bytes from %p ( %s ) ...\n\n", __size, __address, mem->name().c_str() ); unsigned char *buffer = new unsigned char[ __size ]; if( read( __address, buffer, __size ) ){ dumphex( buffer, __address, __size ); } else { perror("ptrace"); fprintf( stderr, "Could not read from process.\n" ); } delete[] buffer; } void action_search( const char *name ) { printf( "Searching for pattern 0x%s ...\n", __hex_pattern.c_str() ); size_t pattern_size = __hex_pattern.size() / 2; Tracer tracer( __process ); PROCESS_FOREACH_MAP_CONST( __process ){ // printf( " Searching in %p-%p ( %s ) ...\n", i->begin(), i->end(), i->name().c_str() ); unsigned char *buffer = new unsigned char[ i->size() ]; if( read( i->begin(), buffer, i->size() ) ){ size_t end = i->size() - pattern_size; for( size_t off = 0; off < end; off += pattern_size ){ if( memcmp( &buffer[off], __pattern, pattern_size ) == 0 ){ printf( "Match @ offset %lu of %p-%p ( %s ):\n\n", off, i->begin(), i->end(), i->name().c_str() ); dumphex( &buffer[off], i->begin() + off, std::min( 32, (int)(end - off) ), " " ); printf("\n"); } } } else { printf( " Could not read %p-%p ( %s ).\n", i->begin(), i->end(), i->name().c_str() ); } delete[] buffer; } } void action_dump( const char *name ) { if( __output == "" ){ fprintf( stderr, "ERROR: --dump action require --output option to be set.\n\n" ); help( name ); } Tracer tracer( __process ); tracer.dumpRegion( __address, __output.c_str() ); } void action_inject( const char *name ) { Tracer tracer( __process ); const Symbols *syms = tracer.getSymbols(); uintptr_t pstr = tracer.writeString( __library.c_str() ); printf( "Library name string allocated @ %p\n", pstr ); uintptr_t ret = tracer.call( syms->_dlopen, 2, pstr, 0 ); printf( "dlopen returned 0x%x\n", ret ); tracer.call( syms->_free, 1, pstr ); } <commit_msg>oh yeah baby, gimme some more newlines <3<commit_after>/* * Copyright (c) 2016, Simone Margaritelli <evilsocket at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of ARM Inject nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <getopt.h> #include <ctype.h> #include <algorithm> #include "tracer.h" typedef enum { ACTION_HELP = 0, ACTION_SHOW, ACTION_SEARCH, ACTION_READ, ACTION_DUMP, ACTION_INJECT } action_t; static struct option options[] = { { "pid", required_argument, 0, 'p' }, { "name", required_argument, 0, 'n' }, { "output", required_argument, 0, 'o' }, { "size", required_argument, 0, 's' }, { "help", no_argument, 0, 'H' }, { "show", no_argument, 0, 'S' }, { "search", required_argument, 0, 'X' }, { "read", required_argument, 0, 'R' }, { "dump", required_argument, 0, 'D' }, { "inject", required_argument, 0, 'I' }, {0,0,0,0} }; static pid_t __pid = -1; static string __name = ""; static action_t __action = ACTION_HELP; static Process *__process = NULL; static string __output = ""; static uintptr_t __address = -1; static size_t __size = -1; static string __library = ""; static string __hex_pattern = ""; static unsigned char *__pattern = NULL; void help( const char *name ); void app_init( const char *name ); unsigned char *parsehex( char *hex ); void dumphex( unsigned char *buffer, size_t base, size_t size, const char *padding = "", size_t step = 16 ); void action_show( const char *name ); void action_search( const char *name ); void action_read( const char *name ); void action_dump( const char *name ); void action_inject( const char *name ); int main( int argc, char **argv ) { int c, option_index = 0; while (1) { c = getopt_long( argc, argv, "o:p:n:s:HSX:D:R:I:", options, &option_index ); if( c == -1 ){ break; } switch(c) { case 'p': __pid = strtol( optarg, NULL, 10 ); break; case 'n': __name = optarg; break; case 'o': __output = optarg; break; case 's': __size = strtoul( optarg, NULL, 10 ); break; case 'S': __action = ACTION_SHOW; break; case 'X': __action = ACTION_SEARCH; __hex_pattern = optarg; __pattern = parsehex( optarg ); if( !__pattern ){ help( argv[0] ); } break; case 'R': __action = ACTION_READ; __address = strtoul( optarg, NULL, 16 ); break; case 'D': __action = ACTION_DUMP; __address = strtoul( optarg, NULL, 16 ); break; case 'I': __action = ACTION_INJECT; __library = optarg; break; case 'H': help( argv[0] ); break; default: help( argv[0] ); } } if( __action == ACTION_HELP ){ help( argv[0] ); } app_init( argv[0] ); switch(__action) { case ACTION_SHOW: action_show( argv[0] ); break; case ACTION_READ: action_read( argv[0] ); break; case ACTION_SEARCH: action_search( argv[0] ); break; case ACTION_DUMP: action_dump( argv[0] ); break; case ACTION_INJECT: action_inject( argv[0] ); break; } delete __process; if( __pattern != NULL ){ delete[] __pattern; } return 0; } void help( const char *name ){ printf( "Usage: %s <options> <action>\n\n", name ); printf( "OPTIONS:\n\n" ); printf( " --pid | -p PID : Select process by pid.\n" ); printf( " --name | -n NAME : Select process by name.\n" ); printf( " --size | -s SIZE : Set size.\n" ); printf( " --output | -o FILE : Set output file.\n" ); printf( "\nACTIONS:\n\n" ); printf( " --help | -H : Show help menu.\n" ); printf( " --show | -S : Show process informations.\n" ); printf( " --search | -X HEX : Search for the given pattern ( in hex ) in the process address space.\n" ); printf( " --read | -R ADDRESS : Read SIZE bytes from address and prints them, requires -s option.\n" ); printf( " --dump | -D ADDRESS : Dump memory region containing a specific address to a file, requires -o option.\n" ); printf( " --inject | -I LIBRARY : Inject the shared LIBRARY into the process.\n" ); exit(0); } void app_init( const char *name ) { if( getuid() != 0 ){ fprintf( stderr, "ERROR: This program must be runned as root.\n\n" ); help( name ); } else if( __pid != -1 && __name != "" ){ fprintf( stderr, "ERROR: --pid and --name options are mutually exclusive.\n\n" ); help( name ); } else if( __pid != -1 ){ __process = new Process( __pid ); } else if( __name != "" ){ __process = Process::find( __name.c_str() ); } else { fprintf( stderr, "ERROR: One of --pid or --name options are required.\n\n" ); help( name ); } } unsigned char *parsehex( char *hex ) { size_t len = strlen(hex); if( len % 2 != 0 ){ fprintf( stderr, "ERROR: Invalid hexadecimal pattern.\n\n" ); return NULL; } unsigned char *dst = new unsigned char[ len / 2 ]; int i = 0; for( char *p = hex; p < hex + len; p += 2 ) { unsigned int byte = 0; if( sscanf( p, "%2x", &byte ) != 1 ) { fprintf( stderr, "ERROR: Invalid hexadecimal pattern.\n\n" ); delete[] dst; return NULL; } dst[i++] = byte & 0xff; } return dst; } void dumphex( unsigned char *buffer, size_t base, size_t size, const char *padding, size_t step ) { unsigned char *p = &buffer[0], *end = p + size; while( p < end ) { unsigned int left = end - p; step = std::min( step, left ); printf( "%s%08X | ", padding, base ); for( int i = 0; i < step; ++i ){ printf( "%02x ", p[i] ); } printf( "| "); for( int i = 0; i < step; ++i ){ printf( "%c", isprint(p[i]) ? p[i] : '.' ); } printf( "\n" ); p += step; base += step; } } void action_show( const char *name ) { __process->dump(); } void action_read( const char *name ) { if( __size == -1 ){ fprintf( stderr, "ERROR: --read action require --size option to be set.\n\n" ); help( name ); } const MemoryMap *mem = __process->findRegion(__address); if( mem == NULL ){ FATAL( "Could not find address %p in the process space.\n", __address ); } Tracer tracer( __process ); // align size __size = ( __size % sizeof(long) ? __size + (sizeof(long) - __size % sizeof(long)) : __size ); printf( "Reading %lu bytes from %p ( %s ) ...\n\n", __size, __address, mem->name().c_str() ); unsigned char *buffer = new unsigned char[ __size ]; if( read( __address, buffer, __size ) ){ dumphex( buffer, __address, __size ); } else { perror("ptrace"); fprintf( stderr, "Could not read from process.\n" ); } delete[] buffer; } void action_search( const char *name ) { printf( "Searching for pattern 0x%s ...\n\n", __hex_pattern.c_str() ); size_t pattern_size = __hex_pattern.size() / 2; Tracer tracer( __process ); PROCESS_FOREACH_MAP_CONST( __process ){ // printf( " Searching in %p-%p ( %s ) ...\n", i->begin(), i->end(), i->name().c_str() ); unsigned char *buffer = new unsigned char[ i->size() ]; if( read( i->begin(), buffer, i->size() ) ){ size_t end = i->size() - pattern_size; for( size_t off = 0; off < end; off += pattern_size ){ if( memcmp( &buffer[off], __pattern, pattern_size ) == 0 ){ printf( "Match @ offset %lu of %p-%p ( %s ):\n\n", off, i->begin(), i->end(), i->name().c_str() ); dumphex( &buffer[off], i->begin() + off, std::min( 32, (int)(end - off) ), " " ); printf("\n"); } } } else { printf( " Could not read %p-%p ( %s ).\n", i->begin(), i->end(), i->name().c_str() ); } delete[] buffer; } } void action_dump( const char *name ) { if( __output == "" ){ fprintf( stderr, "ERROR: --dump action require --output option to be set.\n\n" ); help( name ); } Tracer tracer( __process ); tracer.dumpRegion( __address, __output.c_str() ); } void action_inject( const char *name ) { Tracer tracer( __process ); const Symbols *syms = tracer.getSymbols(); uintptr_t pstr = tracer.writeString( __library.c_str() ); printf( "Library name string allocated @ %p\n", pstr ); uintptr_t ret = tracer.call( syms->_dlopen, 2, pstr, 0 ); printf( "dlopen returned 0x%x\n", ret ); tracer.call( syms->_free, 1, pstr ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MasterPagesPanel.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2007-04-03 16:22:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "MasterPagesPanel.hxx" #include "taskpane/ScrollPanel.hxx" #include "CurrentMasterPagesSelector.hxx" #include "RecentMasterPagesSelector.hxx" #include "AllMasterPagesSelector.hxx" #include "taskpane/TaskPaneControlFactory.hxx" #include "taskpane/TitledControl.hxx" #include "../TaskPaneShellManager.hxx" #include "DrawViewShell.hxx" #include "ViewShellBase.hxx" #include "strings.hrc" #include "sdresid.hxx" #include "helpids.h" #include <svtools/valueset.hxx> namespace sd { namespace toolpanel { namespace controls { MasterPagesPanel::MasterPagesPanel (TreeNode* pParent, ViewShellBase& rBase) : ScrollPanel (pParent) { SdDrawDocument* pDocument = rBase.GetDocument(); ::std::auto_ptr<controls::MasterPagesSelector> pSelector; TitledControl* pTitledControl; ::boost::shared_ptr<MasterPageContainer> pContainer (new MasterPageContainer()); // Create a panel with the master pages that are in use by the currently // edited document. DrawViewShell* pDrawViewShell = dynamic_cast<DrawViewShell*>(rBase.GetMainViewShell().get()); pSelector.reset(new controls::CurrentMasterPagesSelector ( this, *pDocument, rBase, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_CURRENT) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_CURRENT, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_CURRENT_MASTER_PAGES_TITLE), HID_SD_CURRENT_MASTERS); // Create a panel with the most recently used master pages. pSelector.reset(new controls::RecentMasterPagesSelector ( this, *pDocument, rBase, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_RECENT) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_RECENT, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_RECENT_MASTER_PAGES_TITLE), HID_SD_RECENT_MASTERS); // Create a panel with all available master pages. pSelector.reset(new controls::AllMasterPagesSelector ( this, *pDocument, rBase, *pDrawViewShell, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_ALL) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_ALL, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_ALL_MASTER_PAGES_TITLE), HID_SD_ALL_MASTERS); } MasterPagesPanel::~MasterPagesPanel (void) { } std::auto_ptr<ControlFactory> MasterPagesPanel::CreateControlFactory (ViewShellBase& rBase) { return std::auto_ptr<ControlFactory>( new ControlFactoryWithArgs1<MasterPagesPanel,ViewShellBase>(rBase)); } } } } // end of namespace ::sd::toolpanel::controls <commit_msg>INTEGRATION: CWS changefileheader (1.13.234); FILE MERGED 2008/03/31 13:59:02 rt 1.13.234.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MasterPagesPanel.cxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "MasterPagesPanel.hxx" #include "taskpane/ScrollPanel.hxx" #include "CurrentMasterPagesSelector.hxx" #include "RecentMasterPagesSelector.hxx" #include "AllMasterPagesSelector.hxx" #include "taskpane/TaskPaneControlFactory.hxx" #include "taskpane/TitledControl.hxx" #include "../TaskPaneShellManager.hxx" #include "DrawViewShell.hxx" #include "ViewShellBase.hxx" #include "strings.hrc" #include "sdresid.hxx" #include "helpids.h" #include <svtools/valueset.hxx> namespace sd { namespace toolpanel { namespace controls { MasterPagesPanel::MasterPagesPanel (TreeNode* pParent, ViewShellBase& rBase) : ScrollPanel (pParent) { SdDrawDocument* pDocument = rBase.GetDocument(); ::std::auto_ptr<controls::MasterPagesSelector> pSelector; TitledControl* pTitledControl; ::boost::shared_ptr<MasterPageContainer> pContainer (new MasterPageContainer()); // Create a panel with the master pages that are in use by the currently // edited document. DrawViewShell* pDrawViewShell = dynamic_cast<DrawViewShell*>(rBase.GetMainViewShell().get()); pSelector.reset(new controls::CurrentMasterPagesSelector ( this, *pDocument, rBase, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_CURRENT) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_CURRENT, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_CURRENT_MASTER_PAGES_TITLE), HID_SD_CURRENT_MASTERS); // Create a panel with the most recently used master pages. pSelector.reset(new controls::RecentMasterPagesSelector ( this, *pDocument, rBase, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_RECENT) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_RECENT, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_RECENT_MASTER_PAGES_TITLE), HID_SD_RECENT_MASTERS); // Create a panel with all available master pages. pSelector.reset(new controls::AllMasterPagesSelector ( this, *pDocument, rBase, *pDrawViewShell, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_ALL) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_ALL, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_ALL_MASTER_PAGES_TITLE), HID_SD_ALL_MASTERS); } MasterPagesPanel::~MasterPagesPanel (void) { } std::auto_ptr<ControlFactory> MasterPagesPanel::CreateControlFactory (ViewShellBase& rBase) { return std::auto_ptr<ControlFactory>( new ControlFactoryWithArgs1<MasterPagesPanel,ViewShellBase>(rBase)); } } } } // end of namespace ::sd::toolpanel::controls <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include <BALL/VIEW/GUI/DIALOGS/colorMeshDialog.h> #include <BALL/SYSTEM/path.h> #include <BALL/DATATYPE/regularData3D.h> #include <BALL/SYSTEM/file.h> #include <BALL/VIEW/DATATYPE/colorTable.h> #include <BALL/VIEW/GUI/KERNEL/mainControl.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qfiledialog.h> #include <qcolordialog.h> #include <qtabwidget.h> namespace BALL { namespace VIEW { /* * Constructs a ColorMeshDialog which is a child of 'parent', with the * name 'name' and widget flags set to 'f' * * The dialog will by default be modeless, unless you set 'modal' to * TRUE to construct a modal dialog. */ ColorMeshDialog::ColorMeshDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) : ColorMeshDialogData( parent, name, modal, fl ) { } ColorMeshDialog::~ColorMeshDialog() { // no need to delete child widgets, Qt does it all for us } void ColorMeshDialog::apply_clicked() { if (surface_tab->currentPage() == by_file) { // coloring by file RegularData3D dat; String filename = String(location_edit->text()); File infile; try { infile.open(filename, std::ios::in); } catch(Exception::FileNotFound) { Log.error() << "File could not be found!" << std::endl; return; } infile >> dat; infile.close(); // now do the colorizing stuff... mesh->colorList.resize(mesh->vertex.size()); ColorRGBA list[3]; list[0] = ColorRGBA(0.,0.,1.,1.); list[1] = ColorRGBA(0.,1.,1.,1.); list[2] = ColorRGBA(1.,1.,0.,1.); ColorTable table(list, 3); table.setNumberOfColors(levels_box->value()); table.createTable(); table.setRange(atof(min_box->text().latin1()), atof(max_box->text().latin1())); try { for (Position i=0; i<mesh->colorList.size(); i++) { mesh->colorList[i] = table.map(dat[mesh->vertex[i]]); } } catch (Exception::OutOfGrid) { Log.error() << "Error! There is a point contained in the surface that is not " << "inside the grid! Aborting the coloring..." << std::endl; return; } } if (surface_tab->currentPage() == by_color) { ColorRGBA col(red_box->value(), green_box->value(), blue_box->value(), alpha_box->value()); if (alpha_box->value() != 255) { mesh->setProperty(GeometricObject::PROPERTY__OBJECT_TRANSPARENT); } else { mesh->clearProperty(GeometricObject::PROPERTY__OBJECT_TRANSPARENT); } mesh->colorList.resize(1); mesh->colorList[0] = col; } // repaint of the scene and the composites needed MainControl::getMainControl(this)->updateAll(); MainControl::getMainControl(this)->repaint(); hide(); } void ColorMeshDialog::browse_clicked() { // look up the full path of the parameter file Path p; String filename = p.find((String)location_edit->text()); QString result = QFileDialog::getOpenFileName(filename.c_str(), "*", 0, "Select a RegularData file"); if (!result.isEmpty()) { // store the new filename in the lineedit field location_edit->setText(result); } } void ColorMeshDialog::cancel_clicked() { hide(); } QColor ColorMeshDialog::setColor(QPushButton* button) { QPalette p = button->palette(); QColor qcolor = QColorDialog::getColor(button->backgroundColor()); p.setColor(QColorGroup::Button, qcolor); p.setColor(QColorGroup::Base, qcolor); p.setColor(QColorGroup::Light, qcolor); p.setColor(QColorGroup::Mid, qcolor); p.setColor(QColorGroup::Midlight, qcolor); p.setColor(QColorGroup::Shadow, qcolor); button->setPalette(p); return qcolor; } void ColorMeshDialog::choose_clicked() { QColor qcolor = setColor(choose_button); selected_color.set(qcolor.red(), qcolor.green(), qcolor.blue()); red_box->setValue(qcolor.red()); blue_box->setValue(qcolor.blue()); green_box->setValue(qcolor.green()); } void ColorMeshDialog::color_boxes_changed() { selected_color.set(red_box->value(), green_box->value(), blue_box->value(), alpha_box->value()); QColor qcolor(red_box->value(), green_box->value(), blue_box->value()); QPalette p = choose_button->palette(); p.setColor(QColorGroup::Button, qcolor); p.setColor(QColorGroup::Base, qcolor); p.setColor(QColorGroup::Light, qcolor); p.setColor(QColorGroup::Mid, qcolor); p.setColor(QColorGroup::Midlight, qcolor); p.setColor(QColorGroup::Shadow, qcolor); choose_button->setPalette(p); } void ColorMeshDialog::location_changed() { if (String(location_edit->text()).size() != 0) apply_button->setEnabled(true); else apply_button->setEnabled(false); } void ColorMeshDialog::max_clicked() { QColor qcolor = setColor(max_button); max_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::mid_clicked() { QColor qcolor = setColor(mid_button); mid_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::min_clicked() { QColor qcolor = setColor(min_button); min_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::min_min_clicked() { QColor qcolor = setColor(min_min_button); min_min_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::max_max_clicked() { QColor qcolor = setColor(max_max_button); max_max_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::tab_changed() { if (surface_tab->currentPage() == by_file || surface_tab->currentPage() == colormap_tab) { // in coloring by file, allow apply if filename set if (location_edit->text() == "") { apply_button->setEnabled(false); } else { apply_button->setEnabled(true); } return; } if (surface_tab->currentPage() == by_color) { // if coloring by selected color, always enabled apply_button->setEnabled(true); } } // NAMESPACE } } <commit_msg>Compatibility fixes for QT 3.1.1<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include <BALL/VIEW/GUI/DIALOGS/colorMeshDialog.h> #include <BALL/SYSTEM/path.h> #include <BALL/DATATYPE/regularData3D.h> #include <BALL/SYSTEM/file.h> #include <BALL/VIEW/DATATYPE/colorTable.h> #include <BALL/VIEW/GUI/KERNEL/mainControl.h> #include <qlineedit.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qfiledialog.h> #include <qcolordialog.h> #include <qtabwidget.h> namespace BALL { namespace VIEW { /* * Constructs a ColorMeshDialog which is a child of 'parent', with the * name 'name' and widget flags set to 'f' * * The dialog will by default be modeless, unless you set 'modal' to * TRUE to construct a modal dialog. */ ColorMeshDialog::ColorMeshDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) : ColorMeshDialogData( parent, name, modal, fl ) { } ColorMeshDialog::~ColorMeshDialog() { // no need to delete child widgets, Qt does it all for us } void ColorMeshDialog::apply_clicked() { if (surface_tab->currentPage() == by_file) { // coloring by file RegularData3D dat; String filename = String(location_edit->text().latin1()); File infile; try { infile.open(filename, std::ios::in); } catch(Exception::FileNotFound) { Log.error() << "File could not be found!" << std::endl; return; } infile >> dat; infile.close(); // now do the colorizing stuff... mesh->colorList.resize(mesh->vertex.size()); ColorRGBA list[3]; list[0] = ColorRGBA(0.,0.,1.,1.); list[1] = ColorRGBA(0.,1.,1.,1.); list[2] = ColorRGBA(1.,1.,0.,1.); ColorTable table(list, 3); table.setNumberOfColors(levels_box->value()); table.createTable(); table.setRange(atof(min_box->text().latin1()), atof(max_box->text().latin1())); try { for (Position i=0; i<mesh->colorList.size(); i++) { mesh->colorList[i] = table.map(dat[mesh->vertex[i]]); } } catch (Exception::OutOfGrid) { Log.error() << "Error! There is a point contained in the surface that is not " << "inside the grid! Aborting the coloring..." << std::endl; return; } } if (surface_tab->currentPage() == by_color) { ColorRGBA col(red_box->value(), green_box->value(), blue_box->value(), alpha_box->value()); if (alpha_box->value() != 255) { mesh->setProperty(GeometricObject::PROPERTY__OBJECT_TRANSPARENT); } else { mesh->clearProperty(GeometricObject::PROPERTY__OBJECT_TRANSPARENT); } mesh->colorList.resize(1); mesh->colorList[0] = col; } // repaint of the scene and the composites needed MainControl::getMainControl(this)->updateAll(); MainControl::getMainControl(this)->repaint(); hide(); } void ColorMeshDialog::browse_clicked() { // look up the full path of the parameter file Path p; String filename = p.find((String)location_edit->text().latin1()); QString result = QFileDialog::getOpenFileName(filename.c_str(), "*", 0, "Select a RegularData file"); if (!result.isEmpty()) { // store the new filename in the lineedit field location_edit->setText(result); } } void ColorMeshDialog::cancel_clicked() { hide(); } QColor ColorMeshDialog::setColor(QPushButton* button) { QPalette p = button->palette(); QColor qcolor = QColorDialog::getColor(button->backgroundColor()); p.setColor(QColorGroup::Button, qcolor); p.setColor(QColorGroup::Base, qcolor); p.setColor(QColorGroup::Light, qcolor); p.setColor(QColorGroup::Mid, qcolor); p.setColor(QColorGroup::Midlight, qcolor); p.setColor(QColorGroup::Shadow, qcolor); button->setPalette(p); return qcolor; } void ColorMeshDialog::choose_clicked() { QColor qcolor = setColor(choose_button); selected_color.set(qcolor.red(), qcolor.green(), qcolor.blue()); red_box->setValue(qcolor.red()); blue_box->setValue(qcolor.blue()); green_box->setValue(qcolor.green()); } void ColorMeshDialog::color_boxes_changed() { selected_color.set(red_box->value(), green_box->value(), blue_box->value(), alpha_box->value()); QColor qcolor(red_box->value(), green_box->value(), blue_box->value()); QPalette p = choose_button->palette(); p.setColor(QColorGroup::Button, qcolor); p.setColor(QColorGroup::Base, qcolor); p.setColor(QColorGroup::Light, qcolor); p.setColor(QColorGroup::Mid, qcolor); p.setColor(QColorGroup::Midlight, qcolor); p.setColor(QColorGroup::Shadow, qcolor); choose_button->setPalette(p); } void ColorMeshDialog::location_changed() { if (String(location_edit->text().latin1()).size() != 0) apply_button->setEnabled(true); else apply_button->setEnabled(false); } void ColorMeshDialog::max_clicked() { QColor qcolor = setColor(max_button); max_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::mid_clicked() { QColor qcolor = setColor(mid_button); mid_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::min_clicked() { QColor qcolor = setColor(min_button); min_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::min_min_clicked() { QColor qcolor = setColor(min_min_button); min_min_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::max_max_clicked() { QColor qcolor = setColor(max_max_button); max_max_color.set(qcolor.red(), qcolor.green(), qcolor.blue());; } void ColorMeshDialog::tab_changed() { if (surface_tab->currentPage() == by_file || surface_tab->currentPage() == colormap_tab) { // in coloring by file, allow apply if filename set if (location_edit->text() == "") { apply_button->setEnabled(false); } else { apply_button->setEnabled(true); } return; } if (surface_tab->currentPage() == by_color) { // if coloring by selected color, always enabled apply_button->setEnabled(true); } } // NAMESPACE } } <|endoftext|>
<commit_before>/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #if defined(QT4) #include <QApplication> #include <QDeclarativeView> #include <QDeclarativeContext> #include <QDeclarativeEngine> #include <QtDeclarative> #include <QGLWidget> #elif defined(QT5) #include <QGuiApplication> #include <QQuickView> #include <QQmlError> #endif #include <QTranslator> #include "settings.h" #include "filenaming.h" #include "quillitem.h" #include "geocode.h" #include "deviceinfo.h" #include "soundvolumecontrol.h" #include "displaystate.h" #include "fsmonitor.h" #include "cameraresources.h" #include "compass.h" #include "orientation.h" #include "mountprotector.h" #include "trackerstore.h" #include "focusrectangle.h" #include "sharehelper.h" #include "deletehelper.h" #include "galleryhelper.h" #include "postcapturemodel.h" #include "batteryinfo.h" #include "gridlines.h" #include "devicekeys.h" #include "platformsettings.h" #include "dbusservice.h" #include "phoneprofile.h" #ifdef HARMATTAN #include "platformquirks.h" #endif #include "stack.h" #include "toolbarlayout.h" #ifdef HARMATTAN #include "proximity.h" #endif #include "devicesettings.h" #include "pluginloader.h" #include <MDeclarativeCache> #ifdef SAILFISH #include <QQmlEngine> #endif #include "qrangemodel.h" #include "devicefeatures.h" #include "position.h" #if defined(QT4) #include <QAbstractFileEngineHandler> #include "qmlfileengine.h" class QmlFileEngineHandler : public QAbstractFileEngineHandler { QAbstractFileEngine *create(const QString& fileName) const { QString fn = fileName.toLower(); if (fn.startsWith(':') && fn.endsWith(".qml")) { return new QmlFileEngine(fileName); } return 0; } }; #endif #ifdef HARMATTAN #include <X11/Xlib.h> class _XInitThreads { public: _XInitThreads() { // XInitThreads() is required by gst-gltexture sink XInitThreads(); } }; static _XInitThreads __XInitThreads; #endif #ifndef TRANSLATIONS_DIR #define TRANSLATIONS_DIR "/usr/share/cameraplus/translations/" #endif /* TRANSLATIONS_DIR */ Q_DECL_EXPORT int main(int argc, char *argv[]) { #ifdef SAILFISH setenv("LD_LIBRARY_PATH", "/usr/share/harbour-cameraplus/lib/", 1); #endif #if defined(QT4) QApplication *app = MDeclarativeCache::qApplication(argc, argv); app->setApplicationName("cameraplus"); QmlFileEngineHandler handler; Q_UNUSED(handler); QDeclarativeView *view = MDeclarativeCache::qDeclarativeView(); #elif defined(QT5) QGuiApplication *app = MDeclarativeCache::qApplication(argc, argv); app->setApplicationName("cameraplus"); QQuickView *view = MDeclarativeCache::qQuickView(); #endif QTranslator translator; if (translator.load(QString("cameraplus-%1").arg(QLocale().name()), TRANSLATIONS_DIR)) { app->installTranslator(&translator); } #if defined(QT4) view->setBackgroundBrush(QBrush(Qt::black)); view->setAttribute(Qt::WA_NoSystemBackground); view->setViewport(new QGLWidget); view->setResizeMode(QDeclarativeView::SizeRootObjectToView); view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); view->viewport()->setAttribute(Qt::WA_NoSystemBackground); #endif #if defined(QT5) view->setResizeMode(QQuickView::SizeRootObjectToView); #endif qmlRegisterType<Settings>("CameraPlus", 1, 0, "Settings"); qmlRegisterType<FileNaming>("CameraPlus", 1, 0, "FileNaming"); qmlRegisterType<QuillItem>("CameraPlus", 1, 0, "QuillItem"); qmlRegisterType<Geocode>("CameraPlus", 1, 0, "ReverseGeocode"); qmlRegisterType<DeviceInfo>("CameraPlus", 1, 0, "DeviceInfo"); qmlRegisterType<SoundVolumeControl>("CameraPlus", 1, 0, "SoundVolumeControl"); qmlRegisterType<DisplayState>("CameraPlus", 1, 0, "DisplayState"); qmlRegisterType<FSMonitor>("CameraPlus", 1, 0, "FSMonitor"); qmlRegisterType<CameraResources>("CameraPlus", 1, 0, "CameraResources"); qmlRegisterType<Compass>("CameraPlus", 1, 0, "CameraCompass"); qmlRegisterType<Orientation>("CameraPlus", 1, 0, "CameraOrientation"); qmlRegisterType<MountProtector>("CameraPlus", 1, 0, "MountProtector"); qmlRegisterType<TrackerStore>("CameraPlus", 1, 0, "TrackerStore"); qmlRegisterType<FocusRectangle>("CameraPlus", 1, 0, "FocusRectangle"); qmlRegisterType<ShareHelper>("CameraPlus", 1, 0, "ShareHelper"); qmlRegisterType<DeleteHelper>("CameraPlus", 1, 0, "DeleteHelper"); qmlRegisterType<GalleryHelper>("CameraPlus", 1, 0, "GalleryHelper"); qmlRegisterType<PostCaptureModel>("CameraPlus", 1, 0, "PostCaptureModel"); qmlRegisterType<BatteryInfo>("CameraPlus", 1, 0, "BatteryInfo"); qmlRegisterType<GridLines>("CameraPlus", 1, 0, "GridLines"); qmlRegisterType<DeviceKeys>("CameraPlus", 1, 0, "DeviceKeys"); qmlRegisterType<PlatformSettings>("CameraPlus", 1, 0, "PlatformSettings"); qmlRegisterType<PhoneProfile>("CameraPlus", 1, 0, "PhoneProfile"); #ifdef HARMATTAN qmlRegisterType<PlatformQuirks>("CameraPlus", 1, 0, "PlatformQuirks"); #endif qmlRegisterType<Stack>("CameraPlus", 1, 0, "Stack"); qmlRegisterType<ToolBarLayout>("CameraPlus", 1, 0, "ToolBarLayout"); #ifdef HARMATTAN qmlRegisterType<Proximity>("CameraPlus", 1, 0, "Proximity"); #endif qmlRegisterType<DeviceSettings>(); qmlRegisterType<PrimaryDeviceSettings>("CameraPlus", 1, 0, "PrimaryDeviceSettings"); qmlRegisterType<SecondaryDeviceSettings>("CameraPlus", 1, 0, "SecondaryDeviceSettings"); qmlRegisterType<PluginLoader>("CameraPlus", 1, 0, "PluginLoader"); qmlRegisterType<Plugin>("CameraPlus", 1, 0, "Plugin"); qmlRegisterType<QRangeModel>("CameraPlus", 1, 0, "RangeModel"); qmlRegisterType<PrimaryDeviceFeatures>("CameraPlus", 1, 0, "PrimaryDeviceFeatures"); qmlRegisterType<SecondaryDeviceFeatures>("CameraPlus", 1, 0, "SecondaryDeviceFeatures"); qmlRegisterType<Position>("CameraPlus", 1, 0, "Position"); #ifdef SAILFISH view->engine()->addImportPath("/usr/share/harbour-cameraplus/lib/qt5/qml/"); #endif view->setSource(QUrl("qrc:/qml/main.qml")); #if defined(QT5) if (view->status() == QQuickView::Error) { qCritical() << "Errors loading QML:"; QList<QQmlError> errors = view->errors(); foreach (const QQmlError& error, errors) { qCritical() << error.toString(); } delete view; delete app; return 1; } #endif view->showFullScreen(); int ret = app->exec(); delete view; delete app; return ret; } <commit_msg>load plurals qm file upon startup<commit_after>/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #if defined(QT4) #include <QApplication> #include <QDeclarativeView> #include <QDeclarativeContext> #include <QDeclarativeEngine> #include <QtDeclarative> #include <QGLWidget> #elif defined(QT5) #include <QGuiApplication> #include <QQuickView> #include <QQmlError> #endif #include <QTranslator> #include "settings.h" #include "filenaming.h" #include "quillitem.h" #include "geocode.h" #include "deviceinfo.h" #include "soundvolumecontrol.h" #include "displaystate.h" #include "fsmonitor.h" #include "cameraresources.h" #include "compass.h" #include "orientation.h" #include "mountprotector.h" #include "trackerstore.h" #include "focusrectangle.h" #include "sharehelper.h" #include "deletehelper.h" #include "galleryhelper.h" #include "postcapturemodel.h" #include "batteryinfo.h" #include "gridlines.h" #include "devicekeys.h" #include "platformsettings.h" #include "dbusservice.h" #include "phoneprofile.h" #ifdef HARMATTAN #include "platformquirks.h" #endif #include "stack.h" #include "toolbarlayout.h" #ifdef HARMATTAN #include "proximity.h" #endif #include "devicesettings.h" #include "pluginloader.h" #include <MDeclarativeCache> #ifdef SAILFISH #include <QQmlEngine> #endif #include "qrangemodel.h" #include "devicefeatures.h" #include "position.h" #if defined(QT4) #include <QAbstractFileEngineHandler> #include "qmlfileengine.h" class QmlFileEngineHandler : public QAbstractFileEngineHandler { QAbstractFileEngine *create(const QString& fileName) const { QString fn = fileName.toLower(); if (fn.startsWith(':') && fn.endsWith(".qml")) { return new QmlFileEngine(fileName); } return 0; } }; #endif #ifdef HARMATTAN #include <X11/Xlib.h> class _XInitThreads { public: _XInitThreads() { // XInitThreads() is required by gst-gltexture sink XInitThreads(); } }; static _XInitThreads __XInitThreads; #endif #ifndef TRANSLATIONS_DIR #define TRANSLATIONS_DIR "/usr/share/cameraplus/translations/" #endif /* TRANSLATIONS_DIR */ Q_DECL_EXPORT int main(int argc, char *argv[]) { #ifdef SAILFISH setenv("LD_LIBRARY_PATH", "/usr/share/harbour-cameraplus/lib/", 1); #endif #if defined(QT4) QApplication *app = MDeclarativeCache::qApplication(argc, argv); app->setApplicationName("cameraplus"); QmlFileEngineHandler handler; Q_UNUSED(handler); QDeclarativeView *view = MDeclarativeCache::qDeclarativeView(); #elif defined(QT5) QGuiApplication *app = MDeclarativeCache::qApplication(argc, argv); app->setApplicationName("cameraplus"); QQuickView *view = MDeclarativeCache::qQuickView(); #endif QTranslator plurals; if (plurals.load("plurals.qm", TRANSLATIONS_DIR)) { app->installTranslator(&plurals); } QTranslator translator; if (translator.load(QString("cameraplus-%1").arg(QLocale().name()), TRANSLATIONS_DIR)) { app->installTranslator(&translator); } #if defined(QT4) view->setBackgroundBrush(QBrush(Qt::black)); view->setAttribute(Qt::WA_NoSystemBackground); view->setViewport(new QGLWidget); view->setResizeMode(QDeclarativeView::SizeRootObjectToView); view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); view->viewport()->setAttribute(Qt::WA_NoSystemBackground); #endif #if defined(QT5) view->setResizeMode(QQuickView::SizeRootObjectToView); #endif qmlRegisterType<Settings>("CameraPlus", 1, 0, "Settings"); qmlRegisterType<FileNaming>("CameraPlus", 1, 0, "FileNaming"); qmlRegisterType<QuillItem>("CameraPlus", 1, 0, "QuillItem"); qmlRegisterType<Geocode>("CameraPlus", 1, 0, "ReverseGeocode"); qmlRegisterType<DeviceInfo>("CameraPlus", 1, 0, "DeviceInfo"); qmlRegisterType<SoundVolumeControl>("CameraPlus", 1, 0, "SoundVolumeControl"); qmlRegisterType<DisplayState>("CameraPlus", 1, 0, "DisplayState"); qmlRegisterType<FSMonitor>("CameraPlus", 1, 0, "FSMonitor"); qmlRegisterType<CameraResources>("CameraPlus", 1, 0, "CameraResources"); qmlRegisterType<Compass>("CameraPlus", 1, 0, "CameraCompass"); qmlRegisterType<Orientation>("CameraPlus", 1, 0, "CameraOrientation"); qmlRegisterType<MountProtector>("CameraPlus", 1, 0, "MountProtector"); qmlRegisterType<TrackerStore>("CameraPlus", 1, 0, "TrackerStore"); qmlRegisterType<FocusRectangle>("CameraPlus", 1, 0, "FocusRectangle"); qmlRegisterType<ShareHelper>("CameraPlus", 1, 0, "ShareHelper"); qmlRegisterType<DeleteHelper>("CameraPlus", 1, 0, "DeleteHelper"); qmlRegisterType<GalleryHelper>("CameraPlus", 1, 0, "GalleryHelper"); qmlRegisterType<PostCaptureModel>("CameraPlus", 1, 0, "PostCaptureModel"); qmlRegisterType<BatteryInfo>("CameraPlus", 1, 0, "BatteryInfo"); qmlRegisterType<GridLines>("CameraPlus", 1, 0, "GridLines"); qmlRegisterType<DeviceKeys>("CameraPlus", 1, 0, "DeviceKeys"); qmlRegisterType<PlatformSettings>("CameraPlus", 1, 0, "PlatformSettings"); qmlRegisterType<PhoneProfile>("CameraPlus", 1, 0, "PhoneProfile"); #ifdef HARMATTAN qmlRegisterType<PlatformQuirks>("CameraPlus", 1, 0, "PlatformQuirks"); #endif qmlRegisterType<Stack>("CameraPlus", 1, 0, "Stack"); qmlRegisterType<ToolBarLayout>("CameraPlus", 1, 0, "ToolBarLayout"); #ifdef HARMATTAN qmlRegisterType<Proximity>("CameraPlus", 1, 0, "Proximity"); #endif qmlRegisterType<DeviceSettings>(); qmlRegisterType<PrimaryDeviceSettings>("CameraPlus", 1, 0, "PrimaryDeviceSettings"); qmlRegisterType<SecondaryDeviceSettings>("CameraPlus", 1, 0, "SecondaryDeviceSettings"); qmlRegisterType<PluginLoader>("CameraPlus", 1, 0, "PluginLoader"); qmlRegisterType<Plugin>("CameraPlus", 1, 0, "Plugin"); qmlRegisterType<QRangeModel>("CameraPlus", 1, 0, "RangeModel"); qmlRegisterType<PrimaryDeviceFeatures>("CameraPlus", 1, 0, "PrimaryDeviceFeatures"); qmlRegisterType<SecondaryDeviceFeatures>("CameraPlus", 1, 0, "SecondaryDeviceFeatures"); qmlRegisterType<Position>("CameraPlus", 1, 0, "Position"); #ifdef SAILFISH view->engine()->addImportPath("/usr/share/harbour-cameraplus/lib/qt5/qml/"); #endif view->setSource(QUrl("qrc:/qml/main.qml")); #if defined(QT5) if (view->status() == QQuickView::Error) { qCritical() << "Errors loading QML:"; QList<QQmlError> errors = view->errors(); foreach (const QQmlError& error, errors) { qCritical() << error.toString(); } delete view; delete app; return 1; } #endif view->showFullScreen(); int ret = app->exec(); delete view; delete app; return ret; } <|endoftext|>
<commit_before>#ifndef _SMRH_ #define _SMRH_ #include <vector> #include <atomic> #include <algorithm> namespace DNFC { /** * HazardPointer default policy * */ class DefaultHazardPointerPolicy { public: const static int BlockSize = 4; }; template <class T, class Policy = DefaultHazardPointerPolicy> class HazardPointer { public: /** * operator=(const HazardPointer& hp) * * copy operator= with the reference to another Hazard Pointer. */ HazardPointer<T, Policy> &operator=(const HazardPointer &hp) { return operator=(hp.get()); } /** * operator=(HazardPointer&& hp) * * move operator= with another Hazard Pointer. */ HazardPointer<T, Policy> &operator=(HazardPointer &&hp) { return operator=(std::move(hp.release())); } /** * operator=(T* p) * * operator= with a pointer to guard. */ HazardPointer<T, Policy> &operator=(T *p) { if (!ptr.get()) { ptr.reset(HazardPointer<T, Policy>::getMyhp()->guard(p)); } else { if (p != ptr->ptr.load(std::memory_order_relaxed)) ptr->ptr.exchange(p, std::memory_order_release); } return *this; } /** * get * * Retrieve the guarded pointer. */ T *get() const { if (!ptr.get()) return nullptr; return ptr->ptr.load(std::memory_order_relaxed); } /** * release * * Release the safety guard on the pointer. */ T *release() { if (!ptr.get()) return nullptr; return ptr->ptr.exchange(nullptr, std::memory_order_release); } /** * retire * * Safely retire the node for deletion. */ void retire() { std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); if (!myhp.get()) return; myhp->retire(ptr.release()); if (myhp->nbRetiredPtrs >= HazardPointerManager::get().getBatchSize()) { HazardPointerManager::get().scan(); HazardPointerManager::get().helpScan(); } } /** * Constructor * * Automatically subscribe to the manager but don't guard any pointer. * The manager will prevent a thread to subscribe more than one time. */ HazardPointer() : ptr(nullptr) { HazardPointerManager::get().subscribe(); } /** * Constructor * * Automatically subscribe to the manager and guard the given pointer. * The manager will prevent a thread to subscribe more than one time. */ HazardPointer(T *p) { HazardPointerManager::get().subscribe(); if (ptr.get()) { ptr->ptr.exchange(p, std::memory_order_release); return; } ptr.reset(HazardPointer<T, Policy>::getMyhp()->guard(p)); }; /** * Release the guarded pointer if there is one. If no more pointers are * guarded in this thread, then it will unsubscribe from the manager. */ ~HazardPointer() { if (ptr.get()) { HazardPointer<T, Policy>::getMyhp()->release(ptr.release()); if (HazardPointerManager::get().nbhp.load(std::memory_order_relaxed) <= 0) HazardPointerManager::get().unsubscribe(); } }; private: /** * GuardedPointer * * A convenient linked list that hold a pointer on which deletion is prohibited. * In practice each GuardedPointer are contiguous within each GuardedPointerBlock. * See GuardedPointerBlock for more information. */ struct GuardedPointer { std::atomic<T *> ptr; std::atomic<GuardedPointer *> next; void setPtr(T *p) { ptr.store(p, std::memory_order_release); } void setNext(GuardedPointer *n) { next.store(n, std::memory_order_release); } GuardedPointer *getNext() { return getCleared(next.load(std::memory_order_relaxed)); } bool isDeleted() { uintptr_t nextPtr = reinterpret_cast<uintptr_t>(next.load(std::memory_order_relaxed)); return reinterpret_cast<GuardedPointer *>(nextPtr & 0x1); } void markAsDeleted() { uintptr_t nextPtr = reinterpret_cast<uintptr_t>(next.load(std::memory_order_relaxed)); GuardedPointer *mrkd = reinterpret_cast<GuardedPointer *>(nextPtr | 0x1); next.store(mrkd, std::memory_order_release); } private: GuardedPointer *getCleared(GuardedPointer *p) { uintptr_t nextPtr = reinterpret_cast<uintptr_t>(p); return reinterpret_cast<GuardedPointer *>(nextPtr & ~0x1); } }; /** * GuardedPointerBlock * * An helping structure for memory managment. This structure represent a 'chunk' * of memory used for GuardedPointer contiguous arrays. This will allocate the * 'Policy::BlockSize' number of GuardedPointer. */ struct GuardedPointerBlock { std::unique_ptr<GuardedPointerBlock> next = nullptr; GuardedPointer *begin() { return reinterpret_cast<GuardedPointer *>(this + 1); } GuardedPointer *end() { return begin() + Policy::BlockSize; } const GuardedPointer *begin() const { return reinterpret_cast<const GuardedPointer *>(this + 1); } const GuardedPointer *end() const { return begin() + Policy::BlockSize; } GuardedPointerBlock() { GuardedPointer *last = end() - 1; for (auto &&g = begin(); g != last; g = g->next) g->next = g + 1; last->next = nullptr; }; }; /** * HazardPointerRecord * * An object that hold informations about allocated hazard pointers for the current * thread. */ struct HazardPointerRecord { GuardedPointer *rlistHead = nullptr; int nbRetiredPtrs; std::atomic<bool> active; std::unique_ptr<HazardPointerRecord> next = nullptr; // Guard a given pointer GuardedPointer *guard(T *p) { GuardedPointer *newPtr = allocPtr(); newPtr->setPtr(p); HazardPointerManager::get().nbhp.fetch_add(1, std::memory_order_relaxed); return newPtr; } // Put a pointer on the retire list for it to be removed void retire(GuardedPointer *n) { n->setNext(rlistHead); n->markAsDeleted(); rlistHead = n; HazardPointerManager::get().nbhp.fetch_sub(1, std::memory_order_relaxed); nbRetiredPtrs++; } // Return the GuardedPointer to the memory pool const T *release(GuardedPointer *p) { const T *data = p->ptr.load(std::memory_order_relaxed); freePtr(p); return data; } // Destroy the guarded pointer void free(GuardedPointer *n) { delete n->ptr.load(std::memory_order_relaxed); n->ptr.store(nullptr, std::memory_order_release); freePtr(n); } // Return in the passed vector of pointers, all the Hazard Pointers in this HazardPointerRecord void getHps(std::vector<T *> &output) { getHpsPriv(output, blockHead.load(std::memory_order_relaxed)); } HazardPointerRecord(HazardPointerRecord *head, bool active) : next(head), nbRetiredPtrs(0), blockHead(nullptr) { this->active.store(active, std::memory_order_relaxed); } ~HazardPointerRecord() { delete blockHead.load(); } private: std::atomic<GuardedPointerBlock *> blockHead; GuardedPointer *flistHead = nullptr; // Manage pointers memory allocation GuardedPointer *allocPtr() { GuardedPointer *newPtr; if (!flistHead) { void *chunk = std::malloc(Policy::BlockSize * sizeof(GuardedPointer) + sizeof(GuardedPointerBlock)); GuardedPointerBlock *newBlock = ::new (chunk) GuardedPointerBlock(); GuardedPointerBlock *head = blockHead.exchange(newBlock, std::memory_order_relaxed); newBlock->next.reset(head); flistHead = newBlock->begin(); } newPtr = flistHead; flistHead = newPtr->getNext(); newPtr->setNext(nullptr); return newPtr; } // Put HazardPointer on free list for reuse void freePtr(GuardedPointer *p) { p->setPtr(nullptr); p->setNext(flistHead); p->markAsDeleted(); flistHead = p; HazardPointerManager::get().nbhp.fetch_sub(1, std::memory_order_relaxed); } // Return a vector of all the Hazard Pointer contained in the GuardedPointerBlock linked list void getHpsPriv(std::vector<T *> &output, GuardedPointerBlock *block) { for (auto &&g : *block) { if (!g.isDeleted()) output.push_back(g.ptr.load()); } if (block->next) getHpsPriv(output, block->next.get()); } }; /** * HazardPointerManager * * This singleton private class provide a central managment point for safe memory reclamation. * It provide memory managment for system wide hazard pointers. */ friend class HazardPointerManager; class HazardPointerManager { public: // Retrive the unique instance of the HazardPointerManager static HazardPointerManager &get() { static HazardPointerManager m; return m; } ~HazardPointerManager() { delete head.load(std::memory_order_relaxed); } std::atomic<HazardPointerRecord *> head; std::atomic<int> nbhp; /** * Subscribe a thread to the manager. During the time the thread is subscribed, it is * given a HazardPointerRecord object that allow it to protect 'Policy::BlockSize' pointers. */ void subscribe() { std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); // Prevent subbing more than once if (myhp.get()) return; // First try to reuse a retire HP record bool expected = false; for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i != nullptr; i = i->next.get()) { if (i->active.load(std::memory_order_relaxed) || !i->active.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) continue; // Sucessfully locked one record to use myhp.reset(i); return; } // Allocate and push a new record myhp.reset(new HazardPointerRecord(head.load(std::memory_order_relaxed), true)); // Add the new record to the list HazardPointerRecord *nextPtrVal = myhp->next.get(); while (!head.compare_exchange_weak(nextPtrVal, myhp.get(), std::memory_order_release, std::memory_order_relaxed)) ; } /** * Unsubscribe the current thread from the manager. */ static void unsubscribe() { std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); // Prevent unsubscribe more than once if (!myhp.get()) return; myhp->active.store(false, std::memory_order_relaxed); myhp.release(); } /** * Retrieve the threshold of the manager before scanning is required */ unsigned int getBatchSize() { return nbhp.load(std::memory_order_relaxed) * 2 + Policy::BlockSize; } /** * Scan function that is called to garbage collect the memory. */ void scan() { // Stage 1 std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); std::vector<T *> plist; for (auto &&i = head.load(std::memory_order_relaxed); i; i = i->next.get()) { if (!i->active.load(std::memory_order_relaxed)) continue; i->getHps(plist); } if (plist.size() <= 0) return; // Stage 2 std::sort(plist.begin(), plist.end()); GuardedPointer *localRList = myhp->rlistHead; myhp->rlistHead = nullptr; // Stage 3 GuardedPointer *next; for (auto &&g = localRList; g;) { next = g->getNext(); if (std::binary_search(plist.begin(), plist.end(), g->ptr.load(std::memory_order_relaxed))) myhp->retire(g); else myhp->free(g); g = next; } } void helpScan() { std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); bool expected = false; for (auto &&i = head.load(std::memory_order_relaxed); i; i = i->next.get()) { // Trying to lock the next non-used hazard pointer record if (i->active.load(std::memory_order_relaxed) || !i->active.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) continue; // Inserting the rlist of the node in myhp for (auto &&g = i->rlistHead; g; g = g->getNext()) { myhp->retire(g); // scan if we reached the threshold if (myhp->nbRetiredPtrs >= HazardPointerManager::get().getBatchSize()) scan(); } // Release the record i->active.store(false, std::memory_order_relaxed); } } }; // Pointer guarded by the hazard pointer std::unique_ptr<GuardedPointer> ptr; // Thread local storage static std::unique_ptr<HazardPointerRecord> &getMyhp() { static thread_local std::unique_ptr<HazardPointerRecord> myhp; return myhp; } }; } // namespace DNFC #endif <commit_msg>[FIX] HazardPointer: Debug session<commit_after>#ifndef _HAZARD_POINTERH_ #define _HAZARD_POINTERH_ #include <vector> #include <atomic> #include <algorithm> namespace DNFC { /** * HazardPointer default policy * */ class DefaultHazardPointerPolicy { public: const static int BlockSize = 4; }; template <class T, class Policy = DefaultHazardPointerPolicy> class HazardPointer { public: /** * operator=(const HazardPointer& hp) * * copy operator= with the reference to another Hazard Pointer. */ HazardPointer<T, Policy> &operator=(const HazardPointer &hp) { return operator=(hp.get()); } /** * operator=(HazardPointer&& hp) * * move operator= with another Hazard Pointer. */ HazardPointer<T, Policy> &operator=(HazardPointer &&hp) { return operator=(std::move(hp.release())); } /** * operator=(T* p) * * operator= with a pointer to guard. */ HazardPointer<T, Policy> &operator=(T *p) { if (!ptr.get()) { ptr.reset(HazardPointer<T, Policy>::getMyhp()->guard(p)); } else { if (p != ptr->ptr.load(std::memory_order_relaxed)) ptr->ptr.exchange(p, std::memory_order_release); } return *this; } /** * get * * Retrieve the guarded pointer. */ T *get() const { if (!ptr.get()) return nullptr; return ptr->ptr.load(std::memory_order_relaxed); } /** * release * * Release the safety guard on the pointer. */ T *release() { if (!ptr.get()) return nullptr; return ptr->ptr.exchange(nullptr, std::memory_order_release); } /** * retire * * Safely retire the node for deletion. */ void retire() { std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); if (!myhp.get()) return; myhp->retire(ptr.release()); if (myhp->nbRetiredPtrs >= HazardPointerManager::get().getBatchSize()) { HazardPointerManager::get().scan(); HazardPointerManager::get().helpScan(); } } /** * Constructor * * Automatically subscribe to the manager but don't guard any pointer. * The manager will prevent a thread to subscribe more than one time. */ HazardPointer() : ptr(nullptr) { HazardPointerManager::get().subscribe(); } /** * Constructor * * Automatically subscribe to the manager and guard the given pointer. * The manager will prevent a thread to subscribe more than one time. */ HazardPointer(T *p) { HazardPointerManager::get().subscribe(); if (ptr.get()) { ptr->ptr.exchange(p, std::memory_order_release); return; } ptr.reset(HazardPointer<T, Policy>::getMyhp()->guard(p)); }; /** * Release the guarded pointer if there is one. If no more pointers are * guarded in this thread, then it will unsubscribe from the manager. */ ~HazardPointer() { std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); if (myhp) { if (ptr.get()) myhp->release(ptr.release()); if (myhp->nbActivePtrs <= 0) HazardPointerManager::get().unsubscribe(); } }; private: /** * GuardedPointer * * A convenient linked list that hold a pointer on which deletion is prohibited. * In practice each GuardedPointer are contiguous within each GuardedPointerBlock. * See GuardedPointerBlock for more information. */ struct GuardedPointer { std::atomic<T *> ptr; std::atomic<GuardedPointer *> next; void setPtr(T *p) { ptr.store(p, std::memory_order_release); } void setNext(GuardedPointer *n) { next.store(n, std::memory_order_release); } GuardedPointer *getNext() { return getCleared(next.load(std::memory_order_relaxed)); } bool isDeleted() { uintptr_t nextPtr = reinterpret_cast<uintptr_t>(next.load(std::memory_order_relaxed)); return reinterpret_cast<GuardedPointer *>(nextPtr & 0x1); } void markAsDeleted() { uintptr_t nextPtr = reinterpret_cast<uintptr_t>(next.load(std::memory_order_relaxed)); GuardedPointer *mrkd = reinterpret_cast<GuardedPointer *>(nextPtr | 0x1); next.store(mrkd, std::memory_order_release); } private: GuardedPointer *getCleared(GuardedPointer *p) { uintptr_t nextPtr = reinterpret_cast<uintptr_t>(p); return reinterpret_cast<GuardedPointer *>(nextPtr & ~0x1); } }; /** * GuardedPointerBlock * * An helping structure for memory managment. This structure represent a 'chunk' * of memory used for GuardedPointer contiguous arrays. This will allocate the * 'Policy::BlockSize' number of GuardedPointer. */ struct GuardedPointerBlock { std::unique_ptr<GuardedPointerBlock> next = nullptr; GuardedPointer *begin() { return reinterpret_cast<GuardedPointer *>(this + 1); } GuardedPointer *end() { return begin() + Policy::BlockSize; } const GuardedPointer *begin() const { return reinterpret_cast<const GuardedPointer *>(this + 1); } const GuardedPointer *end() const { return begin() + Policy::BlockSize; } GuardedPointerBlock() { GuardedPointer *last = end() - 1; for (auto &&g = begin(); g != last; g = g->next) g->next = g + 1; last->next = nullptr; }; }; /** * HazardPointerRecord * * An object that hold informations about allocated hazard pointers for the current * thread. */ struct HazardPointerRecord { GuardedPointer *rlistHead = nullptr; int nbActivePtrs = 0; int nbRetiredPtrs; std::atomic<bool> active; std::unique_ptr<HazardPointerRecord> next; // Guard a given pointer GuardedPointer *guard(T *p) { GuardedPointer *newPtr = allocPtr(); newPtr->setPtr(p); nbActivePtrs++; HazardPointerManager::get().nbhp.fetch_add(1, std::memory_order_relaxed); return newPtr; } // Put a pointer on the retire list for it to be removed void retire(GuardedPointer *n) { n->setNext(rlistHead); n->markAsDeleted(); rlistHead = n; nbRetiredPtrs++; nbActivePtrs--; HazardPointerManager::get().nbhp.fetch_sub(1, std::memory_order_relaxed); } // Return the GuardedPointer to the memory pool const T *release(GuardedPointer *p) { const T *data = p->ptr.load(std::memory_order_relaxed); freePtr(p); return data; } // Destroy the guarded pointer void free(GuardedPointer *n) { delete n->ptr.load(std::memory_order_relaxed); n->ptr.store(nullptr, std::memory_order_release); freePtr(n); } // Return in the passed vector of pointers, all the Hazard Pointers in this HazardPointerRecord void getHps(std::vector<T *> &output) { getHpsPriv(output, blockHead.load(std::memory_order_relaxed)); } HazardPointerRecord(HazardPointerRecord *head = nullptr, bool active = true) : next(head), nbRetiredPtrs(0), blockHead(nullptr) { this->active.store(active, std::memory_order_relaxed); } ~HazardPointerRecord() { if (blockHead.load(std::memory_order_relaxed)) delete blockHead.load(std::memory_order_relaxed); } private: std::atomic<GuardedPointerBlock *> blockHead; GuardedPointer *flistHead = nullptr; // Manage pointers memory allocation GuardedPointer *allocPtr() { GuardedPointer *newPtr; if (!flistHead) { void *chunk = std::malloc(Policy::BlockSize * sizeof(GuardedPointer) + sizeof(GuardedPointerBlock)); GuardedPointerBlock *newBlock = ::new (chunk) GuardedPointerBlock(); GuardedPointerBlock *head = blockHead.exchange(newBlock, std::memory_order_relaxed); newBlock->next.reset(head); flistHead = newBlock->begin(); } newPtr = flistHead; flistHead = newPtr->getNext(); newPtr->setNext(nullptr); return newPtr; } // Put HazardPointer on free list for reuse void freePtr(GuardedPointer *p) { p->setPtr(nullptr); p->setNext(flistHead); p->markAsDeleted(); flistHead = p; nbActivePtrs--; HazardPointerManager::get().nbhp.fetch_sub(1, std::memory_order_relaxed); } // Return a vector of all the Hazard Pointer contained in the GuardedPointerBlock linked list void getHpsPriv(std::vector<T *> &output, GuardedPointerBlock *block) { for (auto &&g : *block) { if (!g.isDeleted()) output.push_back(g.ptr.load()); } if (block && block->next) getHpsPriv(output, block->next.get()); } }; /** * HazardPointerManager * * This singleton private class provide a central managment point for safe memory reclamation. * It provide memory managment for system wide hazard pointers. */ friend class HazardPointerManager; class HazardPointerManager { public: // Retrive the unique instance of the HazardPointerManager static HazardPointerManager &get() { static HazardPointerManager m; return m; } ~HazardPointerManager() { delete head.load(std::memory_order_relaxed); } std::atomic<HazardPointerRecord *> head = nullptr; std::atomic<int> nbhp; /** * Subscribe a thread to the manager. During the time the thread is subscribed, it is * given a HazardPointerRecord object that allow it to protect 'Policy::BlockSize' pointers. */ void subscribe() { int tid = pthread_self() % 1000; // Prevent subbing more than once std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); if (myhp.get()) return; // First try to reuse a retire HP record bool expected = false; for (HazardPointerRecord *i = head.load(std::memory_order_relaxed); i != nullptr; i = i->next.get()) { if (i->active.load(std::memory_order_relaxed) || !i->active.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) continue; // Sucessfully locked one record to use myhp.reset(i); return; } // Allocate and push a new record myhp.reset(new HazardPointerRecord(head.load(std::memory_order_relaxed), true)); // Add the new record to the list HazardPointerRecord *nextPtrVal = myhp->next.get(); while (!head.compare_exchange_weak(nextPtrVal, myhp.get(), std::memory_order_release, std::memory_order_relaxed)) ; } /** * Unsubscribe the current thread from the manager. */ void unsubscribe() { std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); // Prevent unsubscribe more than once int tid = pthread_self() % 1000; if (!myhp.get()) return; myhp->active.store(false, std::memory_order_relaxed); myhp.release(); } /** * Retrieve the threshold of the manager before scanning is required */ unsigned int getBatchSize() { return nbhp.load(std::memory_order_relaxed) * 2 + Policy::BlockSize; } /** * Scan function that is called to garbage collect the memory. */ void scan() { // Stage 1 std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); std::vector<T *> plist; for (auto &&i = head.load(std::memory_order_relaxed); i; i = i->next.get()) { if (!i->active.load(std::memory_order_relaxed)) continue; i->getHps(plist); } if (plist.size() <= 0) return; // Stage 2 std::sort(plist.begin(), plist.end()); GuardedPointer *localRList = myhp->rlistHead; myhp->rlistHead = nullptr; // Stage 3 GuardedPointer *next; for (auto &&g = localRList; g;) { next = g->getNext(); if (std::binary_search(plist.begin(), plist.end(), g->ptr.load(std::memory_order_relaxed))) myhp->retire(g); else myhp->free(g); g = next; } } void helpScan() { std::unique_ptr<HazardPointerRecord> &myhp = HazardPointer<T, Policy>::getMyhp(); bool expected = false; for (auto &&i = head.load(std::memory_order_relaxed); i; i = i->next.get()) { // Trying to lock the next non-used hazard pointer record if (i->active.load(std::memory_order_relaxed) || !i->active.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) continue; // Inserting the rlist of the node in myhp for (auto &&g = i->rlistHead; g; g = g->getNext()) { myhp->retire(g); // scan if we reached the threshold if (myhp->nbRetiredPtrs >= HazardPointerManager::get().getBatchSize()) scan(); } // Release the record i->active.store(false, std::memory_order_relaxed); } } }; // Pointer guarded by the hazard pointer std::unique_ptr<GuardedPointer> ptr; // Thread local storage static std::unique_ptr<HazardPointerRecord> &getMyhp() { static thread_local std::unique_ptr<HazardPointerRecord> myhp; return myhp; } }; } // namespace DNFC #endif <|endoftext|>
<commit_before>#include <sstream> #include "StorageFlattening.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Bounds.h" #include "Parameter.h" namespace Halide { namespace Internal { using std::ostringstream; using std::string; using std::vector; using std::map; using std::pair; using std::set; namespace { class FlattenDimensions : public IRMutator { public: FlattenDimensions(const map<string, pair<Function, int>> &e, const vector<Function> &o, const Target &t) : env(e), target(t) { for (auto &f : o) { outputs.insert(f.name()); } } Scope<int> scope; private: const map<string, pair<Function, int>> &env; set<string> outputs; const Target &target; Scope<int> realizations; Expr flatten_args(const string &name, const vector<Expr> &args, const Buffer<> &buf, const Parameter &param) { bool internal = realizations.contains(name); Expr idx = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0; vector<Expr> mins(args.size()), strides(args.size()); ReductionDomain rdom; for (size_t i = 0; i < args.size(); i++) { string dim = std::to_string(i); string stride_name = name + ".stride." + dim; string min_name = name + ".min." + dim; string stride_name_constrained = stride_name + ".constrained"; string min_name_constrained = min_name + ".constrained"; if (scope.contains(stride_name_constrained)) { stride_name = stride_name_constrained; } if (scope.contains(min_name_constrained)) { min_name = min_name_constrained; } strides[i] = Variable::make(Int(32), stride_name, buf, param, rdom); mins[i] = Variable::make(Int(32), min_name, buf, param, rdom); } if (internal) { // f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This // strategy makes sense when we expect x to cancel with // something in xmin. We use this for internal allocations for (size_t i = 0; i < args.size(); i++) { if (target.has_feature(Target::LargeBuffers)) { idx += cast<int64_t>(args[i] - mins[i]) * cast<int64_t>(strides[i]); } else { idx += (args[i] - mins[i]) * strides[i]; } } } else { // f(x, y) -> f[x*stride + y*ystride - (xstride*xmin + // ystride*ymin)]. The idea here is that the last term // will be pulled outside the inner loop. We use this for // external buffers, where the mins and strides are likely // to be symbolic Expr base = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0; for (size_t i = 0; i < args.size(); i++) { if (target.has_feature(Target::LargeBuffers)) { idx += cast<int64_t>(args[i]) * cast<int64_t>(strides[i]); base += cast<int64_t>(mins[i]) * cast<int64_t>(strides[i]); } else { idx += args[i] * strides[i]; base += mins[i] * strides[i]; } } idx -= base; } return idx; } using IRMutator::visit; void visit(const Realize *op) { realizations.push(op->name, 0); Stmt body = mutate(op->body); // Compute the size vector<Expr> extents; for (size_t i = 0; i < op->bounds.size(); i++) { extents.push_back(op->bounds[i].extent); extents[i] = mutate(extents[i]); } Expr condition = mutate(op->condition); realizations.pop(op->name); vector<int> storage_permutation; { auto iter = env.find(op->name); internal_assert(iter != env.end()) << "Realize node refers to function not in environment.\n"; Function f = iter->second.first; const vector<StorageDim> &storage_dims = f.schedule().storage_dims(); const vector<string> &args = f.args(); debug(0) << "Args:\n"; for (string s : args) { debug(0) << " " << s << "\n"; } debug(0) << "Storage dims:\n"; for (StorageDim d : storage_dims) { debug(0) << " " << d.var << "\n"; } for (size_t i = 0; i < storage_dims.size(); i++) { for (size_t j = 0; j < args.size(); j++) { if (args[j] == storage_dims[i].var) { storage_permutation.push_back((int)j); Expr alignment = storage_dims[i].alignment; if (alignment.defined()) { extents[j] = ((extents[j] + alignment - 1)/alignment)*alignment; } } } internal_assert(storage_permutation.size() == i+1); } } internal_assert(storage_permutation.size() == op->bounds.size()); stmt = body; internal_assert(op->types.size() == 1); // Make the names for the mins, extents, and strides int dims = op->bounds.size(); vector<string> min_name(dims), extent_name(dims), stride_name(dims); for (int i = 0; i < dims; i++) { string d = std::to_string(i); min_name[i] = op->name + ".min." + d; stride_name[i] = op->name + ".stride." + d; extent_name[i] = op->name + ".extent." + d; } vector<Expr> min_var(dims), extent_var(dims), stride_var(dims); for (int i = 0; i < dims; i++) { min_var[i] = Variable::make(Int(32), min_name[i]); extent_var[i] = Variable::make(Int(32), extent_name[i]); stride_var[i] = Variable::make(Int(32), stride_name[i]); } // Create a buffer_t object for this allocation. BufferBuilder builder; builder.host = Variable::make(Handle(), op->name); builder.type = op->types[0]; builder.dimensions = dims; for (int i = 0; i < dims; i++) { builder.mins.push_back(min_var[i]); builder.extents.push_back(extent_var[i]); builder.strides.push_back(stride_var[i]); } stmt = LetStmt::make(op->name + ".buffer", builder.build(), stmt); // Make the allocation node stmt = Allocate::make(op->name, op->types[0], extents, condition, stmt); // Compute the strides for (int i = (int)op->bounds.size()-1; i > 0; i--) { int prev_j = storage_permutation[i-1]; int j = storage_permutation[i]; Expr stride = stride_var[prev_j] * extent_var[prev_j]; stmt = LetStmt::make(stride_name[j], stride, stmt); } // Innermost stride is one if (dims > 0) { int innermost = storage_permutation.empty() ? 0 : storage_permutation[0]; stmt = LetStmt::make(stride_name[innermost], 1, stmt); } // Assign the mins and extents stored for (size_t i = op->bounds.size(); i > 0; i--) { stmt = LetStmt::make(min_name[i-1], op->bounds[i-1].min, stmt); stmt = LetStmt::make(extent_name[i-1], extents[i-1], stmt); } } void visit(const Provide *op) { internal_assert(op->values.size() == 1); Parameter output_buf; auto it = env.find(op->name); if (it != env.end()) { const Function &f = it->second.first; int idx = it->second.second; // We only want to do this for actual pipeline outputs, // even though every Function has an output buffer. Any // constraints you set on the output buffer of a Func that // isn't actually an output is ignored. This is a language // wart. if (outputs.count(f.name())) { output_buf = f.output_buffers()[idx]; } } Expr idx = mutate(flatten_args(op->name, op->args, Buffer<>(), output_buf)); Expr value = mutate(op->values[0]); stmt = Store::make(op->name, value, idx, output_buf, const_true(value.type().lanes())); } void visit(const Call *op) { if (op->call_type == Call::Halide || op->call_type == Call::Image) { internal_assert(op->value_index == 0); Expr idx = mutate(flatten_args(op->name, op->args, op->image, op->param)); expr = Load::make(op->type, op->name, idx, op->image, op->param, const_true(op->type.lanes())); } else { IRMutator::visit(op); } } void visit(const Prefetch *op) { internal_assert(op->types.size() == 1) << "Prefetch from multi-dimensional halide tuple should have been split\n"; vector<Expr> prefetch_min(op->bounds.size()); vector<Expr> prefetch_extent(op->bounds.size()); vector<Expr> prefetch_stride(op->bounds.size()); for (size_t i = 0; i < op->bounds.size(); i++) { prefetch_min[i] = mutate(op->bounds[i].min); prefetch_extent[i] = mutate(op->bounds[i].extent); prefetch_stride[i] = Variable::make(Int(32), op->name + ".stride." + std::to_string(i), op->param); } Expr base_offset = mutate(flatten_args(op->name, prefetch_min, Buffer<>(), op->param)); Expr base_address = Variable::make(Handle(), op->name); vector<Expr> args = {base_address, base_offset}; auto iter = env.find(op->name); if (iter != env.end()) { // Order the <min, extent> args based on the storage dims (i.e. innermost // dimension should be first in args) vector<int> storage_permutation; { Function f = iter->second.first; const vector<StorageDim> &storage_dims = f.schedule().storage_dims(); const vector<string> &args = f.args(); for (size_t i = 0; i < storage_dims.size(); i++) { for (size_t j = 0; j < args.size(); j++) { if (args[j] == storage_dims[i].var) { storage_permutation.push_back((int)j); } } internal_assert(storage_permutation.size() == i+1); } } internal_assert(storage_permutation.size() == op->bounds.size()); for (size_t i = 0; i < op->bounds.size(); i++) { internal_assert(storage_permutation[i] < (int)op->bounds.size()); args.push_back(prefetch_extent[storage_permutation[i]]); args.push_back(prefetch_stride[storage_permutation[i]]); } } else { for (size_t i = 0; i < op->bounds.size(); i++) { args.push_back(prefetch_extent[i]); args.push_back(prefetch_stride[i]); } } stmt = Evaluate::make(Call::make(op->types[0], Call::prefetch, args, Call::Intrinsic)); } void visit(const LetStmt *let) { // Discover constrained versions of things. bool constrained_version_exists = ends_with(let->name, ".constrained"); if (constrained_version_exists) { scope.push(let->name, 0); } IRMutator::visit(let); if (constrained_version_exists) { scope.pop(let->name); } } }; // Realizations, stores, and loads must all be on types that are // multiples of 8-bits. This really only affects bools class PromoteToMemoryType : public IRMutator { using IRMutator::visit; Type upgrade(Type t) { return t.with_bits(((t.bits() + 7)/8)*8); } void visit(const Load *op) { Type t = upgrade(op->type); if (t != op->type) { expr = Cast::make(op->type, Load::make(t, op->name, mutate(op->index), op->image, op->param, mutate(op->predicate))); } else { IRMutator::visit(op); } } void visit(const Store *op) { Type t = upgrade(op->value.type()); if (t != op->value.type()) { stmt = Store::make(op->name, Cast::make(t, mutate(op->value)), mutate(op->index), op->param, mutate(op->predicate)); } else { IRMutator::visit(op); } } void visit(const Allocate *op) { Type t = upgrade(op->type); if (t != op->type) { vector<Expr> extents; for (Expr e : op->extents) { extents.push_back(mutate(e)); } stmt = Allocate::make(op->name, t, extents, mutate(op->condition), mutate(op->body), mutate(op->new_expr), op->free_function); } else { IRMutator::visit(op); } } }; } // namespace Stmt storage_flattening(Stmt s, const vector<Function> &outputs, const map<string, Function> &env, const Target &target) { // Make an environment that makes it easier to figure out which // Function corresponds to a tuple component. foo.0, foo.1, foo.2, // all point to the function foo. map<string, pair<Function, int>> tuple_env; for (auto p : env) { if (p.second.outputs() > 1) { for (int i = 0; i < p.second.outputs(); i++) { tuple_env[p.first + "." + std::to_string(i)] = {p.second, i}; } } else { tuple_env[p.first] = {p.second, 0}; } } s = FlattenDimensions(tuple_env, outputs, target).mutate(s); s = PromoteToMemoryType().mutate(s); return s; } } } <commit_msg>Remove debugging prints<commit_after>#include <sstream> #include "StorageFlattening.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Bounds.h" #include "Parameter.h" namespace Halide { namespace Internal { using std::ostringstream; using std::string; using std::vector; using std::map; using std::pair; using std::set; namespace { class FlattenDimensions : public IRMutator { public: FlattenDimensions(const map<string, pair<Function, int>> &e, const vector<Function> &o, const Target &t) : env(e), target(t) { for (auto &f : o) { outputs.insert(f.name()); } } Scope<int> scope; private: const map<string, pair<Function, int>> &env; set<string> outputs; const Target &target; Scope<int> realizations; Expr flatten_args(const string &name, const vector<Expr> &args, const Buffer<> &buf, const Parameter &param) { bool internal = realizations.contains(name); Expr idx = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0; vector<Expr> mins(args.size()), strides(args.size()); ReductionDomain rdom; for (size_t i = 0; i < args.size(); i++) { string dim = std::to_string(i); string stride_name = name + ".stride." + dim; string min_name = name + ".min." + dim; string stride_name_constrained = stride_name + ".constrained"; string min_name_constrained = min_name + ".constrained"; if (scope.contains(stride_name_constrained)) { stride_name = stride_name_constrained; } if (scope.contains(min_name_constrained)) { min_name = min_name_constrained; } strides[i] = Variable::make(Int(32), stride_name, buf, param, rdom); mins[i] = Variable::make(Int(32), min_name, buf, param, rdom); } if (internal) { // f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This // strategy makes sense when we expect x to cancel with // something in xmin. We use this for internal allocations for (size_t i = 0; i < args.size(); i++) { if (target.has_feature(Target::LargeBuffers)) { idx += cast<int64_t>(args[i] - mins[i]) * cast<int64_t>(strides[i]); } else { idx += (args[i] - mins[i]) * strides[i]; } } } else { // f(x, y) -> f[x*stride + y*ystride - (xstride*xmin + // ystride*ymin)]. The idea here is that the last term // will be pulled outside the inner loop. We use this for // external buffers, where the mins and strides are likely // to be symbolic Expr base = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0; for (size_t i = 0; i < args.size(); i++) { if (target.has_feature(Target::LargeBuffers)) { idx += cast<int64_t>(args[i]) * cast<int64_t>(strides[i]); base += cast<int64_t>(mins[i]) * cast<int64_t>(strides[i]); } else { idx += args[i] * strides[i]; base += mins[i] * strides[i]; } } idx -= base; } return idx; } using IRMutator::visit; void visit(const Realize *op) { realizations.push(op->name, 0); Stmt body = mutate(op->body); // Compute the size vector<Expr> extents; for (size_t i = 0; i < op->bounds.size(); i++) { extents.push_back(op->bounds[i].extent); extents[i] = mutate(extents[i]); } Expr condition = mutate(op->condition); realizations.pop(op->name); vector<int> storage_permutation; { auto iter = env.find(op->name); internal_assert(iter != env.end()) << "Realize node refers to function not in environment.\n"; Function f = iter->second.first; const vector<StorageDim> &storage_dims = f.schedule().storage_dims(); const vector<string> &args = f.args(); for (size_t i = 0; i < storage_dims.size(); i++) { for (size_t j = 0; j < args.size(); j++) { if (args[j] == storage_dims[i].var) { storage_permutation.push_back((int)j); Expr alignment = storage_dims[i].alignment; if (alignment.defined()) { extents[j] = ((extents[j] + alignment - 1)/alignment)*alignment; } } } internal_assert(storage_permutation.size() == i+1); } } internal_assert(storage_permutation.size() == op->bounds.size()); stmt = body; internal_assert(op->types.size() == 1); // Make the names for the mins, extents, and strides int dims = op->bounds.size(); vector<string> min_name(dims), extent_name(dims), stride_name(dims); for (int i = 0; i < dims; i++) { string d = std::to_string(i); min_name[i] = op->name + ".min." + d; stride_name[i] = op->name + ".stride." + d; extent_name[i] = op->name + ".extent." + d; } vector<Expr> min_var(dims), extent_var(dims), stride_var(dims); for (int i = 0; i < dims; i++) { min_var[i] = Variable::make(Int(32), min_name[i]); extent_var[i] = Variable::make(Int(32), extent_name[i]); stride_var[i] = Variable::make(Int(32), stride_name[i]); } // Create a buffer_t object for this allocation. BufferBuilder builder; builder.host = Variable::make(Handle(), op->name); builder.type = op->types[0]; builder.dimensions = dims; for (int i = 0; i < dims; i++) { builder.mins.push_back(min_var[i]); builder.extents.push_back(extent_var[i]); builder.strides.push_back(stride_var[i]); } stmt = LetStmt::make(op->name + ".buffer", builder.build(), stmt); // Make the allocation node stmt = Allocate::make(op->name, op->types[0], extents, condition, stmt); // Compute the strides for (int i = (int)op->bounds.size()-1; i > 0; i--) { int prev_j = storage_permutation[i-1]; int j = storage_permutation[i]; Expr stride = stride_var[prev_j] * extent_var[prev_j]; stmt = LetStmt::make(stride_name[j], stride, stmt); } // Innermost stride is one if (dims > 0) { int innermost = storage_permutation.empty() ? 0 : storage_permutation[0]; stmt = LetStmt::make(stride_name[innermost], 1, stmt); } // Assign the mins and extents stored for (size_t i = op->bounds.size(); i > 0; i--) { stmt = LetStmt::make(min_name[i-1], op->bounds[i-1].min, stmt); stmt = LetStmt::make(extent_name[i-1], extents[i-1], stmt); } } void visit(const Provide *op) { internal_assert(op->values.size() == 1); Parameter output_buf; auto it = env.find(op->name); if (it != env.end()) { const Function &f = it->second.first; int idx = it->second.second; // We only want to do this for actual pipeline outputs, // even though every Function has an output buffer. Any // constraints you set on the output buffer of a Func that // isn't actually an output is ignored. This is a language // wart. if (outputs.count(f.name())) { output_buf = f.output_buffers()[idx]; } } Expr idx = mutate(flatten_args(op->name, op->args, Buffer<>(), output_buf)); Expr value = mutate(op->values[0]); stmt = Store::make(op->name, value, idx, output_buf, const_true(value.type().lanes())); } void visit(const Call *op) { if (op->call_type == Call::Halide || op->call_type == Call::Image) { internal_assert(op->value_index == 0); Expr idx = mutate(flatten_args(op->name, op->args, op->image, op->param)); expr = Load::make(op->type, op->name, idx, op->image, op->param, const_true(op->type.lanes())); } else { IRMutator::visit(op); } } void visit(const Prefetch *op) { internal_assert(op->types.size() == 1) << "Prefetch from multi-dimensional halide tuple should have been split\n"; vector<Expr> prefetch_min(op->bounds.size()); vector<Expr> prefetch_extent(op->bounds.size()); vector<Expr> prefetch_stride(op->bounds.size()); for (size_t i = 0; i < op->bounds.size(); i++) { prefetch_min[i] = mutate(op->bounds[i].min); prefetch_extent[i] = mutate(op->bounds[i].extent); prefetch_stride[i] = Variable::make(Int(32), op->name + ".stride." + std::to_string(i), op->param); } Expr base_offset = mutate(flatten_args(op->name, prefetch_min, Buffer<>(), op->param)); Expr base_address = Variable::make(Handle(), op->name); vector<Expr> args = {base_address, base_offset}; auto iter = env.find(op->name); if (iter != env.end()) { // Order the <min, extent> args based on the storage dims (i.e. innermost // dimension should be first in args) vector<int> storage_permutation; { Function f = iter->second.first; const vector<StorageDim> &storage_dims = f.schedule().storage_dims(); const vector<string> &args = f.args(); for (size_t i = 0; i < storage_dims.size(); i++) { for (size_t j = 0; j < args.size(); j++) { if (args[j] == storage_dims[i].var) { storage_permutation.push_back((int)j); } } internal_assert(storage_permutation.size() == i+1); } } internal_assert(storage_permutation.size() == op->bounds.size()); for (size_t i = 0; i < op->bounds.size(); i++) { internal_assert(storage_permutation[i] < (int)op->bounds.size()); args.push_back(prefetch_extent[storage_permutation[i]]); args.push_back(prefetch_stride[storage_permutation[i]]); } } else { for (size_t i = 0; i < op->bounds.size(); i++) { args.push_back(prefetch_extent[i]); args.push_back(prefetch_stride[i]); } } stmt = Evaluate::make(Call::make(op->types[0], Call::prefetch, args, Call::Intrinsic)); } void visit(const LetStmt *let) { // Discover constrained versions of things. bool constrained_version_exists = ends_with(let->name, ".constrained"); if (constrained_version_exists) { scope.push(let->name, 0); } IRMutator::visit(let); if (constrained_version_exists) { scope.pop(let->name); } } }; // Realizations, stores, and loads must all be on types that are // multiples of 8-bits. This really only affects bools class PromoteToMemoryType : public IRMutator { using IRMutator::visit; Type upgrade(Type t) { return t.with_bits(((t.bits() + 7)/8)*8); } void visit(const Load *op) { Type t = upgrade(op->type); if (t != op->type) { expr = Cast::make(op->type, Load::make(t, op->name, mutate(op->index), op->image, op->param, mutate(op->predicate))); } else { IRMutator::visit(op); } } void visit(const Store *op) { Type t = upgrade(op->value.type()); if (t != op->value.type()) { stmt = Store::make(op->name, Cast::make(t, mutate(op->value)), mutate(op->index), op->param, mutate(op->predicate)); } else { IRMutator::visit(op); } } void visit(const Allocate *op) { Type t = upgrade(op->type); if (t != op->type) { vector<Expr> extents; for (Expr e : op->extents) { extents.push_back(mutate(e)); } stmt = Allocate::make(op->name, t, extents, mutate(op->condition), mutate(op->body), mutate(op->new_expr), op->free_function); } else { IRMutator::visit(op); } } }; } // namespace Stmt storage_flattening(Stmt s, const vector<Function> &outputs, const map<string, Function> &env, const Target &target) { // Make an environment that makes it easier to figure out which // Function corresponds to a tuple component. foo.0, foo.1, foo.2, // all point to the function foo. map<string, pair<Function, int>> tuple_env; for (auto p : env) { if (p.second.outputs() > 1) { for (int i = 0; i < p.second.outputs(); i++) { tuple_env[p.first + "." + std::to_string(i)] = {p.second, i}; } } else { tuple_env[p.first] = {p.second, 0}; } } s = FlattenDimensions(tuple_env, outputs, target).mutate(s); s = PromoteToMemoryType().mutate(s); return s; } } } <|endoftext|>
<commit_before> // LogMainView.cpp : CLogMainView 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "LogCC.h" #endif #include "LogCCDoc.h" #include "LogMainView.h" #include "ILogQuery.h" #include "LogQueryResult.h" #include "LogItem.h" #include "ILogItemPainter.h" #include "LogPainterFactory.h" #ifdef _DEBUG #define new DEBUG_NEW #endif static const unsigned LineHeight = 15; // CLogMainView IMPLEMENT_DYNCREATE(CLogMainView, CScrollView) BEGIN_MESSAGE_MAP(CLogMainView, CScrollView) ON_WM_ERASEBKGND() ON_WM_VSCROLL() ON_WM_MOUSEMOVE() END_MESSAGE_MAP() // CLogMainView 构造/析构 CLogMainView::CLogMainView() { } CLogMainView::~CLogMainView() { } // CLogMainView 绘制 void CLogMainView::OnDraw(CDC* pDC) { CLogCCDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; CRect clientRect; GetClientRect(clientRect); DEBUG_INFO(_T("客户区区域:") << clientRect.left << ", " << clientRect.top << ", " << clientRect.right << ", " << clientRect.bottom); HDC memDC = ::CreateCompatibleDC(pDC->GetSafeHdc()); HBITMAP memBmp = ::CreateCompatibleBitmap(pDC->GetSafeHdc(), clientRect.Width(), clientRect.Height()); HGDIOBJ oldBmp = ::SelectObject(memDC, memBmp); HBRUSH bkgdBrush = reinterpret_cast<HBRUSH>(::GetStockObject(WHITE_BRUSH)); ::FillRect(memDC, clientRect, bkgdBrush); HFONT font = ::CreateFont(LineHeight - 2, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH, _T("新宋体")); HGDIOBJ oldFont = ::SelectObject(memDC, font); DEBUG_INFO(_T("重绘")); CPoint scrollPosition = GetScrollPosition(); DEBUG_INFO(_T("滚动条位置:") << scrollPosition.x << ", " << scrollPosition.y); // 顶部可以显示半行 int yLogLineStart = scrollPosition.y % LineHeight == 0 ? 0 : scrollPosition.y % LineHeight - LineHeight; unsigned beginLine = scrollPosition.y / LineHeight; // +1是为了底部能显示半行 unsigned endLine = (scrollPosition.y + clientRect.Height()) / LineHeight + 1; endLine = min(endLine, GetDocument()->logQuery->getCurQueryResult()->getCount()); DEBUG_INFO(_T("行号区间:") << beginLine << ", " << endLine); vector<LogItem*> vecLines = GetDocument()->logQuery->getCurQueryResult()->getRange(beginLine, endLine); for (unsigned i = 0; i < vecLines.size(); i++) { LogItem* item = vecLines[i]; CRect rect = clientRect; rect.top = yLogLineStart + i * LineHeight; rect.bottom = rect.top + LineHeight; LogPainterFactory::GetInstance()->GetSingleLinePainter()->Draw(memDC, rect, *item); } ::BitBlt(pDC->GetSafeHdc(), scrollPosition.x, scrollPosition.y, clientRect.Width(), clientRect.Height(), memDC, 0, 0, SRCCOPY); ::SelectObject(memDC, oldFont); ::DeleteObject(font); ::SelectObject(memDC, oldBmp); ::DeleteObject(memBmp); ::DeleteDC(memDC); } void CLogMainView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); GetDocument()->logQuery->registerObserver(this); UpdateScroll(); SetFocus(); } void CLogMainView::PostNcDestroy() { GetDocument()->logQuery->unregisterObserver(this); __super::PostNcDestroy(); } void CLogMainView::UpdateScroll() { CRect clientRect; GetClientRect(clientRect); CSize totalSize; totalSize.cx = clientRect.Width(); // 加1是为了最后一行一定可见 GetDocument()->length = totalSize.cy = (GetDocument()->logQuery->getCurQueryResult()->getCount() + 1) * LineHeight; #define LOGCC_WINUI_CUSTOMIZE_PAGE_SIZE_LINE_SIZE #ifdef LOGCC_WINUI_CUSTOMIZE_PAGE_SIZE_LINE_SIZE CSize pageSize(clientRect.Width(), clientRect.Height() / LineHeight * LineHeight); CSize lineSize(clientRect.Width(), LineHeight); SetScrollSizes(MM_TEXT, totalSize, pageSize, lineSize); #else SetScrollSizes(MM_TEXT, totalSize); #endif #define LOGCC_WINUI_SCROLL_TO_END_ON_UPDATE #ifdef LOGCC_WINUI_SCROLL_TO_END_ON_UPDATE int y = totalSize.cy - clientRect.Height(); ScrollToPosition(CPoint(0, max(y, 0))); #endif } void CLogMainView::onGeneralDataChanged() { Invalidate(); } void CLogMainView::onQueryResultChanged() { UpdateScroll(); Invalidate(); } void CLogMainView::onScrollPositionChanged(int yPosition) { CPoint position = GetScrollPosition(); position.y = yPosition; ScrollToPosition(position); } #ifdef _DEBUG CLogCCDoc* CLogMainView::GetDocument() const // 非调试版本是内联的 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CLogCCDoc))); return (CLogCCDoc*)m_pDocument; } #endif //_DEBUG // CLogMainView 消息处理程序 BOOL CLogMainView::OnEraseBkgnd(CDC* pDC) { #ifdef LOGCC_WINUI_USE_DEFAULT_ERASE_BACKGROUND return CScrollView::OnEraseBkgnd(pDC); #else return TRUE; #endif } void CLogMainView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { if (nSBCode == SB_ENDSCROLL) { Invalidate(); } CScrollView::OnVScroll(nSBCode, nPos, pScrollBar); } BOOL CLogMainView::PreTranslateMessage(MSG* pMsg) { // 更新UI数据到ViewData CPoint scrollPos = GetScrollPosition(); GetDocument()->yScrollPos = scrollPos.y; GetDocument()->lineHeight = LineHeight; GetClientRect(GetDocument()->clientRect); return __super::PreTranslateMessage(pMsg); } void CLogMainView::OnMouseMove(UINT nFlags, CPoint point) { if (GetForegroundWindow() == AfxGetMainWnd()) { SetFocus(); } __super::OnMouseMove(nFlags, point); } <commit_msg>横向滚动长度设为0,尝试彻底禁止滚动条<commit_after> // LogMainView.cpp : CLogMainView 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "LogCC.h" #endif #include "LogCCDoc.h" #include "LogMainView.h" #include "ILogQuery.h" #include "LogQueryResult.h" #include "LogItem.h" #include "ILogItemPainter.h" #include "LogPainterFactory.h" #ifdef _DEBUG #define new DEBUG_NEW #endif static const unsigned LineHeight = 15; // CLogMainView IMPLEMENT_DYNCREATE(CLogMainView, CScrollView) BEGIN_MESSAGE_MAP(CLogMainView, CScrollView) ON_WM_ERASEBKGND() ON_WM_VSCROLL() ON_WM_MOUSEMOVE() END_MESSAGE_MAP() // CLogMainView 构造/析构 CLogMainView::CLogMainView() { } CLogMainView::~CLogMainView() { } // CLogMainView 绘制 void CLogMainView::OnDraw(CDC* pDC) { CLogCCDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; CRect clientRect; GetClientRect(clientRect); DEBUG_INFO(_T("客户区区域:") << clientRect.left << ", " << clientRect.top << ", " << clientRect.right << ", " << clientRect.bottom); HDC memDC = ::CreateCompatibleDC(pDC->GetSafeHdc()); HBITMAP memBmp = ::CreateCompatibleBitmap(pDC->GetSafeHdc(), clientRect.Width(), clientRect.Height()); HGDIOBJ oldBmp = ::SelectObject(memDC, memBmp); HBRUSH bkgdBrush = reinterpret_cast<HBRUSH>(::GetStockObject(WHITE_BRUSH)); ::FillRect(memDC, clientRect, bkgdBrush); HFONT font = ::CreateFont(LineHeight - 2, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH, _T("新宋体")); HGDIOBJ oldFont = ::SelectObject(memDC, font); DEBUG_INFO(_T("重绘")); CPoint scrollPosition = GetScrollPosition(); DEBUG_INFO(_T("滚动条位置:") << scrollPosition.x << ", " << scrollPosition.y); // 顶部可以显示半行 int yLogLineStart = scrollPosition.y % LineHeight == 0 ? 0 : scrollPosition.y % LineHeight - LineHeight; unsigned beginLine = scrollPosition.y / LineHeight; // +1是为了底部能显示半行 unsigned endLine = (scrollPosition.y + clientRect.Height()) / LineHeight + 1; endLine = min(endLine, GetDocument()->logQuery->getCurQueryResult()->getCount()); DEBUG_INFO(_T("行号区间:") << beginLine << ", " << endLine); vector<LogItem*> vecLines = GetDocument()->logQuery->getCurQueryResult()->getRange(beginLine, endLine); for (unsigned i = 0; i < vecLines.size(); i++) { LogItem* item = vecLines[i]; CRect rect = clientRect; rect.top = yLogLineStart + i * LineHeight; rect.bottom = rect.top + LineHeight; LogPainterFactory::GetInstance()->GetSingleLinePainter()->Draw(memDC, rect, *item); } ::BitBlt(pDC->GetSafeHdc(), scrollPosition.x, scrollPosition.y, clientRect.Width(), clientRect.Height(), memDC, 0, 0, SRCCOPY); ::SelectObject(memDC, oldFont); ::DeleteObject(font); ::SelectObject(memDC, oldBmp); ::DeleteObject(memBmp); ::DeleteDC(memDC); } void CLogMainView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); GetDocument()->logQuery->registerObserver(this); UpdateScroll(); SetFocus(); } void CLogMainView::PostNcDestroy() { GetDocument()->logQuery->unregisterObserver(this); __super::PostNcDestroy(); } void CLogMainView::UpdateScroll() { CRect clientRect; GetClientRect(clientRect); CSize totalSize; totalSize.cx = 0; //clientRect.Width(); // 加1是为了最后一行一定可见 GetDocument()->length = totalSize.cy = (GetDocument()->logQuery->getCurQueryResult()->getCount() + 1) * LineHeight; #define LOGCC_WINUI_CUSTOMIZE_PAGE_SIZE_LINE_SIZE #ifdef LOGCC_WINUI_CUSTOMIZE_PAGE_SIZE_LINE_SIZE CSize pageSize(clientRect.Width(), clientRect.Height() / LineHeight * LineHeight); CSize lineSize(clientRect.Width(), LineHeight); SetScrollSizes(MM_TEXT, totalSize, pageSize, lineSize); #else SetScrollSizes(MM_TEXT, totalSize); #endif #define LOGCC_WINUI_SCROLL_TO_END_ON_UPDATE #ifdef LOGCC_WINUI_SCROLL_TO_END_ON_UPDATE int y = totalSize.cy - clientRect.Height(); ScrollToPosition(CPoint(0, max(y, 0))); #endif } void CLogMainView::onGeneralDataChanged() { Invalidate(); } void CLogMainView::onQueryResultChanged() { UpdateScroll(); Invalidate(); } void CLogMainView::onScrollPositionChanged(int yPosition) { CPoint position = GetScrollPosition(); position.y = yPosition; ScrollToPosition(position); } #ifdef _DEBUG CLogCCDoc* CLogMainView::GetDocument() const // 非调试版本是内联的 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CLogCCDoc))); return (CLogCCDoc*)m_pDocument; } #endif //_DEBUG // CLogMainView 消息处理程序 BOOL CLogMainView::OnEraseBkgnd(CDC* pDC) { #ifdef LOGCC_WINUI_USE_DEFAULT_ERASE_BACKGROUND return CScrollView::OnEraseBkgnd(pDC); #else return TRUE; #endif } void CLogMainView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { if (nSBCode == SB_ENDSCROLL) { Invalidate(); } CScrollView::OnVScroll(nSBCode, nPos, pScrollBar); } BOOL CLogMainView::PreTranslateMessage(MSG* pMsg) { // 更新UI数据到ViewData CPoint scrollPos = GetScrollPosition(); GetDocument()->yScrollPos = scrollPos.y; GetDocument()->lineHeight = LineHeight; GetClientRect(GetDocument()->clientRect); return __super::PreTranslateMessage(pMsg); } void CLogMainView::OnMouseMove(UINT nFlags, CPoint point) { if (GetForegroundWindow() == AfxGetMainWnd()) { SetFocus(); } __super::OnMouseMove(nFlags, point); } <|endoftext|>
<commit_before>/* * Copyright 2013 Matthew Harvey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gui/account_list_ctrl.hpp" #include "app.hpp" #include "account.hpp" #include "account_table_iterator.hpp" #include "account_type.hpp" #include "finformat.hpp" #include "dcm_database_connection.hpp" #include "string_flags.hpp" #include "gui/account_dialog.hpp" #include "gui/locale.hpp" #include "gui/persistent_object_event.hpp" #include "gui/top_panel.hpp" #include <jewel/assert.hpp> #include <sqloxx/handle.hpp> #include <wx/event.h> #include <wx/listctrl.h> #include <wx/notebook.h> #include <wx/string.h> #include <algorithm> #include <set> using sqloxx::Handle; using std::is_signed; using std::max; using std::set; namespace dcm { namespace gui { BEGIN_EVENT_TABLE(AccountListCtrl, wxListCtrl) EVT_LIST_ITEM_ACTIVATED ( wxID_ANY, AccountListCtrl::on_item_activated ) END_EVENT_TABLE() AccountListCtrl::AccountListCtrl ( wxWindow* p_parent, DcmDatabaseConnection& p_database_connection, AccountSuperType p_account_super_type ): wxListCtrl ( p_parent, wxID_ANY, wxDefaultPosition, wxSize ( p_parent->GetClientSize().GetX() / 4, p_parent->GetClientSize().GetY() ), wxLC_REPORT | wxLC_SINGLE_SEL | wxFULL_REPAINT_ON_RESIZE ), m_show_hidden(false), m_account_super_type(p_account_super_type), m_database_connection(p_database_connection) { update(); } AccountListCtrl::~AccountListCtrl() { } set<sqloxx::Id> AccountListCtrl::selected_accounts() const { set<sqloxx::Id> ret; size_t i = 0; size_t const lim = GetItemCount(); for ( ; i != lim; ++i) { if (GetItemState(i, wxLIST_STATE_SELECTED)) { Handle<Account> const account ( m_database_connection, GetItemData(i) ); JEWEL_ASSERT (account->has_id()); ret.insert(account->id()); } } return ret; } void AccountListCtrl::on_item_activated(wxListEvent& event) { JEWEL_LOG_TRACE(); sqloxx::Id const account_id = GetItemData(event.GetIndex()); // Fire an Account editing request. This will be handled higher up // the window hierarchy. PersistentObjectEvent::fire ( this, DCM_ACCOUNT_EDITING_EVENT, account_id ); JEWEL_LOG_TRACE(); return; } void AccountListCtrl::update() { // Remember which rows are selected currently auto const selected = selected_accounts(); // Remember scrolled position auto const item_count = GetItemCount(); auto const top_item = GetTopItem(); auto const last_item = item_count - 1; auto const last_position = top_item + GetCountPerPage(); auto const bottom_item = ((last_position < last_item) ? last_position : last_item); // Now (re)draw ClearAll(); InsertColumn ( s_name_col, account_concept_name ( m_account_super_type, AccountPhraseFlags().set(string_flags::capitalize) ), wxLIST_FORMAT_LEFT ); InsertColumn ( s_balance_col, wxString("Balance"), wxLIST_FORMAT_RIGHT ); if (showing_daily_budget()) { InsertColumn(s_budget_col, "Daily top-up", wxLIST_FORMAT_RIGHT); } long i = 0; // because wxWidgets uses long AccountTableIterator it = make_type_name_ordered_account_table_iterator ( m_database_connection ); AccountTableIterator const end; for ( ; it != end; ++it) { Handle<Account> const& account = *it; if ( (account->account_super_type() == m_account_super_type) && (m_show_hidden || (account->visibility() == Visibility::visible)) ) { // Insert item, with string for Column 0 InsertItem(i, account->name()); JEWEL_ASSERT (account->has_id()); auto const id = account->id(); static_assert ( (sizeof(id) <= sizeof(long)) && is_signed<decltype(id)>::value && is_signed<long>::value, "Object Id is too wide to be safely passed to " "SetItemData." ); SetItemData(i, id); // Insert the balance string SetItem ( i, s_balance_col, finformat_wx(account->friendly_balance(), locale()) ); if (showing_daily_budget()) { // Insert budget string SetItem ( i, s_budget_col, finformat_wx(account->budget(), locale()) ); } ++i; } } // Reinstate the selections we remembered for (size_t j = 0, lim = GetItemCount(); j != lim; ++j) { Handle<Account> const account ( m_database_connection, GetItemData(j) ); JEWEL_ASSERT (account->has_id()); if (selected.find(account->id()) != selected.end()) { SetItemState ( j, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED ); } } // Configure column widths SetColumnWidth(s_name_col, wxLIST_AUTOSIZE_USEHEADER); SetColumnWidth(s_name_col, max(GetColumnWidth(s_name_col), 200)); SetColumnWidth(s_balance_col, wxLIST_AUTOSIZE); SetColumnWidth(s_balance_col, max(GetColumnWidth(s_balance_col), 90)); if (showing_daily_budget()) { SetColumnWidth(s_budget_col, wxLIST_AUTOSIZE); SetColumnWidth(s_budget_col, max(GetColumnWidth(s_budget_col), 90)); } // Reinstate scrolled position if (bottom_item > 0) EnsureVisible(bottom_item - 1); Layout(); return; } bool AccountListCtrl::showing_daily_budget() const { return m_account_super_type == AccountSuperType::pl; } Handle<Account> AccountListCtrl::default_account() const { Handle<Account> ret; if (GetItemCount() != 0) { // Return the first Account that is actually showing in the // control. JEWEL_ASSERT (GetItemCount() > 0); ret = Handle<Account>(m_database_connection, GetItemData(GetTopItem())); } else { // Return the an Account of the AccountSuperType of this control, // even though not showing in the control (because hidden). AccountTableIterator it = make_type_name_ordered_account_table_iterator ( m_database_connection ); AccountTableIterator const end; for ( ; it != end; ++it) { Handle<Account> const account = *it; if (account->account_super_type() == m_account_super_type) { ret = account; break; } } } return ret; } void AccountListCtrl::select_only(Handle<Account> const& p_account) { JEWEL_ASSERT (p_account->has_id()); // precondition size_t const sz = GetItemCount(); for (size_t i = 0; i != sz; ++i) { Handle<Account> const account(m_database_connection, GetItemData(i)); long const filter = (wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED); long const flags = ((account == p_account)? filter: 0); SetItemState(i, flags, filter); } return; } bool AccountListCtrl::toggle_showing_hidden() { m_show_hidden = !m_show_hidden; update(); return m_show_hidden; } } // namespace gui } // namespace dcm <commit_msg>Tweak scroll position logic in AccountListCtrl.<commit_after>/* * Copyright 2013 Matthew Harvey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gui/account_list_ctrl.hpp" #include "app.hpp" #include "account.hpp" #include "account_table_iterator.hpp" #include "account_type.hpp" #include "finformat.hpp" #include "dcm_database_connection.hpp" #include "string_flags.hpp" #include "gui/account_dialog.hpp" #include "gui/locale.hpp" #include "gui/persistent_object_event.hpp" #include "gui/top_panel.hpp" #include <jewel/assert.hpp> #include <sqloxx/handle.hpp> #include <wx/event.h> #include <wx/listctrl.h> #include <wx/notebook.h> #include <wx/string.h> #include <algorithm> #include <set> using sqloxx::Handle; using std::is_signed; using std::max; using std::set; namespace dcm { namespace gui { BEGIN_EVENT_TABLE(AccountListCtrl, wxListCtrl) EVT_LIST_ITEM_ACTIVATED ( wxID_ANY, AccountListCtrl::on_item_activated ) END_EVENT_TABLE() AccountListCtrl::AccountListCtrl ( wxWindow* p_parent, DcmDatabaseConnection& p_database_connection, AccountSuperType p_account_super_type ): wxListCtrl ( p_parent, wxID_ANY, wxDefaultPosition, wxSize ( p_parent->GetClientSize().GetX() / 4, p_parent->GetClientSize().GetY() ), wxLC_REPORT | wxLC_SINGLE_SEL | wxFULL_REPAINT_ON_RESIZE ), m_show_hidden(false), m_account_super_type(p_account_super_type), m_database_connection(p_database_connection) { update(); } AccountListCtrl::~AccountListCtrl() { } set<sqloxx::Id> AccountListCtrl::selected_accounts() const { set<sqloxx::Id> ret; size_t i = 0; size_t const lim = GetItemCount(); for ( ; i != lim; ++i) { if (GetItemState(i, wxLIST_STATE_SELECTED)) { Handle<Account> const account ( m_database_connection, GetItemData(i) ); JEWEL_ASSERT (account->has_id()); ret.insert(account->id()); } } return ret; } void AccountListCtrl::on_item_activated(wxListEvent& event) { JEWEL_LOG_TRACE(); sqloxx::Id const account_id = GetItemData(event.GetIndex()); // Fire an Account editing request. This will be handled higher up // the window hierarchy. PersistentObjectEvent::fire ( this, DCM_ACCOUNT_EDITING_EVENT, account_id ); JEWEL_LOG_TRACE(); return; } void AccountListCtrl::update() { // Remember which rows are selected currently auto const selected = selected_accounts(); // Remember scrolled position auto const item_count = GetItemCount(); auto const top_item = GetTopItem(); auto const last_item = item_count - 1; auto const last_position = top_item + GetCountPerPage(); long bottom_item; if (last_position < last_item) { bottom_item = last_position - 1; } else if (last_position == last_item) { bottom_item = last_item - 1; } else { bottom_item = last_item; } // Now (re)draw ClearAll(); InsertColumn ( s_name_col, account_concept_name ( m_account_super_type, AccountPhraseFlags().set(string_flags::capitalize) ), wxLIST_FORMAT_LEFT ); InsertColumn ( s_balance_col, wxString("Balance"), wxLIST_FORMAT_RIGHT ); if (showing_daily_budget()) { InsertColumn(s_budget_col, "Daily top-up", wxLIST_FORMAT_RIGHT); } long i = 0; // because wxWidgets uses long AccountTableIterator it = make_type_name_ordered_account_table_iterator ( m_database_connection ); AccountTableIterator const end; for ( ; it != end; ++it) { Handle<Account> const& account = *it; if ( (account->account_super_type() == m_account_super_type) && (m_show_hidden || (account->visibility() == Visibility::visible)) ) { // Insert item, with string for Column 0 InsertItem(i, account->name()); JEWEL_ASSERT (account->has_id()); auto const id = account->id(); static_assert ( (sizeof(id) <= sizeof(long)) && is_signed<decltype(id)>::value && is_signed<long>::value, "Object Id is too wide to be safely passed to " "SetItemData." ); SetItemData(i, id); // Insert the balance string SetItem ( i, s_balance_col, finformat_wx(account->friendly_balance(), locale()) ); if (showing_daily_budget()) { // Insert budget string SetItem ( i, s_budget_col, finformat_wx(account->budget(), locale()) ); } ++i; } } // Reinstate the selections we remembered for (size_t j = 0, lim = GetItemCount(); j != lim; ++j) { Handle<Account> const account ( m_database_connection, GetItemData(j) ); JEWEL_ASSERT (account->has_id()); if (selected.find(account->id()) != selected.end()) { SetItemState ( j, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED ); } } // Configure column widths SetColumnWidth(s_name_col, wxLIST_AUTOSIZE_USEHEADER); SetColumnWidth(s_name_col, max(GetColumnWidth(s_name_col), 200)); SetColumnWidth(s_balance_col, wxLIST_AUTOSIZE); SetColumnWidth(s_balance_col, max(GetColumnWidth(s_balance_col), 90)); if (showing_daily_budget()) { SetColumnWidth(s_budget_col, wxLIST_AUTOSIZE); SetColumnWidth(s_budget_col, max(GetColumnWidth(s_budget_col), 90)); } // Reinstate scrolled position if (bottom_item >= 0) EnsureVisible(bottom_item); Layout(); return; } bool AccountListCtrl::showing_daily_budget() const { return m_account_super_type == AccountSuperType::pl; } Handle<Account> AccountListCtrl::default_account() const { Handle<Account> ret; if (GetItemCount() != 0) { // Return the first Account that is actually showing in the // control. JEWEL_ASSERT (GetItemCount() > 0); ret = Handle<Account>(m_database_connection, GetItemData(GetTopItem())); } else { // Return the an Account of the AccountSuperType of this control, // even though not showing in the control (because hidden). AccountTableIterator it = make_type_name_ordered_account_table_iterator ( m_database_connection ); AccountTableIterator const end; for ( ; it != end; ++it) { Handle<Account> const account = *it; if (account->account_super_type() == m_account_super_type) { ret = account; break; } } } return ret; } void AccountListCtrl::select_only(Handle<Account> const& p_account) { JEWEL_ASSERT (p_account->has_id()); // precondition size_t const sz = GetItemCount(); for (size_t i = 0; i != sz; ++i) { Handle<Account> const account(m_database_connection, GetItemData(i)); long const filter = (wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED); long const flags = ((account == p_account)? filter: 0); SetItemState(i, flags, filter); } return; } bool AccountListCtrl::toggle_showing_hidden() { m_show_hidden = !m_show_hidden; update(); return m_show_hidden; } } // namespace gui } // namespace dcm <|endoftext|>
<commit_before>// // PROJECT: Aspia // FILE: category/category_logical_drive.cc // LICENSE: Mozilla Public License Version 2.0 // PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru) // #include "base/files/logical_drive_enumerator.h" #include "base/strings/unicode.h" #include "category/category_logical_drive.h" #include "category/category_logical_drive.pb.h" #include "ui/resource.h" namespace aspia { namespace { const char* DriveTypeToString(proto::LogicalDrive::DriveType value) { switch (value) { case proto::LogicalDrive::DRIVE_TYPE_LOCAL: return "Local Disk"; case proto::LogicalDrive::DRIVE_TYPE_REMOVABLE: return "Removable Disk"; case proto::LogicalDrive::DRIVE_TYPE_REMOTE: return "Remote Disk"; case proto::LogicalDrive::DRIVE_TYPE_CDROM: return "Optical Disk"; case proto::LogicalDrive::DRIVE_TYPE_RAM: return "RAM Disk"; default: return "Unknown"; } } } // namespace CategoryLogicalDrive::CategoryLogicalDrive() : CategoryInfo(Type::INFO_LIST) { // Nothing } const char* CategoryLogicalDrive::Name() const { return "Logical Drives"; } Category::IconId CategoryLogicalDrive::Icon() const { return IDI_DRIVE; } const char* CategoryLogicalDrive::Guid() const { return "{8F6D959F-C9E1-41E4-9D97-A12F650B489F}"; } void CategoryLogicalDrive::Parse(Table& table, const std::string& data) { proto::LogicalDrive message; if (!message.ParseFromString(data)) return; table.AddColumns(ColumnList::Create() .AddColumn("Drive", 50) .AddColumn("Label", 80) .AddColumn("Drive Type", 80) .AddColumn("File System", 80) .AddColumn("Total Size", 80) .AddColumn("Used Space", 80) .AddColumn("Free Space", 80) .AddColumn("% Free", 50) .AddColumn("Volume Serial", 100)); for (int index = 0; index < message.item_size(); ++index) { const proto::LogicalDrive::Item& item = message.item(index); Row row = table.AddRow(); row.AddValue(Value::String(item.drive_letter())); row.AddValue(Value::String(item.drive_label())); row.AddValue(Value::String(DriveTypeToString(item.drive_type()))); row.AddValue(Value::String(item.file_system())); row.AddValue(Value::MemorySize(item.total_size())); uint64_t used_space = item.total_size() - item.free_space(); row.AddValue(Value::MemorySize(used_space)); row.AddValue(Value::MemorySize(item.free_space())); uint64_t free_percent = (item.free_space() * 100ULL) / item.total_size(); row.AddValue(Value::Number(free_percent, "%")); row.AddValue(Value::String(item.volume_serial())); } } std::string CategoryLogicalDrive::Serialize() { proto::LogicalDrive message; LogicalDriveEnumerator enumerator; for (;;) { FilePath path = enumerator.Next(); if (path.empty()) break; LogicalDriveEnumerator::DriveInfo drive_info = enumerator.GetInfo(); proto::LogicalDrive::Item* item = message.add_item(); item->set_drive_letter(drive_info.Path().u8string()); item->set_drive_label(UTF8fromUNICODE(drive_info.VolumeName())); switch (drive_info.Type()) { case LogicalDriveEnumerator::DriveInfo::DriveType::FIXED: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_LOCAL); break; case LogicalDriveEnumerator::DriveInfo::DriveType::REMOVABLE: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_REMOVABLE); break; case LogicalDriveEnumerator::DriveInfo::DriveType::REMOTE: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_REMOTE); break; case LogicalDriveEnumerator::DriveInfo::DriveType::CDROM: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_CDROM); break; case LogicalDriveEnumerator::DriveInfo::DriveType::RAM: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_RAM); break; default: break; } item->set_file_system(UTF8fromUNICODE(drive_info.FileSystem())); item->set_total_size(drive_info.TotalSpace()); item->set_free_space(drive_info.FreeSpace()); item->set_volume_serial(drive_info.VolumeSerial()); } return message.SerializeAsString(); } } // namespace aspia <commit_msg>- Fixed a potential division by zero.<commit_after>// // PROJECT: Aspia // FILE: category/category_logical_drive.cc // LICENSE: Mozilla Public License Version 2.0 // PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru) // #include "base/files/logical_drive_enumerator.h" #include "base/strings/unicode.h" #include "category/category_logical_drive.h" #include "category/category_logical_drive.pb.h" #include "ui/resource.h" namespace aspia { namespace { const char* DriveTypeToString(proto::LogicalDrive::DriveType value) { switch (value) { case proto::LogicalDrive::DRIVE_TYPE_LOCAL: return "Local Disk"; case proto::LogicalDrive::DRIVE_TYPE_REMOVABLE: return "Removable Disk"; case proto::LogicalDrive::DRIVE_TYPE_REMOTE: return "Remote Disk"; case proto::LogicalDrive::DRIVE_TYPE_CDROM: return "Optical Disk"; case proto::LogicalDrive::DRIVE_TYPE_RAM: return "RAM Disk"; default: return "Unknown"; } } } // namespace CategoryLogicalDrive::CategoryLogicalDrive() : CategoryInfo(Type::INFO_LIST) { // Nothing } const char* CategoryLogicalDrive::Name() const { return "Logical Drives"; } Category::IconId CategoryLogicalDrive::Icon() const { return IDI_DRIVE; } const char* CategoryLogicalDrive::Guid() const { return "{8F6D959F-C9E1-41E4-9D97-A12F650B489F}"; } void CategoryLogicalDrive::Parse(Table& table, const std::string& data) { proto::LogicalDrive message; if (!message.ParseFromString(data)) return; table.AddColumns(ColumnList::Create() .AddColumn("Drive", 50) .AddColumn("Label", 80) .AddColumn("Drive Type", 80) .AddColumn("File System", 80) .AddColumn("Total Size", 80) .AddColumn("Used Space", 80) .AddColumn("Free Space", 80) .AddColumn("% Free", 50) .AddColumn("Volume Serial", 100)); for (int index = 0; index < message.item_size(); ++index) { const proto::LogicalDrive::Item& item = message.item(index); Row row = table.AddRow(); row.AddValue(Value::String(item.drive_letter())); row.AddValue(Value::String(item.drive_label())); row.AddValue(Value::String(DriveTypeToString(item.drive_type()))); row.AddValue(Value::String(item.file_system())); row.AddValue(Value::MemorySize(item.total_size())); uint64_t used_space = item.total_size() - item.free_space(); row.AddValue(Value::MemorySize(used_space)); row.AddValue(Value::MemorySize(item.free_space())); uint64_t free_percent = (item.total_size() != 0) ? ((item.free_space() * 100ULL) / item.total_size()) : 0; row.AddValue(Value::Number(free_percent, "%")); row.AddValue(Value::String(item.volume_serial())); } } std::string CategoryLogicalDrive::Serialize() { proto::LogicalDrive message; LogicalDriveEnumerator enumerator; for (;;) { FilePath path = enumerator.Next(); if (path.empty()) break; LogicalDriveEnumerator::DriveInfo drive_info = enumerator.GetInfo(); proto::LogicalDrive::Item* item = message.add_item(); item->set_drive_letter(drive_info.Path().u8string()); item->set_drive_label(UTF8fromUNICODE(drive_info.VolumeName())); switch (drive_info.Type()) { case LogicalDriveEnumerator::DriveInfo::DriveType::FIXED: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_LOCAL); break; case LogicalDriveEnumerator::DriveInfo::DriveType::REMOVABLE: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_REMOVABLE); break; case LogicalDriveEnumerator::DriveInfo::DriveType::REMOTE: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_REMOTE); break; case LogicalDriveEnumerator::DriveInfo::DriveType::CDROM: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_CDROM); break; case LogicalDriveEnumerator::DriveInfo::DriveType::RAM: item->set_drive_type(proto::LogicalDrive::DRIVE_TYPE_RAM); break; default: break; } item->set_file_system(UTF8fromUNICODE(drive_info.FileSystem())); item->set_total_size(drive_info.TotalSpace()); item->set_free_space(drive_info.FreeSpace()); item->set_volume_serial(drive_info.VolumeSerial()); } return message.SerializeAsString(); } } // namespace aspia <|endoftext|>
<commit_before>/// /// @file test.cpp /// @brief bool test_ParallelPrimeSieve(); runs sieving tests to /// ensure that ParallelPrimeSieve (and PrimeSieve) objects /// produce correct results. /// /// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/soe/ParallelPrimeSieve.h> #include <iostream> #include <iomanip> #include <exception> #include <stdexcept> #include <algorithm> #include <cstdlib> #include <ctime> #include <stdint.h> using namespace std; namespace { /// Correct values to compare with test results const unsigned int primeCounts[19] = { 4, // pi(10^1) 25, // pi(10^2) 168, // pi(10^3) 1229, // pi(10^4) 9592, // pi(10^5) 78498, // pi(10^6) 664579, // pi(10^7) 5761455, // pi(10^8) 50847534, // pi(10^9) 455052511, // pi(10^10) 155428406, // pi[10^12, 10^12+2^32] 143482916, // pi[10^13, 10^13+2^32] 133235063, // pi[10^14, 10^14+2^32] 124350420, // pi[10^15, 10^15+2^32] 116578809, // pi[10^16, 10^16+2^32] 109726486, // pi[10^17, 10^17+2^32] 103626726, // pi[10^18, 10^18+2^32] 98169972, // pi[10^19, 10^19+2^32] 2895317534U // pi[10^15, 10^15+10^11] }; /// Keeps the memory usage below 1GB const int maxThreads[8] = { 32, 32, 32, 32, 32, 8, 4, 1 }; double seconds = 0.0; uint64_t ipow(uint64_t x, int n) { uint64_t result = 1; while (n != 0) { if ((n & 1) != 0) { result *= x; n -= 1; } x *= x; n /= 2; } return result; } /// Get a random 64-bit integer < limit uint64_t getRand64(uint64_t limit) { uint64_t rand64 = 0; for (int i = 0; i < 4; i++) rand64 = rand() % (1 << 16) + (rand64 << i * 16); return rand64 % limit; } void check(bool isCorrect) { cout << (isCorrect ? "OK" : "ERROR") << endl; if (!isCorrect) throw runtime_error("test failed!"); } /// Count the primes up to 10^10 void testPix() { cout << "pi(x) : Prime-counting function test" << endl; ParallelPrimeSieve pps; pps.setStart(0); pps.setStop(0); uint64_t primeCount = 0; // pi(x) with x = 10^i for i = 1 to 10 for (int i = 1; i <= 10; i++) { primeCount += pps.countPrimes(pps.getStop() + 1, ipow(10, i)); seconds += pps.getSeconds(); cout << "pi(10^" << i << (i < 10 ? ") = " : ") = ") << setw(12) << primeCount; check(primeCount == primeCounts[i - 1]); } cout << endl; } /// Count the primes within [10^i, 10^i+2^32] for i = 12 to 19 void testBigPrimes() { ParallelPrimeSieve pps; pps.setFlags(pps.COUNT_PRIMES | pps.PRINT_STATUS); for (int i = 12; i <= 19; i++) { cout << "Sieving the primes within [10^" << i << ", 10^" << i << "+2^32]" << endl; pps.setStart(ipow(10, i)); pps.setStop(pps.getStart() + ipow(2, 32)); pps.setNumThreads(min(pps.getNumThreads(), maxThreads[i - 12])); pps.sieve(); seconds += pps.getSeconds(); cout << "\rPrime count: " << setw(11) << pps.getPrimeCount(); check(pps.getPrimeCount() == primeCounts[i - 2]); } cout << endl; } /// Sieve about 200 small random intervals until the interval /// [10^15, 10^15+10^11] has been completed. /// void testRandomIntervals() { cout << "Sieving the primes within [10^15, 10^15+10^11] randomly" << endl; uint64_t maxInterval = ipow(10, 9); uint64_t lowerBound = ipow(10, 15); uint64_t upperBound = lowerBound + ipow(10, 11); uint64_t primeCount = 0; srand(static_cast<unsigned int>(time(0))); ParallelPrimeSieve pps; pps.setStart(lowerBound - 1); pps.setStop(lowerBound - 1); while (pps.getStop() < upperBound) { pps.setStart(pps.getStop() + 1); pps.setStop(min(pps.getStart() + getRand64(maxInterval), upperBound)); pps.setSieveSize(1 << (rand() % 12)); pps.sieve(); primeCount += pps.getPrimeCount(); seconds += pps.getSeconds(); cout << "\rRemaining chunk: " << "\rRemaining chunk: " << upperBound - pps.getStop() << flush; } cout << endl << "Prime count: " << setw(11) << primeCount; check(primeCount == primeCounts[18]); cout << endl; } } // end namespace /// Run various sieving tests to ensure that ParallelPrimeSieve /// (and PrimeSieve) objects produce correct results. /// The tests use up to 1 GB of memory and take about 3 minutes to /// complete on a dual core CPU from 2011. /// @return true If no error occurred else false. /// bool test_ParallelPrimeSieve() { cout << left; try { testPix(); testBigPrimes(); testRandomIntervals(); } catch (exception& e) { cerr << endl << "Error: " << e.what() << endl; return false; } cout << "Time elapsed: " << seconds << " sec" << endl << "All tests passed successfully!" << endl; return true; } <commit_msg>Added main() function.<commit_after>/// /// @file test.cpp /// @brief bool test_ParallelPrimeSieve(); runs sieving tests to /// ensure that ParallelPrimeSieve (and PrimeSieve) objects /// produce correct results. /// /// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/soe/ParallelPrimeSieve.h> #include <iostream> #include <iomanip> #include <exception> #include <stdexcept> #include <algorithm> #include <cstdlib> #include <ctime> #include <stdint.h> using namespace std; namespace { /// Correct values to compare with test results const unsigned int primeCounts[19] = { 4, // pi(10^1) 25, // pi(10^2) 168, // pi(10^3) 1229, // pi(10^4) 9592, // pi(10^5) 78498, // pi(10^6) 664579, // pi(10^7) 5761455, // pi(10^8) 50847534, // pi(10^9) 455052511, // pi(10^10) 155428406, // pi[10^12, 10^12+2^32] 143482916, // pi[10^13, 10^13+2^32] 133235063, // pi[10^14, 10^14+2^32] 124350420, // pi[10^15, 10^15+2^32] 116578809, // pi[10^16, 10^16+2^32] 109726486, // pi[10^17, 10^17+2^32] 103626726, // pi[10^18, 10^18+2^32] 98169972, // pi[10^19, 10^19+2^32] 2895317534U // pi[10^15, 10^15+10^11] }; /// Keeps the memory usage below 1GB const int maxThreads[8] = { 32, 32, 32, 32, 32, 8, 4, 1 }; double seconds = 0.0; uint64_t ipow(uint64_t x, int n) { uint64_t result = 1; while (n != 0) { if ((n & 1) != 0) { result *= x; n -= 1; } x *= x; n /= 2; } return result; } /// Get a random 64-bit integer < limit uint64_t getRand64(uint64_t limit) { uint64_t rand64 = 0; for (int i = 0; i < 4; i++) rand64 = rand() % (1 << 16) + (rand64 << i * 16); return rand64 % limit; } void check(bool isCorrect) { cout << (isCorrect ? "OK" : "ERROR") << endl; if (!isCorrect) throw runtime_error("test failed!"); } /// Count the primes up to 10^10 void testPix() { cout << "pi(x) : Prime-counting function test" << endl; ParallelPrimeSieve pps; pps.setStart(0); pps.setStop(0); uint64_t primeCount = 0; // pi(x) with x = 10^i for i = 1 to 10 for (int i = 1; i <= 10; i++) { primeCount += pps.countPrimes(pps.getStop() + 1, ipow(10, i)); seconds += pps.getSeconds(); cout << "pi(10^" << i << (i < 10 ? ") = " : ") = ") << setw(12) << primeCount; check(primeCount == primeCounts[i - 1]); } cout << endl; } /// Count the primes within [10^i, 10^i+2^32] for i = 12 to 19 void testBigPrimes() { ParallelPrimeSieve pps; pps.setFlags(pps.COUNT_PRIMES | pps.PRINT_STATUS); for (int i = 12; i <= 19; i++) { cout << "Sieving the primes within [10^" << i << ", 10^" << i << "+2^32]" << endl; pps.setStart(ipow(10, i)); pps.setStop(pps.getStart() + ipow(2, 32)); pps.setNumThreads(min(pps.getNumThreads(), maxThreads[i - 12])); pps.sieve(); seconds += pps.getSeconds(); cout << "\rPrime count: " << setw(11) << pps.getPrimeCount(); check(pps.getPrimeCount() == primeCounts[i - 2]); } cout << endl; } /// Sieve about 200 small random intervals until the interval /// [10^15, 10^15+10^11] has been completed. /// void testRandomIntervals() { cout << "Sieving the primes within [10^15, 10^15+10^11] randomly" << endl; uint64_t maxInterval = ipow(10, 9); uint64_t lowerBound = ipow(10, 15); uint64_t upperBound = lowerBound + ipow(10, 11); uint64_t primeCount = 0; srand(static_cast<unsigned int>(time(0))); ParallelPrimeSieve pps; pps.setStart(lowerBound - 1); pps.setStop(lowerBound - 1); while (pps.getStop() < upperBound) { pps.setStart(pps.getStop() + 1); pps.setStop(min(pps.getStart() + getRand64(maxInterval), upperBound)); pps.setSieveSize(1 << (rand() % 12)); pps.sieve(); primeCount += pps.getPrimeCount(); seconds += pps.getSeconds(); cout << "\rRemaining chunk: " << "\rRemaining chunk: " << upperBound - pps.getStop() << flush; } cout << endl << "Prime count: " << setw(11) << primeCount; check(primeCount == primeCounts[18]); cout << endl; } } // end namespace /// Run various sieving tests to ensure that ParallelPrimeSieve /// (and PrimeSieve) objects produce correct results. /// The tests use up to 1 GB of memory and take about 3 minutes to /// complete on a dual core CPU from 2011. /// @return true If no error occurred else false. /// bool test_ParallelPrimeSieve() { cout << left; try { testPix(); testBigPrimes(); testRandomIntervals(); } catch (exception& e) { cerr << endl << "Error: " << e.what() << endl; return false; } cout << "Time elapsed: " << seconds << " sec" << endl << "All tests passed successfully!" << endl; return true; } #ifdef STANDALONE int main() { return (test_ParallelPrimeSieve() == true) ? 0 : 1; } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2007-2008 The Florida State University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_REGISTERS_HH__ #define __ARCH_ARM_REGISTERS_HH__ #include "arch/arm/max_inst_regs.hh" #include "arch/arm/intregs.hh" #include "arch/arm/miscregs.hh" namespace ArmISA { using ArmISAInst::MaxInstSrcRegs; using ArmISAInst::MaxInstDestRegs; typedef uint16_t RegIndex; typedef uint64_t IntReg; // floating point register file entry type typedef uint32_t FloatRegBits; typedef float FloatReg; // cop-0/cop-1 system control register typedef uint64_t MiscReg; // Constants Related to the number of registers const int NumIntArchRegs = NUM_ARCH_INTREGS; // The number of single precision floating point registers const int NumFloatArchRegs = 64; const int NumFloatSpecialRegs = 8; const int NumIntRegs = NUM_INTREGS; const int NumFloatRegs = NumFloatArchRegs + NumFloatSpecialRegs; const int NumMiscRegs = NUM_MISCREGS; // semantically meaningful register indices const int ReturnValueReg = 0; const int ReturnValueReg1 = 1; const int ReturnValueReg2 = 2; const int ArgumentReg0 = 0; const int ArgumentReg1 = 1; const int ArgumentReg2 = 2; const int ArgumentReg3 = 3; const int FramePointerReg = 11; const int StackPointerReg = INTREG_SP; const int ReturnAddressReg = INTREG_LR; const int PCReg = INTREG_PC; const int ZeroReg = INTREG_ZERO; const int SyscallNumReg = ReturnValueReg; const int SyscallPseudoReturnReg = ReturnValueReg; const int SyscallSuccessReg = ReturnValueReg; // These help enumerate all the registers for dependence tracking. const int FP_Base_DepTag = NumIntRegs * (MODE_MAXMODE + 1); const int Ctrl_Base_DepTag = FP_Base_DepTag + NumFloatRegs; typedef union { IntReg intreg; FloatReg fpreg; MiscReg ctrlreg; } AnyReg; enum FPControlRegNums { FIR = NumFloatArchRegs, FCCR, FEXR, FENR, FCSR }; enum FCSRBits { Inexact = 1, Underflow, Overflow, DivideByZero, Invalid, Unimplemented }; enum FCSRFields { Flag_Field = 1, Enable_Field = 6, Cause_Field = 11 }; } // namespace ArmISA #endif <commit_msg>ARM: Eliminate some unused enums.<commit_after>/* * Copyright (c) 2007-2008 The Florida State University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_REGISTERS_HH__ #define __ARCH_ARM_REGISTERS_HH__ #include "arch/arm/max_inst_regs.hh" #include "arch/arm/intregs.hh" #include "arch/arm/miscregs.hh" namespace ArmISA { using ArmISAInst::MaxInstSrcRegs; using ArmISAInst::MaxInstDestRegs; typedef uint16_t RegIndex; typedef uint64_t IntReg; // floating point register file entry type typedef uint32_t FloatRegBits; typedef float FloatReg; // cop-0/cop-1 system control register typedef uint64_t MiscReg; // Constants Related to the number of registers const int NumIntArchRegs = NUM_ARCH_INTREGS; // The number of single precision floating point registers const int NumFloatArchRegs = 64; const int NumFloatSpecialRegs = 8; const int NumIntRegs = NUM_INTREGS; const int NumFloatRegs = NumFloatArchRegs + NumFloatSpecialRegs; const int NumMiscRegs = NUM_MISCREGS; // semantically meaningful register indices const int ReturnValueReg = 0; const int ReturnValueReg1 = 1; const int ReturnValueReg2 = 2; const int ArgumentReg0 = 0; const int ArgumentReg1 = 1; const int ArgumentReg2 = 2; const int ArgumentReg3 = 3; const int FramePointerReg = 11; const int StackPointerReg = INTREG_SP; const int ReturnAddressReg = INTREG_LR; const int PCReg = INTREG_PC; const int ZeroReg = INTREG_ZERO; const int SyscallNumReg = ReturnValueReg; const int SyscallPseudoReturnReg = ReturnValueReg; const int SyscallSuccessReg = ReturnValueReg; // These help enumerate all the registers for dependence tracking. const int FP_Base_DepTag = NumIntRegs * (MODE_MAXMODE + 1); const int Ctrl_Base_DepTag = FP_Base_DepTag + NumFloatRegs; typedef union { IntReg intreg; FloatReg fpreg; MiscReg ctrlreg; } AnyReg; } // namespace ArmISA #endif <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2014 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // // Original author of this file is Nick Hebner (hebnern@gmail.com). // #include "AudioEngine.h" #include "Dynamics.h" #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/TimeSource.h" #include <iostream> using namespace std; using namespace boost; namespace avg { AudioEngine* AudioEngine::s_pInstance = 0; AudioEngine* AudioEngine::get() { return s_pInstance; } AudioEngine::AudioEngine() : m_pTempBuffer(), m_pMixBuffer(0), m_pLimiter(0), m_pGobblerThread(0), m_bEnabled(true), m_Volume(1), m_bInitialized(false) { AVG_ASSERT(s_pInstance == 0); if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) { AVG_LOG_ERROR("Can't init SDL audio subsystem."); exit(-1); } s_pInstance = this; } AudioEngine::~AudioEngine() { if (m_pMixBuffer) { delete[] m_pMixBuffer; } if (m_pLimiter) { delete m_pLimiter; m_pLimiter = 0; } SDL_QuitSubSystem(SDL_INIT_AUDIO); m_AudioSources.clear(); } int AudioEngine::getChannels() { return m_AP.m_Channels; } int AudioEngine::getSampleRate() { return m_AP.m_SampleRate; } const AudioParams * AudioEngine::getParams() { if (isEnabled()) { return &m_AP; } else { return 0; } } void AudioEngine::init(const AudioParams& ap, float volume) { m_Volume = volume; if (!m_bInitialized) { m_bInitialized = true; m_AP = ap; Dynamics<float, 2>* pLimiter = new Dynamics<float, 2>(float(m_AP.m_SampleRate)); pLimiter->setThreshold(0.f); // in dB pLimiter->setAttackTime(0.f); // in seconds pLimiter->setReleaseTime(0.05f); // in seconds pLimiter->setRmsTime(0.f); // in seconds pLimiter->setRatio(std::numeric_limits<float>::infinity()); pLimiter->setMakeupGain(0.f); // in dB m_pLimiter = pLimiter; SDL_AudioSpec desired; desired.freq = m_AP.m_SampleRate; desired.format = AUDIO_S16SYS; desired.channels = m_AP.m_Channels; desired.silence = 0; desired.samples = m_AP.m_OutputBufferSamples; desired.callback = audioCallback; desired.userdata = this; int err = SDL_OpenAudio(&desired, 0); if (err < 0) { AVG_TRACE(Logger::category::CONFIG, Logger::severity::WARNING, "Can't open audio: " << SDL_GetError()); m_bStopGobbler = false; m_bFakeAudio = true; m_pGobblerThread = new boost::thread(&AudioEngine::consumeBuffers, this); } else { m_bFakeAudio = false; } } else { if (m_bFakeAudio) { m_bStopGobbler = false; m_pGobblerThread = new boost::thread(&AudioEngine::consumeBuffers, this); } else { SDL_PauseAudio(0); } } } void AudioEngine::teardown() { if (m_bFakeAudio) { if (m_pGobblerThread) { m_bStopGobbler = true; m_pGobblerThread->join(); delete m_pGobblerThread; m_pGobblerThread = 0; } } else { lock_guard lock(m_Mutex); SDL_PauseAudio(1); // Optimized away - takes too long. // SDL_CloseAudio(); } m_AudioSources.clear(); } void AudioEngine::setAudioEnabled(bool bEnabled) { SDL_LockAudio(); lock_guard lock(m_Mutex); AVG_ASSERT(m_AudioSources.empty()); m_bEnabled = bEnabled; if (m_bEnabled) { play(); } else { pause(); } SDL_UnlockAudio(); } void AudioEngine::play() { SDL_PauseAudio(0); } void AudioEngine::pause() { SDL_PauseAudio(1); } int AudioEngine::addSource(AudioMsgQueue& dataQ, AudioMsgQueue& statusQ) { SDL_LockAudio(); lock_guard lock(m_Mutex); static int nextID = -1; nextID++; AudioSourcePtr pSrc(new AudioSource(dataQ, statusQ, m_AP.m_SampleRate)); m_AudioSources[nextID] = pSrc; SDL_UnlockAudio(); return nextID; } void AudioEngine::removeSource(int id) { SDL_LockAudio(); lock_guard lock(m_Mutex); int numErased = m_AudioSources.erase(id); AVG_ASSERT(numErased == 1); SDL_UnlockAudio(); } void AudioEngine::pauseSource(int id) { lock_guard lock(m_Mutex); AudioSourceMap::iterator itSource = m_AudioSources.find(id); AVG_ASSERT(itSource != m_AudioSources.end()); AudioSourcePtr pSource = itSource->second; pSource->pause(); } void AudioEngine::playSource(int id) { lock_guard lock(m_Mutex); AudioSourceMap::iterator itSource = m_AudioSources.find(id); AVG_ASSERT(itSource != m_AudioSources.end()); AudioSourcePtr pSource = itSource->second; pSource->play(); } void AudioEngine::notifySeek(int id) { lock_guard lock(m_Mutex); AudioSourceMap::iterator itSource = m_AudioSources.find(id); AVG_ASSERT(itSource != m_AudioSources.end()); AudioSourcePtr pSource = itSource->second; pSource->notifySeek(); } void AudioEngine::setSourceVolume(int id, float volume) { lock_guard lock(m_Mutex); AudioSourceMap::iterator itSource = m_AudioSources.find(id); AVG_ASSERT(itSource != m_AudioSources.end()); AudioSourcePtr pSource = itSource->second; pSource->setVolume(volume); } void AudioEngine::setVolume(float volume) { SDL_LockAudio(); lock_guard lock(m_Mutex); m_Volume = volume; SDL_UnlockAudio(); } float AudioEngine::getVolume() const { return m_Volume; } bool AudioEngine::isEnabled() const { return m_bEnabled; } void AudioEngine::mixAudio(Uint8 *pDestBuffer, int destBufferLen) { int numFrames = destBufferLen/(2*getChannels()); // 16 bit samples. if (m_AudioSources.size() == 0) { return; } if (!m_pTempBuffer || m_pTempBuffer->getNumFrames() < numFrames) { if (m_pTempBuffer) { delete[] m_pMixBuffer; } m_pTempBuffer = AudioBufferPtr(new AudioBuffer(numFrames, m_AP)); m_pMixBuffer = new float[getChannels()*numFrames]; } for (int i = 0; i < getChannels()*numFrames; ++i) { m_pMixBuffer[i]=0; } { lock_guard lock(m_Mutex); AudioSourceMap::iterator it; for (it = m_AudioSources.begin(); it != m_AudioSources.end(); it++) { m_pTempBuffer->clear(); it->second->fillAudioBuffer(m_pTempBuffer); addBuffers(m_pMixBuffer, m_pTempBuffer); } } calcVolume(m_pMixBuffer, numFrames*getChannels(), getVolume()); for (int i = 0; i < numFrames; ++i) { m_pLimiter->process(m_pMixBuffer+i*getChannels()); for (int j = 0; j < getChannels(); ++j) { ((short*)pDestBuffer)[i*2+j]=short(m_pMixBuffer[i*2+j]*32768); } } } void AudioEngine::consumeBuffers() { // Separate thread that's active only if we don't have a running sound subsystem. while (!m_bStopGobbler) { msleep(3); AudioSourceMap::iterator it; lock_guard lock(m_Mutex); for (it = m_AudioSources.begin(); it != m_AudioSources.end(); it++) { it->second->clearQueue(); } } } void AudioEngine::audioCallback(void *userData, Uint8 *audioBuffer, int audioBufferLen) { AudioEngine *pThis = (AudioEngine*)userData; pThis->mixAudio(audioBuffer, audioBufferLen); } void AudioEngine::addBuffers(float *pDest, AudioBufferPtr pSrc) { int numFrames = pSrc->getNumFrames(); short * pData = pSrc->getData(); for(int i = 0; i < numFrames*getChannels(); ++i) { pDest[i] += pData[i]/32768.0f; } } void AudioEngine::calcVolume(float *pBuffer, int numSamples, float volume) { // TODO: We need a VolumeFader class that keeps state. for(int i = 0; i < numSamples; ++i) { pBuffer[i] *= volume; } } } <commit_msg>Fixed mac audio.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2014 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // // Original author of this file is Nick Hebner (hebnern@gmail.com). // #include "AudioEngine.h" #include "Dynamics.h" #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/TimeSource.h" #include <iostream> using namespace std; using namespace boost; namespace avg { AudioEngine* AudioEngine::s_pInstance = 0; AudioEngine* AudioEngine::get() { return s_pInstance; } AudioEngine::AudioEngine() : m_pTempBuffer(), m_pMixBuffer(0), m_pLimiter(0), m_pGobblerThread(0), m_bEnabled(true), m_Volume(1), m_bInitialized(false) { AVG_ASSERT(s_pInstance == 0); if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) { AVG_LOG_ERROR("Can't init SDL audio subsystem."); exit(-1); } s_pInstance = this; } AudioEngine::~AudioEngine() { if (m_pMixBuffer) { delete[] m_pMixBuffer; } if (m_pLimiter) { delete m_pLimiter; m_pLimiter = 0; } SDL_QuitSubSystem(SDL_INIT_AUDIO); m_AudioSources.clear(); } int AudioEngine::getChannels() { return m_AP.m_Channels; } int AudioEngine::getSampleRate() { return m_AP.m_SampleRate; } const AudioParams * AudioEngine::getParams() { if (isEnabled()) { return &m_AP; } else { return 0; } } void AudioEngine::init(const AudioParams& ap, float volume) { m_Volume = volume; if (!m_bInitialized) { m_bInitialized = true; m_AP = ap; Dynamics<float, 2>* pLimiter = new Dynamics<float, 2>(float(m_AP.m_SampleRate)); pLimiter->setThreshold(0.f); // in dB pLimiter->setAttackTime(0.f); // in seconds pLimiter->setReleaseTime(0.05f); // in seconds pLimiter->setRmsTime(0.f); // in seconds pLimiter->setRatio(std::numeric_limits<float>::infinity()); pLimiter->setMakeupGain(0.f); // in dB m_pLimiter = pLimiter; SDL_AudioSpec desired; desired.freq = m_AP.m_SampleRate; desired.format = AUDIO_S16SYS; desired.channels = m_AP.m_Channels; desired.silence = 0; desired.samples = m_AP.m_OutputBufferSamples; desired.callback = audioCallback; desired.userdata = this; int err = SDL_OpenAudio(&desired, 0); if (err < 0) { AVG_TRACE(Logger::category::CONFIG, Logger::severity::WARNING, "Can't open audio: " << SDL_GetError()); m_bStopGobbler = false; m_bFakeAudio = true; m_pGobblerThread = new boost::thread(&AudioEngine::consumeBuffers, this); } else { m_bFakeAudio = false; } } else { if (m_bFakeAudio) { m_bStopGobbler = false; m_pGobblerThread = new boost::thread(&AudioEngine::consumeBuffers, this); } else { SDL_PauseAudio(0); } } } void AudioEngine::teardown() { if (m_bFakeAudio) { if (m_pGobblerThread) { m_bStopGobbler = true; m_pGobblerThread->join(); delete m_pGobblerThread; m_pGobblerThread = 0; } } else { lock_guard lock(m_Mutex); SDL_PauseAudio(1); // Optimized away - takes too long. // SDL_CloseAudio(); } m_AudioSources.clear(); } void AudioEngine::setAudioEnabled(bool bEnabled) { SDL_LockAudio(); lock_guard lock(m_Mutex); AVG_ASSERT(m_AudioSources.empty()); m_bEnabled = bEnabled; if (m_bEnabled) { play(); } else { pause(); } SDL_UnlockAudio(); } void AudioEngine::play() { SDL_PauseAudio(0); } void AudioEngine::pause() { SDL_PauseAudio(1); } int AudioEngine::addSource(AudioMsgQueue& dataQ, AudioMsgQueue& statusQ) { SDL_LockAudio(); lock_guard lock(m_Mutex); static int nextID = -1; nextID++; AudioSourcePtr pSrc(new AudioSource(dataQ, statusQ, m_AP.m_SampleRate)); m_AudioSources[nextID] = pSrc; SDL_UnlockAudio(); return nextID; } void AudioEngine::removeSource(int id) { SDL_LockAudio(); lock_guard lock(m_Mutex); int numErased = m_AudioSources.erase(id); AVG_ASSERT(numErased == 1); SDL_UnlockAudio(); } void AudioEngine::pauseSource(int id) { lock_guard lock(m_Mutex); AudioSourceMap::iterator itSource = m_AudioSources.find(id); AVG_ASSERT(itSource != m_AudioSources.end()); AudioSourcePtr pSource = itSource->second; pSource->pause(); } void AudioEngine::playSource(int id) { lock_guard lock(m_Mutex); AudioSourceMap::iterator itSource = m_AudioSources.find(id); AVG_ASSERT(itSource != m_AudioSources.end()); AudioSourcePtr pSource = itSource->second; pSource->play(); } void AudioEngine::notifySeek(int id) { lock_guard lock(m_Mutex); AudioSourceMap::iterator itSource = m_AudioSources.find(id); AVG_ASSERT(itSource != m_AudioSources.end()); AudioSourcePtr pSource = itSource->second; pSource->notifySeek(); } void AudioEngine::setSourceVolume(int id, float volume) { lock_guard lock(m_Mutex); AudioSourceMap::iterator itSource = m_AudioSources.find(id); AVG_ASSERT(itSource != m_AudioSources.end()); AudioSourcePtr pSource = itSource->second; pSource->setVolume(volume); } void AudioEngine::setVolume(float volume) { SDL_LockAudio(); lock_guard lock(m_Mutex); m_Volume = volume; SDL_UnlockAudio(); } float AudioEngine::getVolume() const { return m_Volume; } bool AudioEngine::isEnabled() const { return m_bEnabled; } void AudioEngine::mixAudio(Uint8 *pDestBuffer, int destBufferLen) { int numFrames = destBufferLen/(2*getChannels()); // 16 bit samples. if (!m_pTempBuffer || m_pTempBuffer->getNumFrames() < numFrames) { if (m_pTempBuffer) { delete[] m_pMixBuffer; } m_pTempBuffer = AudioBufferPtr(new AudioBuffer(numFrames, m_AP)); m_pMixBuffer = new float[getChannels()*numFrames]; } for (int i = 0; i < getChannels()*numFrames; ++i) { m_pMixBuffer[i]=0; } { lock_guard lock(m_Mutex); AudioSourceMap::iterator it; for (it = m_AudioSources.begin(); it != m_AudioSources.end(); it++) { m_pTempBuffer->clear(); it->second->fillAudioBuffer(m_pTempBuffer); addBuffers(m_pMixBuffer, m_pTempBuffer); } } calcVolume(m_pMixBuffer, numFrames*getChannels(), getVolume()); for (int i = 0; i < numFrames; ++i) { m_pLimiter->process(m_pMixBuffer+i*getChannels()); for (int j = 0; j < getChannels(); ++j) { ((short*)pDestBuffer)[i*2+j]=short(m_pMixBuffer[i*2+j]*32768); } } } void AudioEngine::consumeBuffers() { // Separate thread that's active only if we don't have a running sound subsystem. while (!m_bStopGobbler) { msleep(3); AudioSourceMap::iterator it; lock_guard lock(m_Mutex); for (it = m_AudioSources.begin(); it != m_AudioSources.end(); it++) { it->second->clearQueue(); } } } void AudioEngine::audioCallback(void *userData, Uint8 *audioBuffer, int audioBufferLen) { AudioEngine *pThis = (AudioEngine*)userData; pThis->mixAudio(audioBuffer, audioBufferLen); } void AudioEngine::addBuffers(float *pDest, AudioBufferPtr pSrc) { int numFrames = pSrc->getNumFrames(); short * pData = pSrc->getData(); for(int i = 0; i < numFrames*getChannels(); ++i) { pDest[i] += pData[i]/32768.0f; } } void AudioEngine::calcVolume(float *pBuffer, int numSamples, float volume) { // TODO: We need a VolumeFader class that keeps state. for(int i = 0; i < numSamples; ++i) { pBuffer[i] *= volume; } } } <|endoftext|>
<commit_before>//===-- LibCxxOptional.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "LibCxx.h" #include "lldb/DataFormatters/FormattersHelpers.h" using namespace lldb; using namespace lldb_private; namespace { class OptionalFrontEnd : public SyntheticChildrenFrontEnd { public: OptionalFrontEnd(ValueObject &valobj) : SyntheticChildrenFrontEnd(valobj) { Update(); } size_t GetIndexOfChildWithName(const ConstString &name) override { return formatters::ExtractIndexFromString(name.GetCString()); } bool MightHaveChildren() override { return true; } bool Update() override; size_t CalculateNumChildren() override { return m_size; } ValueObjectSP GetChildAtIndex(size_t idx) override; private: size_t m_size = 0; ValueObjectSP m_base_sp; }; } // namespace bool OptionalFrontEnd::Update() { ValueObjectSP engaged_sp( m_backend.GetChildMemberWithName(ConstString("__engaged_"), true)); if (!engaged_sp) return false; // __engaged_ is a bool flag and is true if the optional contains a value. // Converting it to unsigned gives us a size of 1 if it contains a value // and 0 if not. m_size = engaged_sp->GetValueAsUnsigned(0); return false; } ValueObjectSP OptionalFrontEnd::GetChildAtIndex(size_t idx) { if (idx >= m_size) return ValueObjectSP(); // __val_ contains the underlying value of an optional if it has one. // Currently because it is part of an anonymous union GetChildMemberWithName() // does not peer through and find it unless we are at the parent itself. // We can obtain the parent through __engaged_. ValueObjectSP val_sp( m_backend.GetChildMemberWithName(ConstString("__engaged_"), true) ->GetParent() ->GetChildAtIndex(0, true) ->GetChildMemberWithName(ConstString("__val_"), true)); if (!val_sp) return ValueObjectSP(); CompilerType holder_type = val_sp->GetCompilerType(); if (!holder_type) return ValueObjectSP(); return val_sp->Clone(ConstString(llvm::formatv("Value").str())); } SyntheticChildrenFrontEnd * formatters::LibcxxOptionalFrontEndCreator(CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) { if (valobj_sp) return new OptionalFrontEnd(*valobj_sp); return nullptr; } <commit_msg>First test commit into svn, adding space to comment<commit_after>//===-- LibCxxOptional.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "LibCxx.h" #include "lldb/DataFormatters/FormattersHelpers.h" using namespace lldb; using namespace lldb_private; namespace { class OptionalFrontEnd : public SyntheticChildrenFrontEnd { public: OptionalFrontEnd(ValueObject &valobj) : SyntheticChildrenFrontEnd(valobj) { Update(); } size_t GetIndexOfChildWithName(const ConstString &name) override { return formatters::ExtractIndexFromString(name.GetCString()); } bool MightHaveChildren() override { return true; } bool Update() override; size_t CalculateNumChildren() override { return m_size; } ValueObjectSP GetChildAtIndex(size_t idx) override; private: size_t m_size = 0; ValueObjectSP m_base_sp; }; } // namespace bool OptionalFrontEnd::Update() { ValueObjectSP engaged_sp( m_backend.GetChildMemberWithName(ConstString("__engaged_"), true)); if (!engaged_sp) return false; // __engaged_ is a bool flag and is true if the optional contains a value. // Converting it to unsigned gives us a size of 1 if it contains a value // and 0 if not . m_size = engaged_sp->GetValueAsUnsigned(0); return false; } ValueObjectSP OptionalFrontEnd::GetChildAtIndex(size_t idx) { if (idx >= m_size) return ValueObjectSP(); // __val_ contains the underlying value of an optional if it has one. // Currently because it is part of an anonymous union GetChildMemberWithName() // does not peer through and find it unless we are at the parent itself. // We can obtain the parent through __engaged_. ValueObjectSP val_sp( m_backend.GetChildMemberWithName(ConstString("__engaged_"), true) ->GetParent() ->GetChildAtIndex(0, true) ->GetChildMemberWithName(ConstString("__val_"), true)); if (!val_sp) return ValueObjectSP(); CompilerType holder_type = val_sp->GetCompilerType(); if (!holder_type) return ValueObjectSP(); return val_sp->Clone(ConstString(llvm::formatv("Value").str())); } SyntheticChildrenFrontEnd * formatters::LibcxxOptionalFrontEndCreator(CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) { if (valobj_sp) return new OptionalFrontEnd(*valobj_sp); return nullptr; } <|endoftext|>
<commit_before>#include "ScreenSpaceFluidRenderer.h" #include <iostream> #include <glm/ext.hpp> #include <glbinding/gl/enum.h> #include <glbinding/gl/bitfield.h> #include <glbinding/gl/functions.h> #include <gloperate/painter/CameraCapability.h> #include <gloperate/painter/PerspectiveProjectionCapability.h> #include <gloperate/painter/ViewportCapability.h> #include <globjects/Buffer.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include "MetaballsExample.h" ScreenSpaceFluidRenderer::ScreenSpaceFluidRenderer() { } ScreenSpaceFluidRenderer::~ScreenSpaceFluidRenderer() { } void ScreenSpaceFluidRenderer::initialize() { m_program = new globjects::Program; m_program->attach( globjects::Shader::fromFile(gl::GL_VERTEX_SHADER, "data/metaballsexample/screen_space_fluid/shader.vert"), globjects::Shader::fromFile(gl::GL_FRAGMENT_SHADER, "data/metaballsexample/screen_space_fluid/shader.frag"), globjects::Shader::fromFile(gl::GL_GEOMETRY_SHADER, "data/metaballsexample/screen_space_fluid/quad_emmiting.geom") ); } void ScreenSpaceFluidRenderer::draw(MetaballsExample * painter) { //parameters float sphere_radius = 1.0f; glm::vec4 light_dir = glm::vec4(-1.0f, -1.0f, -1.0f, 1.0f); //--// m_vertices = new globjects::Buffer; m_vertices->setData( painter->metaballs() , gl::GL_STATIC_DRAW); m_vao = new globjects::VertexArray; auto binding = m_vao->binding(0); binding->setAttribute(0); binding->setBuffer(m_vertices, 0, 4 * sizeof(float)); binding->setFormat(4, gl::GL_FLOAT); m_vao->enable(0); m_vao->bind(); m_program->use(); m_program->setUniform("view", painter->cameraCapability()->view()); m_program->setUniform("projection", painter->projectionCapability()->projection()); m_program->setUniform("eye_pos", painter->cameraCapability()->center()); m_program->setUniform("sphere_radius", sphere_radius); m_program->setUniform("light_dir", light_dir); gl::glDrawArrays(gl::GL_POINTS, 0, painter->metaballs().size()); m_vao->unbind(); }<commit_msg>solved merge conflicts<commit_after>#include "ScreenSpaceFluidRenderer.h" #include <iostream> #include <glm/ext.hpp> #include <glbinding/gl/enum.h> #include <glbinding/gl/bitfield.h> #include <glbinding/gl/functions.h> #include <gloperate/painter/CameraCapability.h> #include <gloperate/painter/PerspectiveProjectionCapability.h> #include <gloperate/painter/ViewportCapability.h> #include <globjects/Buffer.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include "MetaballsExample.h" ScreenSpaceFluidRenderer::ScreenSpaceFluidRenderer() { } ScreenSpaceFluidRenderer::~ScreenSpaceFluidRenderer() { } void ScreenSpaceFluidRenderer::initialize() { m_program = new globjects::Program; m_program->attach( globjects::Shader::fromFile(gl::GL_VERTEX_SHADER, "data/metaballsexample/screen_space_fluid/shader.vert"), globjects::Shader::fromFile(gl::GL_FRAGMENT_SHADER, "data/metaballsexample/screen_space_fluid/shader.frag"), globjects::Shader::fromFile(gl::GL_GEOMETRY_SHADER, "data/metaballsexample/screen_space_fluid/quad_emmiting.geom") ); } void ScreenSpaceFluidRenderer::draw(MetaballsExample * painter) { std::array<glm::vec4> m_metaballs[20] = painter->getMetaballs(); //parameters float sphere_radius = 1.0f; glm::vec4 light_dir = glm::vec4(-1.0f, -1.0f, -1.0f, 1.0f); //--// m_vertices = new globjects::Buffer; m_vertices->setData( m_metaballs , gl::GL_STATIC_DRAW); m_vao = new globjects::VertexArray; auto binding = m_vao->binding(0); binding->setAttribute(0); binding->setBuffer(m_vertices, 0, 4 * sizeof(float)); binding->setFormat(4, gl::GL_FLOAT); m_vao->enable(0); m_vao->bind(); m_program->use(); m_program->setUniform("view", painter->cameraCapability()->view()); m_program->setUniform("projection", painter->projectionCapability()->projection()); m_program->setUniform("eye_pos", painter->cameraCapability()->center()); m_program->setUniform("sphere_radius", sphere_radius); m_program->setUniform("light_dir", light_dir); gl::glDrawArrays(gl::GL_POINTS, 0, m_metaballs.size()); m_vao->unbind(); }<|endoftext|>
<commit_before>#include "FileCreator.h" #include "ErrorCodes.h" #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <folly/Conv.h> namespace facebook { namespace wdt { bool FileCreator::setFileSize(int fd, size_t fileSize) { struct stat fileStat; if (fstat(fd, &fileStat) != 0) { PLOG(ERROR) << "fstat() failed for " << fd; return false; } if (fileStat.st_size > fileSize) { // existing file is larger than required if (ftruncate(fd, fileSize) != 0) { PLOG(ERROR) << "ftruncate() failed for " << fd; return false; } } int status = posix_fallocate(fd, 0, fileSize); if (status != 0) { LOG(ERROR) << "fallocate() failed " << strerror(status); return false; } return true; } int FileCreator::openAndSetSize(const std::string &relPath, size_t size) { int fd = createFile(relPath); if (fd < 0) { return -1; } if (!setFileSize(fd, size)) { close(fd); return -1; } return fd; } int FileCreator::openForFirstBlock(int threadIndex, const std::string &relPath, uint64_t seqId, size_t size) { int fd = openAndSetSize(relPath, size); { folly::SpinLockGuard guard(lock_); auto it = fileStatusMap_.find(seqId); WDT_CHECK(it != fileStatusMap_.end()); it->second = fd >= 0 ? ALLOCATED : FAILED; } std::unique_lock<std::mutex> waitLock(allocationMutex_); threadConditionVariables_[threadIndex].notify_all(); return fd; } bool FileCreator::waitForAllocationFinish(int allocatingThreadIndex, uint64_t seqId) { std::unique_lock<std::mutex> waitLock(allocationMutex_); while (true) { { folly::SpinLockGuard guard(lock_); auto it = fileStatusMap_.find(seqId); WDT_CHECK(it != fileStatusMap_.end()); if (it->second == ALLOCATED) { return true; } if (it->second == FAILED) { return false; } } threadConditionVariables_[allocatingThreadIndex].wait(waitLock); } } int FileCreator::openForBlocks(int threadIndex, const std::string &relPath, uint64_t seqId, size_t size) { lock_.lock(); auto it = fileStatusMap_.find(seqId); if (it == fileStatusMap_.end()) { // allocation has not started for this file fileStatusMap_.insert(std::make_pair(seqId, threadIndex)); lock_.unlock(); return openForFirstBlock(threadIndex, relPath, seqId, size); } auto status = it->second; lock_.unlock(); if (status == FAILED) { // allocation failed previously return -1; } if (status != ALLOCATED) { // allocation in progress if (!waitForAllocationFinish(it->second, seqId)) { return -1; } } return createFile(relPath); } using std::string; int FileCreator::createFile(const string &relPathStr) { CHECK(!relPathStr.empty()); CHECK(relPathStr[0] != '/'); CHECK(relPathStr.back() != '/'); std::string path(rootDir_); path.append(relPathStr); int p = relPathStr.size(); while (p && relPathStr[p - 1] != '/') { --p; } std::string dir; if (p) { dir.assign(relPathStr.data(), p); if (!createDirRecursively(dir)) { // retry with force LOG(ERROR) << "failed to create dir " << dir << " recursively, " << "trying to force directory creation"; if (!createDirRecursively(dir, true /* force */)) { LOG(ERROR) << "failed to create dir " << dir << " recursively"; return -1; } } } int openFlags = O_CREAT | O_WRONLY; int res = open(path.c_str(), openFlags, 0644); if (res < 0) { if (dir.empty()) { PLOG(ERROR) << "failed creating file " << path; return -1; } PLOG(ERROR) << "failed creating file " << path << ", trying to " << "force directory creation"; if (!createDirRecursively(dir, true /* force */)) { LOG(ERROR) << "failed to create dir " << dir << " recursively"; return -1; } res = open(path.c_str(), openFlags, 0644); if (res < 0) { PLOG(ERROR) << "failed creating file " << path; return -1; } } VLOG(1) << "successfully created file " << path; return res; } bool FileCreator::createDirRecursively(const std::string dir, bool force) { if (!force && dirCreated(dir)) { return true; } CHECK(dir.back() == '/'); size_t lastIndex = dir.size() - 1; while (lastIndex > 0 && dir[lastIndex - 1] != '/') { lastIndex--; } if (lastIndex > 0) { if (!createDirRecursively(dir.substr(0, lastIndex), force)) { return false; } } std::string fullDirPath; folly::toAppend(rootDir_, dir, &fullDirPath); int code = mkdir(fullDirPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (code != 0 && errno != EEXIST) { PLOG(ERROR) << "failed to make directory " << fullDirPath; return false; } else if (code != 0) { LOG(INFO) << "dir already exists " << fullDirPath; } else { LOG(INFO) << "made dir " << fullDirPath; } { std::lock_guard<std::mutex> lock(mutex_); createdDirs_.insert(dir); } return true; } /* static */ void FileCreator::addTrailingSlash(string &path) { if (path.back() != '/') { path.push_back('/'); VLOG(1) << "Added missing trailing / to " << path; } } } } <commit_msg>Fixing a minor bug related to pre-allocation<commit_after>#include "FileCreator.h" #include "ErrorCodes.h" #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <folly/Conv.h> namespace facebook { namespace wdt { bool FileCreator::setFileSize(int fd, size_t fileSize) { struct stat fileStat; if (fstat(fd, &fileStat) != 0) { PLOG(ERROR) << "fstat() failed for " << fd; return false; } if (fileStat.st_size > fileSize) { // existing file is larger than required if (ftruncate(fd, fileSize) != 0) { PLOG(ERROR) << "ftruncate() failed for " << fd; return false; } } if (fileSize == 0) { return true; } int status = posix_fallocate(fd, 0, fileSize); if (status != 0) { LOG(ERROR) << "fallocate() failed " << strerror(status); return false; } return true; } int FileCreator::openAndSetSize(const std::string &relPath, size_t size) { int fd = createFile(relPath); if (fd < 0) { return -1; } if (!setFileSize(fd, size)) { close(fd); return -1; } return fd; } int FileCreator::openForFirstBlock(int threadIndex, const std::string &relPath, uint64_t seqId, size_t size) { int fd = openAndSetSize(relPath, size); { folly::SpinLockGuard guard(lock_); auto it = fileStatusMap_.find(seqId); WDT_CHECK(it != fileStatusMap_.end()); it->second = fd >= 0 ? ALLOCATED : FAILED; } std::unique_lock<std::mutex> waitLock(allocationMutex_); threadConditionVariables_[threadIndex].notify_all(); return fd; } bool FileCreator::waitForAllocationFinish(int allocatingThreadIndex, uint64_t seqId) { std::unique_lock<std::mutex> waitLock(allocationMutex_); while (true) { { folly::SpinLockGuard guard(lock_); auto it = fileStatusMap_.find(seqId); WDT_CHECK(it != fileStatusMap_.end()); if (it->second == ALLOCATED) { return true; } if (it->second == FAILED) { return false; } } threadConditionVariables_[allocatingThreadIndex].wait(waitLock); } } int FileCreator::openForBlocks(int threadIndex, const std::string &relPath, uint64_t seqId, size_t size) { lock_.lock(); auto it = fileStatusMap_.find(seqId); if (it == fileStatusMap_.end()) { // allocation has not started for this file fileStatusMap_.insert(std::make_pair(seqId, threadIndex)); lock_.unlock(); return openForFirstBlock(threadIndex, relPath, seqId, size); } auto status = it->second; lock_.unlock(); if (status == FAILED) { // allocation failed previously return -1; } if (status != ALLOCATED) { // allocation in progress if (!waitForAllocationFinish(it->second, seqId)) { return -1; } } return createFile(relPath); } using std::string; int FileCreator::createFile(const string &relPathStr) { CHECK(!relPathStr.empty()); CHECK(relPathStr[0] != '/'); CHECK(relPathStr.back() != '/'); std::string path(rootDir_); path.append(relPathStr); int p = relPathStr.size(); while (p && relPathStr[p - 1] != '/') { --p; } std::string dir; if (p) { dir.assign(relPathStr.data(), p); if (!createDirRecursively(dir)) { // retry with force LOG(ERROR) << "failed to create dir " << dir << " recursively, " << "trying to force directory creation"; if (!createDirRecursively(dir, true /* force */)) { LOG(ERROR) << "failed to create dir " << dir << " recursively"; return -1; } } } int openFlags = O_CREAT | O_WRONLY; int res = open(path.c_str(), openFlags, 0644); if (res < 0) { if (dir.empty()) { PLOG(ERROR) << "failed creating file " << path; return -1; } PLOG(ERROR) << "failed creating file " << path << ", trying to " << "force directory creation"; if (!createDirRecursively(dir, true /* force */)) { LOG(ERROR) << "failed to create dir " << dir << " recursively"; return -1; } res = open(path.c_str(), openFlags, 0644); if (res < 0) { PLOG(ERROR) << "failed creating file " << path; return -1; } } VLOG(1) << "successfully created file " << path; return res; } bool FileCreator::createDirRecursively(const std::string dir, bool force) { if (!force && dirCreated(dir)) { return true; } CHECK(dir.back() == '/'); size_t lastIndex = dir.size() - 1; while (lastIndex > 0 && dir[lastIndex - 1] != '/') { lastIndex--; } if (lastIndex > 0) { if (!createDirRecursively(dir.substr(0, lastIndex), force)) { return false; } } std::string fullDirPath; folly::toAppend(rootDir_, dir, &fullDirPath); int code = mkdir(fullDirPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (code != 0 && errno != EEXIST) { PLOG(ERROR) << "failed to make directory " << fullDirPath; return false; } else if (code != 0) { LOG(INFO) << "dir already exists " << fullDirPath; } else { LOG(INFO) << "made dir " << fullDirPath; } { std::lock_guard<std::mutex> lock(mutex_); createdDirs_.insert(dir); } return true; } /* static */ void FileCreator::addTrailingSlash(string &path) { if (path.back() != '/') { path.push_back('/'); VLOG(1) << "Added missing trailing / to " << path; } } } } <|endoftext|>
<commit_before>/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /*************************************************************************************************/ #include <GG/EveParser.h> #include <GG/adobe/adam.hpp> #include <GG/adobe/array.hpp> #include <GG/adobe/cmath.hpp> #include <GG/adobe/dictionary.hpp> #include <GG/adobe/empty.hpp> #include <GG/adobe/eve_evaluate.hpp> #include <GG/adobe/eve_parser.hpp> #include <GG/adobe/eve.hpp> #include <GG/adobe/enum_ops.hpp> #include <GG/adobe/future/resources.hpp> #include <GG/adobe/future/widgets/headers/button_factory.hpp> #include <GG/adobe/future/widgets/headers/checkbox_factory.hpp> #include <GG/adobe/future/widgets/headers/control_button_factory.hpp> #include <GG/adobe/future/widgets/headers/display_number_factory.hpp> #include <GG/adobe/future/widgets/headers/display.hpp> #include <GG/adobe/future/widgets/headers/edit_number_factory.hpp> #include <GG/adobe/future/widgets/headers/edit_text_factory.hpp> #include <GG/adobe/future/widgets/headers/factory.hpp> #include <GG/adobe/future/widgets/headers/group_factory.hpp> #include <GG/adobe/future/widgets/headers/image_factory.hpp> #include <GG/adobe/future/widgets/headers/label_factory.hpp> #include <GG/adobe/future/widgets/headers/optional_panel_factory.hpp> #include <GG/adobe/future/widgets/headers/panel_factory.hpp> #include <GG/adobe/future/widgets/headers/popup_factory.hpp> #include <GG/adobe/future/widgets/headers/presets_factory.hpp> #include <GG/adobe/future/widgets/headers/preview_factory.hpp> #include <GG/adobe/future/widgets/headers/progress_bar_factory.hpp> #include <GG/adobe/future/widgets/headers/radio_button_factory.hpp> #include <GG/adobe/future/widgets/headers/reveal_factory.hpp> #include <GG/adobe/future/widgets/headers/separator_factory.hpp> #include <GG/adobe/future/widgets/headers/slider_factory.hpp> #include <GG/adobe/future/widgets/headers/tab_group_factory.hpp> #include <GG/adobe/future/widgets/headers/toggle_factory.hpp> #include <GG/adobe/future/widgets/headers/value_range_format.hpp> #include <GG/adobe/future/widgets/headers/virtual_machine_extension.hpp> #include <GG/adobe/future/widgets/headers/widget_factory_registry.hpp> #include <GG/adobe/future/widgets/headers/widget_factory.hpp> #include <GG/adobe/future/widgets/headers/widget_tokens.hpp> #include <GG/adobe/future/widgets/headers/window_factory.hpp> #include <GG/adobe/istream.hpp> #include <GG/adobe/memory.hpp> #include <GG/adobe/name.hpp> #include <GG/adobe/poly_placeable.hpp> #include <GG/adobe/static_table.hpp> #include <GG/adobe/string.hpp> #include <GG/adobe/view_concept.hpp> #ifdef ADOBE_STD_SERIALIZATION #include <GG/adobe/iomanip.hpp> #endif #include <boost/optional.hpp> #include <boost/bind.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include <cassert> #include <fstream> #include <iostream> #include <string> /*************************************************************************************************/ namespace { /*************************************************************************************************/ struct noncreating_placeable_t { void measure(adobe::extents_t&) { } void place(const adobe::place_data_t&) const { } }; inline bool operator==(const noncreating_placeable_t& x, const noncreating_placeable_t& y) { return &x == &y; // Temporary hack until equality is implemented } /*************************************************************************************************/ inline const adobe::layout_attributes_t& row_layout_attributes() { static bool inited(false); static adobe::layout_attributes_t result; if (!inited) { result.placement_m = adobe::eve_t::place_row; result.vertical().suppress_m = false; // Allow baselines to propagate result.create_m = false; inited = true; } return result; } /*************************************************************************************************/ inline const adobe::layout_attributes_t& column_layout_attributes() { static bool inited(false); static adobe::layout_attributes_t result; if (!inited) { result.placement_m = adobe::eve_t::place_column; result.vertical().suppress_m = true; result.create_m = false; inited = true; } return result; } /*************************************************************************************************/ inline const adobe::layout_attributes_t& overlay_layout_attributes() { static bool inited(false); static adobe::layout_attributes_t result; if (!inited) { result.placement_m = adobe::eve_t::place_overlay; result.vertical().suppress_m = false; // Allow baselines to propagate result.create_m = false; inited = true; } return result; } /*************************************************************************************************/ adobe::widget_node_t wire_to_eve_noncreating(const adobe::factory_token_t& token, const adobe::widget_node_t& parent, const adobe::dictionary_t& parameters, bool is_container, const adobe::layout_attributes_t& layout_attributes) { adobe::poly_placeable_t *p(new adobe::poly_placeable_t(noncreating_placeable_t())); adobe::layout_attributes_t attributes = layout_attributes; apply_layout_parameters(attributes, parameters); adobe::eve_t::iterator eve_token = token.client_holder_m.eve_m.add_placeable(parent.eve_token_m, attributes, is_container, boost::ref(*p)); token.client_holder_m.assemblage_m.cleanup(boost::bind(adobe::delete_ptr<adobe::poly_placeable_t *>(), p)); return adobe::widget_node_t(parent.size_m, eve_token, parent.display_token_m, parent.keyboard_token_m); } /*************************************************************************************************/ } // namespace /*************************************************************************************************/ namespace adobe { /*************************************************************************************************/ widget_node_t row_factory(const dictionary_t& parameters, const widget_node_t& parent, const factory_token_t& token, const widget_factory_t& factory) { return wire_to_eve_noncreating(token, parent, parameters, factory.is_container(static_name_t("row")), factory.layout_attributes(static_name_t("row"))); } widget_node_t column_factory(const dictionary_t& parameters, const widget_node_t& parent, const factory_token_t& token, const widget_factory_t& factory) { return wire_to_eve_noncreating(token, parent, parameters, factory.is_container(static_name_t("column")), factory.layout_attributes(static_name_t("column"))); } widget_node_t overlay_factory(const dictionary_t& parameters, const widget_node_t& parent, const factory_token_t& token, const widget_factory_t& factory) { return wire_to_eve_noncreating(token, parent, parameters, factory.is_container(static_name_t("overlay")), factory.layout_attributes(static_name_t("overlay"))); } /*************************************************************************************************/ widget_factory_t& default_asl_widget_factory() { static bool inited(false); static widget_factory_t default_factory_s; if (!inited) { default_factory_s.reg(name_column, &column_factory, true, column_layout_attributes()); default_factory_s.reg(name_overlay, &overlay_factory, true, overlay_layout_attributes()); default_factory_s.reg(name_row, &row_factory, true, row_layout_attributes()); default_factory_s.reg(name_button, &make_button); default_factory_s.reg(name_checkbox, &make_checkbox); default_factory_s.reg(name_control_button, &make_control_button); default_factory_s.reg(name_dialog, &make_window, true, window_layout_attributes()); default_factory_s.reg(name_display_number, &implementation::make_display_number); default_factory_s.reg(name_edit_number, &make_edit_number); default_factory_s.reg(name_edit_text, &implementation::make_edit_text); default_factory_s.reg(name_group, &make_group, true, group_layout_attributes()); default_factory_s.reg(name_image, &implementation::make_image_hack); default_factory_s.reg(name_toggle, &make_toggle); default_factory_s.reg(name_label, &implementation::make_label_hack); default_factory_s.reg(name_optional, &make_optional_panel, true, optional_panel_layout_attributes()); default_factory_s.reg(name_panel, &make_panel, true, panel_layout_attributes()); default_factory_s.reg(name_popup, &make_popup); default_factory_s.reg(name_preset, &make_presets); default_factory_s.reg(name_preview, &make_preview); default_factory_s.reg(name_progress_bar, &make_progress_bar); default_factory_s.reg(name_radio_button, &make_radio_button); default_factory_s.reg(name_reveal, &make_reveal); default_factory_s.reg(name_separator, &make_separator, false, separator_layout_attributes()); default_factory_s.reg(name_slider, &make_slider); default_factory_s.reg(name_static_text, &implementation::make_label_hack); default_factory_s.reg(name_tab_group, &make_tab_group, true, tab_group_layout_attributes()); inited = true; } return default_factory_s; } /*************************************************************************************************/ } // namespace adobe /*************************************************************************************************/ boost::any client_assembler(adobe::factory_token_t& token, const boost::any& parent, adobe::name_t class_name, const adobe::dictionary_t& arguments, const adobe::widget_factory_proc_t& proc) { // // Notice that we use the supplied factory to create widgets. // return proc(class_name, arguments, boost::any_cast<adobe::widget_node_t>(parent), token); } /*************************************************************************************************/ namespace adobe { /*************************************************************************************************/ auto_ptr<eve_client_holder> make_view(const std::string& stream_source, const line_position_t::getline_proc_t& getline_proc, std::istream& stream, sheet_t& sheet, behavior_t& root_behavior, const button_notifier_t& button_notifier, const signal_notifier_t& signal_notifier, size_enum_t dialog_size, const widget_factory_proc_t& proc, platform_display_type display_root) { adobe::auto_ptr<eve_client_holder> result(new eve_client_holder(root_behavior)); factory_token_t token(get_main_display(), sheet, *(result.get()), button_notifier, signal_notifier); /* We set the initial parent to be the root of the main display, an empty eve iterator and the given dialog size. */ get_main_display().set_root(display_root); std::string stream_contents; std::getline(stream, stream_contents, '\0'); if (!GG::Parse(stream_contents, stream_source, widget_node_t(dialog_size, eve_t::iterator(), get_main_display().root(), keyboard_t::iterator()), bind_layout(boost::bind(&client_assembler, boost::ref(token), _1, _2, _3, boost::cref(proc)), result->layout_sheet_m, sheet.machine_m))) { throw std::logic_error("Eve parse failed."); } result->contributing_m = sheet.contributing(); return result; } /*************************************************************************************************/ } // namespace adobe /*************************************************************************************************/ <commit_msg>Revert "Fixed a problem with the registration of user expression functions." It allowed registrations of user-defined functions, but broke some existing functionality.<commit_after>/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /*************************************************************************************************/ #include <GG/EveParser.h> #include <GG/adobe/adam.hpp> #include <GG/adobe/array.hpp> #include <GG/adobe/cmath.hpp> #include <GG/adobe/dictionary.hpp> #include <GG/adobe/empty.hpp> #include <GG/adobe/eve_evaluate.hpp> #include <GG/adobe/eve_parser.hpp> #include <GG/adobe/eve.hpp> #include <GG/adobe/enum_ops.hpp> #include <GG/adobe/future/resources.hpp> #include <GG/adobe/future/widgets/headers/button_factory.hpp> #include <GG/adobe/future/widgets/headers/checkbox_factory.hpp> #include <GG/adobe/future/widgets/headers/control_button_factory.hpp> #include <GG/adobe/future/widgets/headers/display_number_factory.hpp> #include <GG/adobe/future/widgets/headers/display.hpp> #include <GG/adobe/future/widgets/headers/edit_number_factory.hpp> #include <GG/adobe/future/widgets/headers/edit_text_factory.hpp> #include <GG/adobe/future/widgets/headers/factory.hpp> #include <GG/adobe/future/widgets/headers/group_factory.hpp> #include <GG/adobe/future/widgets/headers/image_factory.hpp> #include <GG/adobe/future/widgets/headers/label_factory.hpp> #include <GG/adobe/future/widgets/headers/optional_panel_factory.hpp> #include <GG/adobe/future/widgets/headers/panel_factory.hpp> #include <GG/adobe/future/widgets/headers/popup_factory.hpp> #include <GG/adobe/future/widgets/headers/presets_factory.hpp> #include <GG/adobe/future/widgets/headers/preview_factory.hpp> #include <GG/adobe/future/widgets/headers/progress_bar_factory.hpp> #include <GG/adobe/future/widgets/headers/radio_button_factory.hpp> #include <GG/adobe/future/widgets/headers/reveal_factory.hpp> #include <GG/adobe/future/widgets/headers/separator_factory.hpp> #include <GG/adobe/future/widgets/headers/slider_factory.hpp> #include <GG/adobe/future/widgets/headers/tab_group_factory.hpp> #include <GG/adobe/future/widgets/headers/toggle_factory.hpp> #include <GG/adobe/future/widgets/headers/value_range_format.hpp> #include <GG/adobe/future/widgets/headers/virtual_machine_extension.hpp> #include <GG/adobe/future/widgets/headers/widget_factory_registry.hpp> #include <GG/adobe/future/widgets/headers/widget_factory.hpp> #include <GG/adobe/future/widgets/headers/widget_tokens.hpp> #include <GG/adobe/future/widgets/headers/window_factory.hpp> #include <GG/adobe/istream.hpp> #include <GG/adobe/memory.hpp> #include <GG/adobe/name.hpp> #include <GG/adobe/poly_placeable.hpp> #include <GG/adobe/static_table.hpp> #include <GG/adobe/string.hpp> #include <GG/adobe/view_concept.hpp> #ifdef ADOBE_STD_SERIALIZATION #include <GG/adobe/iomanip.hpp> #endif #include <boost/optional.hpp> #include <boost/bind.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include <cassert> #include <fstream> #include <iostream> #include <string> /*************************************************************************************************/ namespace { /*************************************************************************************************/ struct noncreating_placeable_t { void measure(adobe::extents_t&) { } void place(const adobe::place_data_t&) const { } }; inline bool operator==(const noncreating_placeable_t& x, const noncreating_placeable_t& y) { return &x == &y; // Temporary hack until equality is implemented } /*************************************************************************************************/ inline const adobe::layout_attributes_t& row_layout_attributes() { static bool inited(false); static adobe::layout_attributes_t result; if (!inited) { result.placement_m = adobe::eve_t::place_row; result.vertical().suppress_m = false; // Allow baselines to propagate result.create_m = false; inited = true; } return result; } /*************************************************************************************************/ inline const adobe::layout_attributes_t& column_layout_attributes() { static bool inited(false); static adobe::layout_attributes_t result; if (!inited) { result.placement_m = adobe::eve_t::place_column; result.vertical().suppress_m = true; result.create_m = false; inited = true; } return result; } /*************************************************************************************************/ inline const adobe::layout_attributes_t& overlay_layout_attributes() { static bool inited(false); static adobe::layout_attributes_t result; if (!inited) { result.placement_m = adobe::eve_t::place_overlay; result.vertical().suppress_m = false; // Allow baselines to propagate result.create_m = false; inited = true; } return result; } /*************************************************************************************************/ adobe::widget_node_t wire_to_eve_noncreating(const adobe::factory_token_t& token, const adobe::widget_node_t& parent, const adobe::dictionary_t& parameters, bool is_container, const adobe::layout_attributes_t& layout_attributes) { adobe::poly_placeable_t *p(new adobe::poly_placeable_t(noncreating_placeable_t())); adobe::layout_attributes_t attributes = layout_attributes; apply_layout_parameters(attributes, parameters); adobe::eve_t::iterator eve_token = token.client_holder_m.eve_m.add_placeable(parent.eve_token_m, attributes, is_container, boost::ref(*p)); token.client_holder_m.assemblage_m.cleanup(boost::bind(adobe::delete_ptr<adobe::poly_placeable_t *>(), p)); return adobe::widget_node_t(parent.size_m, eve_token, parent.display_token_m, parent.keyboard_token_m); } /*************************************************************************************************/ } // namespace /*************************************************************************************************/ namespace adobe { /*************************************************************************************************/ widget_node_t row_factory(const dictionary_t& parameters, const widget_node_t& parent, const factory_token_t& token, const widget_factory_t& factory) { return wire_to_eve_noncreating(token, parent, parameters, factory.is_container(static_name_t("row")), factory.layout_attributes(static_name_t("row"))); } widget_node_t column_factory(const dictionary_t& parameters, const widget_node_t& parent, const factory_token_t& token, const widget_factory_t& factory) { return wire_to_eve_noncreating(token, parent, parameters, factory.is_container(static_name_t("column")), factory.layout_attributes(static_name_t("column"))); } widget_node_t overlay_factory(const dictionary_t& parameters, const widget_node_t& parent, const factory_token_t& token, const widget_factory_t& factory) { return wire_to_eve_noncreating(token, parent, parameters, factory.is_container(static_name_t("overlay")), factory.layout_attributes(static_name_t("overlay"))); } /*************************************************************************************************/ widget_factory_t& default_asl_widget_factory() { static bool inited(false); static widget_factory_t default_factory_s; if (!inited) { default_factory_s.reg(name_column, &column_factory, true, column_layout_attributes()); default_factory_s.reg(name_overlay, &overlay_factory, true, overlay_layout_attributes()); default_factory_s.reg(name_row, &row_factory, true, row_layout_attributes()); default_factory_s.reg(name_button, &make_button); default_factory_s.reg(name_checkbox, &make_checkbox); default_factory_s.reg(name_control_button, &make_control_button); default_factory_s.reg(name_dialog, &make_window, true, window_layout_attributes()); default_factory_s.reg(name_display_number, &implementation::make_display_number); default_factory_s.reg(name_edit_number, &make_edit_number); default_factory_s.reg(name_edit_text, &implementation::make_edit_text); default_factory_s.reg(name_group, &make_group, true, group_layout_attributes()); default_factory_s.reg(name_image, &implementation::make_image_hack); default_factory_s.reg(name_toggle, &make_toggle); default_factory_s.reg(name_label, &implementation::make_label_hack); default_factory_s.reg(name_optional, &make_optional_panel, true, optional_panel_layout_attributes()); default_factory_s.reg(name_panel, &make_panel, true, panel_layout_attributes()); default_factory_s.reg(name_popup, &make_popup); default_factory_s.reg(name_preset, &make_presets); default_factory_s.reg(name_preview, &make_preview); default_factory_s.reg(name_progress_bar, &make_progress_bar); default_factory_s.reg(name_radio_button, &make_radio_button); default_factory_s.reg(name_reveal, &make_reveal); default_factory_s.reg(name_separator, &make_separator, false, separator_layout_attributes()); default_factory_s.reg(name_slider, &make_slider); default_factory_s.reg(name_static_text, &implementation::make_label_hack); default_factory_s.reg(name_tab_group, &make_tab_group, true, tab_group_layout_attributes()); inited = true; } return default_factory_s; } /*************************************************************************************************/ } // namespace adobe /*************************************************************************************************/ boost::any client_assembler(adobe::factory_token_t& token, const boost::any& parent, adobe::name_t class_name, const adobe::dictionary_t& arguments, const adobe::widget_factory_proc_t& proc) { // // Notice that we use the supplied factory to create widgets. // return proc(class_name, arguments, boost::any_cast<adobe::widget_node_t>(parent), token); } /*************************************************************************************************/ namespace adobe { /*************************************************************************************************/ auto_ptr<eve_client_holder> make_view(const std::string& stream_source, const line_position_t::getline_proc_t& getline_proc, std::istream& stream, sheet_t& sheet, behavior_t& root_behavior, const button_notifier_t& button_notifier, const signal_notifier_t& signal_notifier, size_enum_t dialog_size, const widget_factory_proc_t& proc, platform_display_type display_root) { adobe::auto_ptr<eve_client_holder> result(new eve_client_holder(root_behavior)); factory_token_t token(get_main_display(), sheet, *(result.get()), button_notifier, signal_notifier); virtual_machine_t evaluator; vm_lookup_t lookup; lookup.attach_to(evaluator); /* We set the initial parent to be the root of the main display, an empty eve iterator and the given dialog size. */ get_main_display().set_root(display_root); std::string stream_contents; std::getline(stream, stream_contents, '\0'); if (!GG::Parse(stream_contents, stream_source, widget_node_t(dialog_size, eve_t::iterator(), get_main_display().root(), keyboard_t::iterator()), bind_layout(boost::bind(&client_assembler, boost::ref(token), _1, _2, _3, boost::cref(proc)), result->layout_sheet_m, evaluator))) { throw std::logic_error("Eve parse failed."); } result->contributing_m = sheet.contributing(); return result; } /*************************************************************************************************/ } // namespace adobe /*************************************************************************************************/ <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ // Class header file. #include "AttributeListImpl.hpp" #include <algorithm> #include <cassert> #include <Include/XalanAutoPtr.hpp> #include "STLHelper.hpp" AttributeListImpl::AttributeListImpl() : AttributeList(), m_AttributeVector(), m_cacheVector() { } AttributeListImpl::~AttributeListImpl() { // Clean up everything... clear(); assert(m_AttributeVector.empty() == true); deleteEntries(m_cacheVector); } AttributeListImpl::AttributeListImpl(const AttributeListImpl& theSource) : AttributeList(), m_AttributeVector() { // Use the assignment operator to do the dirty work... *this = theSource; assert(getLength() == theSource.getLength()); } AttributeListImpl::AttributeListImpl(const AttributeList& theSource) : AttributeList(), m_AttributeVector() { // Use the assignment operator to do the dirty work... *this = theSource; assert(getLength() == theSource.getLength()); } void AttributeListImpl::deleteEntries(AttributeVectorType& theVector) { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Delete all of the objects in the vector. for_each(theVector.begin(), theVector.end(), DeleteFunctor<AttributeVectorEntry>()); } AttributeListImpl& AttributeListImpl::operator=(const AttributeListImpl& theRHS) { if (this != &theRHS) { // Note that we can't chain up to our base class operator=() // because it's private. // Some temporary structures to hold everything // until we're done. AttributeVectorType tempVector; const unsigned int theLength = theRHS.getLength(); if (theLength > 0) { // Reserve the appropriate capacity right now... tempVector.reserve(theLength); // This will delete everything in tempVector when we're done... CollectionDeleteGuard<AttributeVectorType, DeleteFunctor<AttributeVectorEntry> > theGuard(tempVector); typedef AttributeVectorType::const_iterator const_iterator; const const_iterator theEnd = theRHS.m_AttributeVector.begin(); // Copy the vector entries, and build the index map... for(const_iterator i = theRHS.m_AttributeVector.end(); i != theEnd; ++i) { AttributeVectorEntry* const theEntry = *i; assert(theEntry != 0); // Add the item... tempVector.push_back( getNewEntry( theEntry->m_Name.begin(), theEntry->m_Type.begin(), theEntry->m_Value.begin())); } // OK, we're safe, so swap the contents of the // containers. This is guaranteed not to throw. m_AttributeVector.swap(tempVector); } assert(getLength() == theLength); } return *this; } AttributeListImpl& AttributeListImpl::operator=(const AttributeList& theRHS) { if (this != &theRHS) { // Note that we can't chain up to our base class operator=() // because it's private. // Add all of the attributes to this temp list, // then swap at the end. This means we're exception // safe and don't need any try blocks. AttributeListImpl theTempList; const unsigned int theLength = theRHS.getLength(); theTempList.reserve(theLength); // Add each attribute. for(unsigned int i = 0; i < theLength; i++) { theTempList.addAttribute( theRHS.getName(i), theRHS.getType(i), theRHS.getValue(i)); } // Now that the temp list is built, swap everything. This is // guaranteed not to throw. swap(theTempList); } return *this; } unsigned int AttributeListImpl::getLength() const { return m_AttributeVector.size(); } const XMLCh* AttributeListImpl::getName(const unsigned int index) const { assert(index < getLength()); return &*m_AttributeVector[index]->m_Name.begin(); } const XMLCh* AttributeListImpl::getType(const unsigned int index) const { assert(index < getLength()); return &*m_AttributeVector[index]->m_Type.begin(); } const XMLCh* AttributeListImpl::getValue(const unsigned int index) const { assert(index < getLength()); return &*m_AttributeVector[index]->m_Value.begin(); } struct NameCompareFunctor { NameCompareFunctor(const XMLCh* theName) : m_name(theName) { } bool operator()(const AttributeListImpl::AttributeVectorEntry* theEntry) const { return equals(&*theEntry->m_Name.begin(), m_name); } private: const XMLCh* const m_name; }; const XMLCh* AttributeListImpl::getType(const XMLCh* const name) const { assert(name != 0); #if !defined(XALAN_NO_NAMESPACES) using std::find_if; #endif const AttributeVectorType::const_iterator i = find_if( m_AttributeVector.begin(), m_AttributeVector.end(), NameCompareFunctor(name)); if (i != m_AttributeVector.end()) { // Found it, so return a pointer to the type. return &*(*i)->m_Type.begin(); } else { return 0; } } const XMLCh* AttributeListImpl::getValue(const char* const name) const { return getValue(&*MakeXalanDOMCharVector(name).begin()); } const XMLCh* AttributeListImpl::getValue(const XMLCh* const name) const { assert(name != 0); #if !defined(XALAN_NO_NAMESPACES) using std::find_if; #endif const AttributeVectorType::const_iterator i = find_if( m_AttributeVector.begin(), m_AttributeVector.end(), NameCompareFunctor(name)); if (i != m_AttributeVector.end()) { // Found it, so return a pointer to the value. return &*(*i)->m_Value.begin(); } else { return 0; } } void AttributeListImpl::clear() { m_cacheVector.insert(m_cacheVector.end(), m_AttributeVector.begin(), m_AttributeVector.end()); // Clear everything out. m_AttributeVector.clear(); } // A convenience function to find the length of a null-terminated // array of XMLChs inline const XMLCh* endArray(const XMLCh* data) { assert(data != 0); while(*data) { ++data; } return data; } bool AttributeListImpl::addAttribute( const XMLCh* name, const XMLCh* type, const XMLCh* value) { assert(name != 0); assert(type != 0); assert(value != 0); bool fResult = false; #if !defined(XALAN_NO_NAMESPACES) using std::find_if; using std::copy; #endif // Update the attribute, if it's already there... const AttributeVectorType::const_iterator i = find_if( m_AttributeVector.begin(), m_AttributeVector.end(), NameCompareFunctor(name)); if (i != m_AttributeVector.end()) { // This is a special optimization for type, since it's (almost) always "CDATA". if (equals(type, &*(*i)->m_Type.begin()) == false) { // If necessary, create the a new vector and swap them. Otherwise, // just copy the new data in. const XMLCh* const theNewTypeEnd = endArray(type) + 1; if ((*i)->m_Type.capacity() < XMLChVectorType::size_type(theNewTypeEnd - type)) { XMLChVectorType theNewType(type, theNewTypeEnd); theNewType.swap((*i)->m_Type); } else { copy(type, theNewTypeEnd, (*i)->m_Type.begin()); } } const XMLCh* const theNewValueEnd = endArray(value) + 1; // If necessary, create the a new vector and swap them. Otherwise, // just copy the new data in. if ((*i)->m_Value.capacity() < XMLChVectorType::size_type(theNewValueEnd - value)) { XMLChVectorType theNewValue(value, theNewValueEnd); theNewValue.swap((*i)->m_Value); } else { copy(value, theNewValueEnd, (*i)->m_Value.begin()); } } else { if (m_AttributeVector.capacity() == 0) { m_AttributeVector.reserve(eDefaultVectorSize); } XalanAutoPtr<AttributeVectorEntry> theEntry(getNewEntry(name, type, value)); // Add the new one. m_AttributeVector.push_back(theEntry.get()); // The entry is now safely in the vector, so release the // XalanAutoPtr... theEntry.release(); fResult = true; } return fResult; } AttributeListImpl::AttributeVectorEntry* AttributeListImpl::getNewEntry( const XMLCh* name, const XMLCh* type, const XMLCh* value) { if (m_cacheVector.size() == 0) { return new AttributeVectorEntry(name, value, type); } else { AttributeVectorEntry* const theEntry = m_cacheVector.back(); theEntry->clear(); assert(theEntry->m_Name.size() == 0 && theEntry->m_Value.size() == 0 && theEntry->m_Type.size() == 0); theEntry->m_Name.insert(theEntry->m_Name.begin(), name, endArray(name) + 1); theEntry->m_Value.insert(theEntry->m_Value.begin(), value, endArray(value) + 1); theEntry->m_Type.insert(theEntry->m_Type.begin(), type, endArray(type) + 1); m_cacheVector.pop_back(); return theEntry; } } bool AttributeListImpl::removeAttribute(const XMLCh* name) { assert(name != 0); #if !defined(XALAN_NO_NAMESPACES) using std::find_if; #endif bool fResult = false; // Update the attribute, if it's already there... const AttributeVectorType::iterator i = find_if( m_AttributeVector.begin(), m_AttributeVector.end(), NameCompareFunctor(name)); if (i != m_AttributeVector.end()) { m_cacheVector.push_back(*i); m_AttributeVector.erase(i); fResult = true; } return fResult; } <commit_msg>Fixed compiler error when iterator is not a pointer, and iterator bug in operator=().<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ // Class header file. #include "AttributeListImpl.hpp" #include <algorithm> #include <cassert> #include <Include/XalanAutoPtr.hpp> #include "STLHelper.hpp" AttributeListImpl::AttributeListImpl() : AttributeList(), m_AttributeVector(), m_cacheVector() { } AttributeListImpl::~AttributeListImpl() { // Clean up everything... clear(); assert(m_AttributeVector.empty() == true); deleteEntries(m_cacheVector); } AttributeListImpl::AttributeListImpl(const AttributeListImpl& theSource) : AttributeList(), m_AttributeVector() { // Use the assignment operator to do the dirty work... *this = theSource; assert(getLength() == theSource.getLength()); } AttributeListImpl::AttributeListImpl(const AttributeList& theSource) : AttributeList(), m_AttributeVector() { // Use the assignment operator to do the dirty work... *this = theSource; assert(getLength() == theSource.getLength()); } void AttributeListImpl::deleteEntries(AttributeVectorType& theVector) { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Delete all of the objects in the vector. for_each(theVector.begin(), theVector.end(), DeleteFunctor<AttributeVectorEntry>()); } AttributeListImpl& AttributeListImpl::operator=(const AttributeListImpl& theRHS) { if (this != &theRHS) { // Note that we can't chain up to our base class operator=() // because it's private. // Some temporary structures to hold everything // until we're done. AttributeVectorType tempVector; const unsigned int theLength = theRHS.getLength(); if (theLength > 0) { // Reserve the appropriate capacity right now... tempVector.reserve(theLength); // This will delete everything in tempVector when we're done... CollectionDeleteGuard<AttributeVectorType, DeleteFunctor<AttributeVectorEntry> > theGuard(tempVector); typedef AttributeVectorType::const_iterator const_iterator; const const_iterator theEnd = theRHS.m_AttributeVector.end(); // Copy the vector entries, and build the index map... for(const_iterator i = theRHS.m_AttributeVector.begin(); i != theEnd; ++i) { AttributeVectorEntry* const theEntry = *i; assert(theEntry != 0); // Add the item... tempVector.push_back( getNewEntry( &*theEntry->m_Name.begin(), &*theEntry->m_Type.begin(), &*theEntry->m_Value.begin())); } // OK, we're safe, so swap the contents of the // containers. This is guaranteed not to throw. m_AttributeVector.swap(tempVector); } assert(getLength() == theLength); } return *this; } AttributeListImpl& AttributeListImpl::operator=(const AttributeList& theRHS) { if (this != &theRHS) { // Note that we can't chain up to our base class operator=() // because it's private. // Add all of the attributes to this temp list, // then swap at the end. This means we're exception // safe and don't need any try blocks. AttributeListImpl theTempList; const unsigned int theLength = theRHS.getLength(); theTempList.reserve(theLength); // Add each attribute. for(unsigned int i = 0; i < theLength; i++) { theTempList.addAttribute( theRHS.getName(i), theRHS.getType(i), theRHS.getValue(i)); } // Now that the temp list is built, swap everything. This is // guaranteed not to throw. swap(theTempList); } return *this; } unsigned int AttributeListImpl::getLength() const { return m_AttributeVector.size(); } const XMLCh* AttributeListImpl::getName(const unsigned int index) const { assert(index < getLength()); return &*m_AttributeVector[index]->m_Name.begin(); } const XMLCh* AttributeListImpl::getType(const unsigned int index) const { assert(index < getLength()); return &*m_AttributeVector[index]->m_Type.begin(); } const XMLCh* AttributeListImpl::getValue(const unsigned int index) const { assert(index < getLength()); return &*m_AttributeVector[index]->m_Value.begin(); } struct NameCompareFunctor { NameCompareFunctor(const XMLCh* theName) : m_name(theName) { } bool operator()(const AttributeListImpl::AttributeVectorEntry* theEntry) const { return equals(&*theEntry->m_Name.begin(), m_name); } private: const XMLCh* const m_name; }; const XMLCh* AttributeListImpl::getType(const XMLCh* const name) const { assert(name != 0); #if !defined(XALAN_NO_NAMESPACES) using std::find_if; #endif const AttributeVectorType::const_iterator i = find_if( m_AttributeVector.begin(), m_AttributeVector.end(), NameCompareFunctor(name)); if (i != m_AttributeVector.end()) { // Found it, so return a pointer to the type. return &*(*i)->m_Type.begin(); } else { return 0; } } const XMLCh* AttributeListImpl::getValue(const char* const name) const { return getValue(&*MakeXalanDOMCharVector(name).begin()); } const XMLCh* AttributeListImpl::getValue(const XMLCh* const name) const { assert(name != 0); #if !defined(XALAN_NO_NAMESPACES) using std::find_if; #endif const AttributeVectorType::const_iterator i = find_if( m_AttributeVector.begin(), m_AttributeVector.end(), NameCompareFunctor(name)); if (i != m_AttributeVector.end()) { // Found it, so return a pointer to the value. return &*(*i)->m_Value.begin(); } else { return 0; } } void AttributeListImpl::clear() { m_cacheVector.insert(m_cacheVector.end(), m_AttributeVector.begin(), m_AttributeVector.end()); // Clear everything out. m_AttributeVector.clear(); } // A convenience function to find the length of a null-terminated // array of XMLChs inline const XMLCh* endArray(const XMLCh* data) { assert(data != 0); while(*data) { ++data; } return data; } bool AttributeListImpl::addAttribute( const XMLCh* name, const XMLCh* type, const XMLCh* value) { assert(name != 0); assert(type != 0); assert(value != 0); bool fResult = false; #if !defined(XALAN_NO_NAMESPACES) using std::find_if; using std::copy; #endif // Update the attribute, if it's already there... const AttributeVectorType::const_iterator i = find_if( m_AttributeVector.begin(), m_AttributeVector.end(), NameCompareFunctor(name)); if (i != m_AttributeVector.end()) { // This is a special optimization for type, since it's (almost) always "CDATA". if (equals(type, &*(*i)->m_Type.begin()) == false) { // If necessary, create the a new vector and swap them. Otherwise, // just copy the new data in. const XMLCh* const theNewTypeEnd = endArray(type) + 1; if ((*i)->m_Type.capacity() < XMLChVectorType::size_type(theNewTypeEnd - type)) { XMLChVectorType theNewType(type, theNewTypeEnd); theNewType.swap((*i)->m_Type); } else { copy(type, theNewTypeEnd, (*i)->m_Type.begin()); } } const XMLCh* const theNewValueEnd = endArray(value) + 1; // If necessary, create the a new vector and swap them. Otherwise, // just copy the new data in. if ((*i)->m_Value.capacity() < XMLChVectorType::size_type(theNewValueEnd - value)) { XMLChVectorType theNewValue(value, theNewValueEnd); theNewValue.swap((*i)->m_Value); } else { copy(value, theNewValueEnd, (*i)->m_Value.begin()); } } else { if (m_AttributeVector.capacity() == 0) { m_AttributeVector.reserve(eDefaultVectorSize); } XalanAutoPtr<AttributeVectorEntry> theEntry(getNewEntry(name, type, value)); // Add the new one. m_AttributeVector.push_back(theEntry.get()); // The entry is now safely in the vector, so release the // XalanAutoPtr... theEntry.release(); fResult = true; } return fResult; } AttributeListImpl::AttributeVectorEntry* AttributeListImpl::getNewEntry( const XMLCh* name, const XMLCh* type, const XMLCh* value) { if (m_cacheVector.size() == 0) { return new AttributeVectorEntry(name, value, type); } else { AttributeVectorEntry* const theEntry = m_cacheVector.back(); theEntry->clear(); assert(theEntry->m_Name.size() == 0 && theEntry->m_Value.size() == 0 && theEntry->m_Type.size() == 0); theEntry->m_Name.insert(theEntry->m_Name.begin(), name, endArray(name) + 1); theEntry->m_Value.insert(theEntry->m_Value.begin(), value, endArray(value) + 1); theEntry->m_Type.insert(theEntry->m_Type.begin(), type, endArray(type) + 1); m_cacheVector.pop_back(); return theEntry; } } bool AttributeListImpl::removeAttribute(const XMLCh* name) { assert(name != 0); #if !defined(XALAN_NO_NAMESPACES) using std::find_if; #endif bool fResult = false; // Update the attribute, if it's already there... const AttributeVectorType::iterator i = find_if( m_AttributeVector.begin(), m_AttributeVector.end(), NameCompareFunctor(name)); if (i != m_AttributeVector.end()) { m_cacheVector.push_back(*i); m_AttributeVector.erase(i); fResult = true; } return fResult; } <|endoftext|>