text
stringlengths
54
60.6k
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "FizzContextProvider.h" #include <fizz/client/FizzClientContext.h> #include <fizz/client/SynchronizedLruPskCache.h> #include <fizz/protocol/DefaultCertificateVerifier.h> #include <fizz/server/FizzServerContext.h> #include <fizz/server/TicketCodec.h> #include <fizz/server/TicketTypes.h> #include <folly/Singleton.h> #include <folly/ssl/Init.h> #include "mcrouter/lib/fbi/cpp/LogFailure.h" namespace facebook { namespace memcache { namespace { void initSSL() { static folly::once_flag flag; folly::call_once(flag, [&]() { folly::ssl::init(); }); } /* Sessions are valid for upto 24 hours */ constexpr size_t kSessionLifeTime = 86400; /* Handshakes are valid for up to 1 week */ constexpr size_t kHandshakeValidity = 604800; } // namespace FizzContextAndVerifier createClientFizzContextAndVerifier( std::string certData, std::string keyData, folly::StringPiece pemCaPath, bool preferOcbCipher) { // global session cache static auto SESSION_CACHE = std::make_shared<fizz::client::SynchronizedLruPskCache>(100); initSSL(); auto ctx = std::make_shared<fizz::client::FizzClientContext>(); ctx->setSupportedVersions({fizz::ProtocolVersion::tls_1_3}); ctx->setPskCache(SESSION_CACHE); if (!certData.empty() && !keyData.empty()) { auto cert = fizz::CertUtils::makeSelfCert(std::move(certData), std::move(keyData)); ctx->setClientCertificate(std::move(cert)); } std::shared_ptr<fizz::DefaultCertificateVerifier> verifier; if (!pemCaPath.empty()) { verifier = fizz::DefaultCertificateVerifier::createFromCAFile( fizz::VerificationContext::Client, pemCaPath.str()); } if (preferOcbCipher) { #if FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_OCB) auto ciphers = folly::copy(ctx->getSupportedCiphers()); ciphers.insert( ciphers.begin(), fizz::CipherSuite::TLS_AES_128_OCB_SHA256_EXPERIMENTAL); ctx->setSupportedCiphers(std::move(ciphers)); #endif } return FizzContextAndVerifier(std::move(ctx), std::move(verifier)); } std::shared_ptr<fizz::server::FizzServerContext> createFizzServerContext( folly::StringPiece pemCertPath, folly::StringPiece certData, folly::StringPiece pemKeyPath, folly::StringPiece keyData, folly::StringPiece pemCaPath, bool requireClientVerification, bool preferOcbCipher, wangle::TLSTicketKeySeeds* ticketKeySeeds) { initSSL(); auto certMgr = std::make_unique<fizz::server::CertManager>(); try { auto selfCert = fizz::CertUtils::makeSelfCert(certData.str(), keyData.str()); // add the default cert certMgr->addCert(std::move(selfCert), true); } catch (const std::exception& ex) { LOG_FAILURE( "SSLCert", failure::Category::kBadEnvironment, "Failed to create self cert from \"{}\" and \"{}\". ex: {}", pemCertPath, pemKeyPath, ex.what()); return nullptr; } auto ctx = std::make_shared<fizz::server::FizzServerContext>(); ctx->setSupportedVersions({fizz::ProtocolVersion::tls_1_3}); ctx->setSupportedPskModes( {fizz::PskKeyExchangeMode::psk_ke, fizz::PskKeyExchangeMode::psk_dhe_ke}); ctx->setVersionFallbackEnabled(true); ctx->setCertManager(std::move(certMgr)); if (!pemCaPath.empty()) { auto verifier = fizz::DefaultCertificateVerifier::createFromCAFile( fizz::VerificationContext::Server, pemCaPath.str()); ctx->setClientCertVerifier(std::move(verifier)); ctx->setClientAuthMode(fizz::server::ClientAuthMode::Optional); } if (requireClientVerification) { ctx->setClientAuthMode(fizz::server::ClientAuthMode::Required); } if (preferOcbCipher) { #if FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_OCB) auto serverCiphers = folly::copy(ctx->getSupportedCiphers()); serverCiphers.insert( serverCiphers.begin(), { fizz::CipherSuite::TLS_AES_128_OCB_SHA256_EXPERIMENTAL, }); ctx->setSupportedCiphers(std::move(serverCiphers)); #endif } // set ticket seeds if (ticketKeySeeds) { std::vector<folly::ByteRange> ticketSecrets; for (const auto& secret : ticketKeySeeds->currentSeeds) { ticketSecrets.push_back(folly::StringPiece(secret)); } for (const auto& secret : ticketKeySeeds->oldSeeds) { ticketSecrets.push_back(folly::StringPiece(secret)); } for (const auto& secret : ticketKeySeeds->newSeeds) { ticketSecrets.push_back(folly::StringPiece(secret)); } auto cipher = std::make_shared<fizz::server::AES128TicketCipher>(); cipher->setTicketSecrets(std::move(ticketSecrets)); cipher->setTicketValidity(std::chrono::seconds(kSessionLifeTime)); cipher->setHandshakeValidity(std::chrono::seconds(kHandshakeValidity)); ctx->setTicketCipher(std::move(cipher)); } // TODO: allow for custom FizzFactory return ctx; } } // namespace memcache } // namespace facebook <commit_msg>Refactoring AeadTicketCipher to use TicketPolicy instead of tracking time directly<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "FizzContextProvider.h" #include <fizz/client/FizzClientContext.h> #include <fizz/client/SynchronizedLruPskCache.h> #include <fizz/protocol/DefaultCertificateVerifier.h> #include <fizz/server/FizzServerContext.h> #include <fizz/server/TicketCodec.h> #include <fizz/server/TicketTypes.h> #include <folly/Singleton.h> #include <folly/ssl/Init.h> #include "mcrouter/lib/fbi/cpp/LogFailure.h" namespace facebook { namespace memcache { namespace { void initSSL() { static folly::once_flag flag; folly::call_once(flag, [&]() { folly::ssl::init(); }); } /* Sessions are valid for upto 24 hours */ constexpr size_t kSessionLifeTime = 86400; /* Handshakes are valid for up to 1 week */ constexpr size_t kHandshakeValidity = 604800; } // namespace FizzContextAndVerifier createClientFizzContextAndVerifier( std::string certData, std::string keyData, folly::StringPiece pemCaPath, bool preferOcbCipher) { // global session cache static auto SESSION_CACHE = std::make_shared<fizz::client::SynchronizedLruPskCache>(100); initSSL(); auto ctx = std::make_shared<fizz::client::FizzClientContext>(); ctx->setSupportedVersions({fizz::ProtocolVersion::tls_1_3}); ctx->setPskCache(SESSION_CACHE); if (!certData.empty() && !keyData.empty()) { auto cert = fizz::CertUtils::makeSelfCert(std::move(certData), std::move(keyData)); ctx->setClientCertificate(std::move(cert)); } std::shared_ptr<fizz::DefaultCertificateVerifier> verifier; if (!pemCaPath.empty()) { verifier = fizz::DefaultCertificateVerifier::createFromCAFile( fizz::VerificationContext::Client, pemCaPath.str()); } if (preferOcbCipher) { #if FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_OCB) auto ciphers = folly::copy(ctx->getSupportedCiphers()); ciphers.insert( ciphers.begin(), fizz::CipherSuite::TLS_AES_128_OCB_SHA256_EXPERIMENTAL); ctx->setSupportedCiphers(std::move(ciphers)); #endif } return FizzContextAndVerifier(std::move(ctx), std::move(verifier)); } std::shared_ptr<fizz::server::FizzServerContext> createFizzServerContext( folly::StringPiece pemCertPath, folly::StringPiece certData, folly::StringPiece pemKeyPath, folly::StringPiece keyData, folly::StringPiece pemCaPath, bool requireClientVerification, bool preferOcbCipher, wangle::TLSTicketKeySeeds* ticketKeySeeds) { initSSL(); auto certMgr = std::make_unique<fizz::server::CertManager>(); try { auto selfCert = fizz::CertUtils::makeSelfCert(certData.str(), keyData.str()); // add the default cert certMgr->addCert(std::move(selfCert), true); } catch (const std::exception& ex) { LOG_FAILURE( "SSLCert", failure::Category::kBadEnvironment, "Failed to create self cert from \"{}\" and \"{}\". ex: {}", pemCertPath, pemKeyPath, ex.what()); return nullptr; } auto ctx = std::make_shared<fizz::server::FizzServerContext>(); ctx->setSupportedVersions({fizz::ProtocolVersion::tls_1_3}); ctx->setSupportedPskModes( {fizz::PskKeyExchangeMode::psk_ke, fizz::PskKeyExchangeMode::psk_dhe_ke}); ctx->setVersionFallbackEnabled(true); ctx->setCertManager(std::move(certMgr)); if (!pemCaPath.empty()) { auto verifier = fizz::DefaultCertificateVerifier::createFromCAFile( fizz::VerificationContext::Server, pemCaPath.str()); ctx->setClientCertVerifier(std::move(verifier)); ctx->setClientAuthMode(fizz::server::ClientAuthMode::Optional); } if (requireClientVerification) { ctx->setClientAuthMode(fizz::server::ClientAuthMode::Required); } if (preferOcbCipher) { #if FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_OCB) auto serverCiphers = folly::copy(ctx->getSupportedCiphers()); serverCiphers.insert( serverCiphers.begin(), { fizz::CipherSuite::TLS_AES_128_OCB_SHA256_EXPERIMENTAL, }); ctx->setSupportedCiphers(std::move(serverCiphers)); #endif } // set ticket seeds if (ticketKeySeeds) { std::vector<folly::ByteRange> ticketSecrets; for (const auto& secret : ticketKeySeeds->currentSeeds) { ticketSecrets.push_back(folly::StringPiece(secret)); } for (const auto& secret : ticketKeySeeds->oldSeeds) { ticketSecrets.push_back(folly::StringPiece(secret)); } for (const auto& secret : ticketKeySeeds->newSeeds) { ticketSecrets.push_back(folly::StringPiece(secret)); } auto cipher = std::make_shared<fizz::server::AES128TicketCipher>(); cipher->setTicketSecrets(std::move(ticketSecrets)); fizz::server::TicketPolicy policy; policy.setTicketValidity(std::chrono::seconds(kSessionLifeTime)); policy.setHandshakeValidity(std::chrono::seconds(kHandshakeValidity)); cipher->setPolicy(std::move(policy)); ctx->setTicketCipher(std::move(cipher)); } // TODO: allow for custom FizzFactory return ctx; } } // namespace memcache } // namespace facebook <|endoftext|>
<commit_before>#include <algorithm> #include "EntityManager.h" #include "EntityType.h" #include "components/debug/Debug.h" template <typename T> int EntityManager::EntityGroup<T>::getCount() const { return static_cast<int>(this->indices.size()); } template <typename T> T *EntityManager::EntityGroup<T>::getEntityAtIndex(int index) { DebugAssert(this->validEntities.size() == this->entities.size()); DebugAssertIndex(this->validEntities, index); const bool isValid = this->validEntities[index]; return isValid ? &this->entities[index] : nullptr; } template <typename T> const T *EntityManager::EntityGroup<T>::getEntityAtIndex(int index) const { DebugAssert(this->validEntities.size() == this->entities.size()); DebugAssertIndex(this->validEntities, index); const bool isValid = this->validEntities[index]; return isValid ? &this->entities[index] : nullptr; } template <typename T> int EntityManager::EntityGroup<T>::getEntities(Entity **outEntities, int outSize) { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); DebugAssert(this->validEntities.size() == this->entities.size()); int writeIndex = 0; const int count = this->getCount(); for (int i = 0; i < count; i++) { // Break if the destination buffer is full. if (writeIndex == outSize) { break; } DebugAssertIndex(this->validEntities, i); const bool isValid = this->validEntities[i]; // Skip if entity is not valid. if (!isValid) { continue; } T &entity = this->entities[i]; outEntities[writeIndex] = &entity; writeIndex++; } return writeIndex; } template <typename T> int EntityManager::EntityGroup<T>::getEntities(const Entity **outEntities, int outSize) const { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); DebugAssert(this->validEntities.size() == this->entities.size()); int writeIndex = 0; const int count = this->getCount(); for (int i = 0; i < count; i++) { // Break if the destination buffer is full. if (writeIndex == outSize) { break; } DebugAssertIndex(this->validEntities, i); const bool isValid = this->validEntities[i]; // Skip if entity is not valid. if (!isValid) { continue; } const T &entity = this->entities[i]; outEntities[writeIndex] = &entity; writeIndex++; } return writeIndex; } template <typename T> std::optional<int> EntityManager::EntityGroup<T>::getEntityIndex(int id) const { const auto iter = this->indices.find(id); if (iter != this->indices.end()) { return iter->second; } else { return std::nullopt; } } template <typename T> T *EntityManager::EntityGroup<T>::addEntity(int id) { DebugAssert(id != EntityManager::NO_ID); DebugAssert(this->validEntities.size() == this->entities.size()); // Entity ID must not already be in use. DebugAssert(!this->getEntityIndex(id).has_value()); // Find available position in entities array. int index; if (this->freeIndices.size() > 0) { // Reuse a previously-owned entity slot. index = this->freeIndices.back(); this->freeIndices.pop_back(); DebugAssertIndex(this->validEntities, index); this->validEntities[index] = true; } else { // Insert new at the end of the entities list. index = static_cast<int>(this->entities.size()); this->entities.push_back(T()); this->validEntities.push_back(true); } // Initialize basic entity data. DebugAssertIndex(this->entities, index); T &entitySlot = this->entities[index]; entitySlot.reset(); entitySlot.setID(id); // Insert into ID -> entity index table. this->indices.insert(std::make_pair(id, index)); return &entitySlot; } template <typename T> void EntityManager::EntityGroup<T>::remove(int id) { DebugAssert(id != EntityManager::NO_ID); DebugAssert(this->validEntities.size() == this->entities.size()); // Find entity with the given ID. const std::optional<int> optIndex = this->getEntityIndex(id); if (optIndex.has_value()) { const int index = optIndex.value(); // Clear entity slot. DebugAssertIndex(this->entities, index); this->entities[index].reset(); this->validEntities[index] = false; // Clear ID mapping. this->indices.erase(id); // Add ID to previously-owned IDs list. this->freeIndices.push_back(id); } else { // Not in entity group. DebugLogWarning("Tried to remove missing entity \"" + std::to_string(id) + "\"."); } } template <typename T> void EntityManager::EntityGroup<T>::clear() { this->entities.clear(); this->validEntities.clear(); this->indices.clear(); this->freeIndices.clear(); } const int EntityManager::NO_ID = -1; EntityManager::EntityManager() { this->nextID = 0; } int EntityManager::nextFreeID() { // Check if any pre-owned entity IDs are available. if (this->freeIDs.size() > 0) { const int id = this->freeIDs.back(); this->freeIDs.pop_back(); return id; } else { // Get the next available ID. const int id = this->nextID; this->nextID++; return id; } } Doodad *EntityManager::makeDoodad() { const int id = this->nextFreeID(); Doodad *doodad = this->doodads.addEntity(id); DebugAssert(doodad->getID() == id); return doodad; } NonPlayer *EntityManager::makeNPC() { const int id = this->nextFreeID(); NonPlayer *npc = this->npcs.addEntity(id); DebugAssert(npc->getID() == id); return npc; } Entity *EntityManager::get(int id) { // Find which entity group the given ID is in. std::optional<int> entityIndex = this->npcs.getEntityIndex(id); if (entityIndex.has_value()) { // NPC. return this->npcs.getEntityAtIndex(entityIndex.value()); } entityIndex = this->doodads.getEntityIndex(id); if (entityIndex.has_value()) { // Doodad. return this->doodads.getEntityAtIndex(entityIndex.value()); } // Not in any entity group. return nullptr; } const Entity *EntityManager::get(int id) const { // Find which entity group the given ID is in. std::optional<int> entityIndex = this->npcs.getEntityIndex(id); if (entityIndex.has_value()) { // NPC. return this->npcs.getEntityAtIndex(entityIndex.value()); } entityIndex = this->doodads.getEntityIndex(id); if (entityIndex.has_value()) { // Doodad. return this->doodads.getEntityAtIndex(entityIndex.value()); } // Not in any entity group. return nullptr; } int EntityManager::getCount(EntityType entityType) const { switch (entityType) { case EntityType::NonPlayer: return this->npcs.getCount(); case EntityType::Doodad: return this->doodads.getCount(); default: DebugUnhandledReturnMsg(int, std::to_string(static_cast<int>(entityType))); } } int EntityManager::getTotalCount() const { return this->npcs.getCount() + this->doodads.getCount(); } int EntityManager::getEntities(EntityType entityType, Entity **outEntities, int outSize) { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); // Get entities from the desired type. switch (entityType) { case EntityType::NonPlayer: return this->npcs.getEntities(outEntities, outSize); case EntityType::Doodad: return this->doodads.getEntities(outEntities, outSize); default: DebugUnhandledReturnMsg(int, std::to_string(static_cast<int>(entityType))); } } int EntityManager::getEntities(EntityType entityType, const Entity **outEntities, int outSize) const { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); // Get entities from the desired type. switch (entityType) { case EntityType::NonPlayer: return this->npcs.getEntities(outEntities, outSize); case EntityType::Doodad: return this->doodads.getEntities(outEntities, outSize); default: DebugUnhandledReturnMsg(int, std::to_string(static_cast<int>(entityType))); } } int EntityManager::getTotalEntities(const Entity **outEntities, int outSize) const { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); // Fill the output buffer with as many entities as will fit. int writeIndex = 0; auto tryWriteEntities = [outEntities, outSize, &writeIndex](const auto &entityGroup) { const int entityCount = entityGroup.getCount(); for (int i = 0; i < entityCount; i++) { // Break if the output buffer is full. if (writeIndex == outSize) { break; } outEntities[writeIndex] = entityGroup.getEntityAtIndex(i); writeIndex++; } }; tryWriteEntities(this->npcs); tryWriteEntities(this->doodads); return writeIndex; } void EntityManager::remove(int id) { // Find which entity group the given ID is in. std::optional<int> entityIndex = this->npcs.getEntityIndex(id); if (entityIndex.has_value()) { // NPC. this->npcs.remove(id); // Insert entity ID into the free list. this->freeIDs.push_back(id); return; } entityIndex = this->doodads.getEntityIndex(id); if (entityIndex.has_value()) { // Doodad. this->doodads.remove(id); // Insert entity ID into the free list. this->freeIDs.push_back(id); return; } // Not in any entity group. DebugLogWarning("Tried to remove missing entity \"" + std::to_string(id) + "\"."); } void EntityManager::clear() { this->npcs.clear(); this->doodads.clear(); this->freeIDs.clear(); this->nextID = 0; } <commit_msg>Fixed index value given to freeIndices list.<commit_after>#include <algorithm> #include "EntityManager.h" #include "EntityType.h" #include "components/debug/Debug.h" template <typename T> int EntityManager::EntityGroup<T>::getCount() const { return static_cast<int>(this->indices.size()); } template <typename T> T *EntityManager::EntityGroup<T>::getEntityAtIndex(int index) { DebugAssert(this->validEntities.size() == this->entities.size()); DebugAssertIndex(this->validEntities, index); const bool isValid = this->validEntities[index]; return isValid ? &this->entities[index] : nullptr; } template <typename T> const T *EntityManager::EntityGroup<T>::getEntityAtIndex(int index) const { DebugAssert(this->validEntities.size() == this->entities.size()); DebugAssertIndex(this->validEntities, index); const bool isValid = this->validEntities[index]; return isValid ? &this->entities[index] : nullptr; } template <typename T> int EntityManager::EntityGroup<T>::getEntities(Entity **outEntities, int outSize) { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); DebugAssert(this->validEntities.size() == this->entities.size()); int writeIndex = 0; const int count = this->getCount(); for (int i = 0; i < count; i++) { // Break if the destination buffer is full. if (writeIndex == outSize) { break; } DebugAssertIndex(this->validEntities, i); const bool isValid = this->validEntities[i]; // Skip if entity is not valid. if (!isValid) { continue; } T &entity = this->entities[i]; outEntities[writeIndex] = &entity; writeIndex++; } return writeIndex; } template <typename T> int EntityManager::EntityGroup<T>::getEntities(const Entity **outEntities, int outSize) const { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); DebugAssert(this->validEntities.size() == this->entities.size()); int writeIndex = 0; const int count = this->getCount(); for (int i = 0; i < count; i++) { // Break if the destination buffer is full. if (writeIndex == outSize) { break; } DebugAssertIndex(this->validEntities, i); const bool isValid = this->validEntities[i]; // Skip if entity is not valid. if (!isValid) { continue; } const T &entity = this->entities[i]; outEntities[writeIndex] = &entity; writeIndex++; } return writeIndex; } template <typename T> std::optional<int> EntityManager::EntityGroup<T>::getEntityIndex(int id) const { const auto iter = this->indices.find(id); if (iter != this->indices.end()) { return iter->second; } else { return std::nullopt; } } template <typename T> T *EntityManager::EntityGroup<T>::addEntity(int id) { DebugAssert(id != EntityManager::NO_ID); DebugAssert(this->validEntities.size() == this->entities.size()); // Entity ID must not already be in use. DebugAssert(!this->getEntityIndex(id).has_value()); // Find available position in entities array. int index; if (this->freeIndices.size() > 0) { // Reuse a previously-owned entity slot. index = this->freeIndices.back(); this->freeIndices.pop_back(); DebugAssertIndex(this->validEntities, index); this->validEntities[index] = true; } else { // Insert new at the end of the entities list. index = static_cast<int>(this->entities.size()); this->entities.push_back(T()); this->validEntities.push_back(true); } // Initialize basic entity data. DebugAssertIndex(this->entities, index); T &entitySlot = this->entities[index]; entitySlot.reset(); entitySlot.setID(id); // Insert into ID -> entity index table. this->indices.insert(std::make_pair(id, index)); return &entitySlot; } template <typename T> void EntityManager::EntityGroup<T>::remove(int id) { DebugAssert(id != EntityManager::NO_ID); DebugAssert(this->validEntities.size() == this->entities.size()); // Find entity with the given ID. const std::optional<int> optIndex = this->getEntityIndex(id); if (optIndex.has_value()) { const int index = optIndex.value(); // Clear entity slot. DebugAssertIndex(this->entities, index); this->entities[index].reset(); this->validEntities[index] = false; // Clear ID mapping. this->indices.erase(id); // Add entity index to previously-owned slots list. this->freeIndices.push_back(index); } else { // Not in entity group. DebugLogWarning("Tried to remove missing entity \"" + std::to_string(id) + "\"."); } } template <typename T> void EntityManager::EntityGroup<T>::clear() { this->entities.clear(); this->validEntities.clear(); this->indices.clear(); this->freeIndices.clear(); } const int EntityManager::NO_ID = -1; EntityManager::EntityManager() { this->nextID = 0; } int EntityManager::nextFreeID() { // Check if any pre-owned entity IDs are available. if (this->freeIDs.size() > 0) { const int id = this->freeIDs.back(); this->freeIDs.pop_back(); return id; } else { // Get the next available ID. const int id = this->nextID; this->nextID++; return id; } } Doodad *EntityManager::makeDoodad() { const int id = this->nextFreeID(); Doodad *doodad = this->doodads.addEntity(id); DebugAssert(doodad->getID() == id); return doodad; } NonPlayer *EntityManager::makeNPC() { const int id = this->nextFreeID(); NonPlayer *npc = this->npcs.addEntity(id); DebugAssert(npc->getID() == id); return npc; } Entity *EntityManager::get(int id) { // Find which entity group the given ID is in. std::optional<int> entityIndex = this->npcs.getEntityIndex(id); if (entityIndex.has_value()) { // NPC. return this->npcs.getEntityAtIndex(entityIndex.value()); } entityIndex = this->doodads.getEntityIndex(id); if (entityIndex.has_value()) { // Doodad. return this->doodads.getEntityAtIndex(entityIndex.value()); } // Not in any entity group. return nullptr; } const Entity *EntityManager::get(int id) const { // Find which entity group the given ID is in. std::optional<int> entityIndex = this->npcs.getEntityIndex(id); if (entityIndex.has_value()) { // NPC. return this->npcs.getEntityAtIndex(entityIndex.value()); } entityIndex = this->doodads.getEntityIndex(id); if (entityIndex.has_value()) { // Doodad. return this->doodads.getEntityAtIndex(entityIndex.value()); } // Not in any entity group. return nullptr; } int EntityManager::getCount(EntityType entityType) const { switch (entityType) { case EntityType::NonPlayer: return this->npcs.getCount(); case EntityType::Doodad: return this->doodads.getCount(); default: DebugUnhandledReturnMsg(int, std::to_string(static_cast<int>(entityType))); } } int EntityManager::getTotalCount() const { return this->npcs.getCount() + this->doodads.getCount(); } int EntityManager::getEntities(EntityType entityType, Entity **outEntities, int outSize) { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); // Get entities from the desired type. switch (entityType) { case EntityType::NonPlayer: return this->npcs.getEntities(outEntities, outSize); case EntityType::Doodad: return this->doodads.getEntities(outEntities, outSize); default: DebugUnhandledReturnMsg(int, std::to_string(static_cast<int>(entityType))); } } int EntityManager::getEntities(EntityType entityType, const Entity **outEntities, int outSize) const { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); // Get entities from the desired type. switch (entityType) { case EntityType::NonPlayer: return this->npcs.getEntities(outEntities, outSize); case EntityType::Doodad: return this->doodads.getEntities(outEntities, outSize); default: DebugUnhandledReturnMsg(int, std::to_string(static_cast<int>(entityType))); } } int EntityManager::getTotalEntities(const Entity **outEntities, int outSize) const { DebugAssert(outEntities != nullptr); DebugAssert(outSize >= 0); // Fill the output buffer with as many entities as will fit. int writeIndex = 0; auto tryWriteEntities = [outEntities, outSize, &writeIndex](const auto &entityGroup) { const int entityCount = entityGroup.getCount(); for (int i = 0; i < entityCount; i++) { // Break if the output buffer is full. if (writeIndex == outSize) { break; } outEntities[writeIndex] = entityGroup.getEntityAtIndex(i); writeIndex++; } }; tryWriteEntities(this->npcs); tryWriteEntities(this->doodads); return writeIndex; } void EntityManager::remove(int id) { // Find which entity group the given ID is in. std::optional<int> entityIndex = this->npcs.getEntityIndex(id); if (entityIndex.has_value()) { // NPC. this->npcs.remove(id); // Insert entity ID into the free list. this->freeIDs.push_back(id); return; } entityIndex = this->doodads.getEntityIndex(id); if (entityIndex.has_value()) { // Doodad. this->doodads.remove(id); // Insert entity ID into the free list. this->freeIDs.push_back(id); return; } // Not in any entity group. DebugLogWarning("Tried to remove missing entity \"" + std::to_string(id) + "\"."); } void EntityManager::clear() { this->npcs.clear(); this->doodads.clear(); this->freeIDs.clear(); this->nextID = 0; } <|endoftext|>
<commit_before>#include "oddlib/path.hpp" #include "oddlib/stream.hpp" #include "logger.hpp" #include <array> namespace Oddlib { void Path::Point16::Read(IStream& stream) { stream.Read(mX); stream.Read(mY); } void Path::Links::Read(IStream& stream) { stream.Read(mPrevious); stream.Read(mNext); } void Path::CollisionItem::Read(IStream& stream) { mP1.Read(stream); mP2.Read(stream); stream.Read(mType); mLinks[0].Read(stream); mLinks[1].Read(stream); stream.Read(mLineLength); } Path::Path( IStream& pathChunkStream, u32 collisionDataOffset, u32 objectIndexTableOffset, u32 objectDataOffset, u32 mapXSize, u32 mapYSize, bool isAo) : mXSize(mapXSize), mYSize(mapYSize), mIsAo(isAo) { TRACE_ENTRYEXIT; ReadCameraMap(pathChunkStream); if (collisionDataOffset != 0) { //pathChunkStream.BinaryDump("PATH.DUMP"); assert(pathChunkStream.Pos()+16 == collisionDataOffset); } // TODO: Psx data != pc data for Ao const u32 indexTableOffset = (pathChunkStream.Size() - (mCameras.size() * sizeof(u32))) + 16; assert(indexTableOffset == objectIndexTableOffset); if (collisionDataOffset != 0) { const u32 numCollisionDataBytes = objectDataOffset - collisionDataOffset; const u32 numCollisionItems = numCollisionDataBytes / kCollisionItemSize; ReadCollisionItems(pathChunkStream, numCollisionItems); ReadMapObjects(pathChunkStream, objectIndexTableOffset); } } u32 Path::XSize() const { return mXSize; } u32 Path::YSize() const { return mYSize; } const Path::Camera& Path::CameraByPosition(u32 x, u32 y) const { if (x >= XSize() || y >= YSize()) { LOG_ERROR("Out of bounds x:y" << std::to_string(x) << " " << std::to_string(y) <<" vs " << std::to_string(XSize()) << " " << std::to_string(YSize())); } return mCameras[(y * XSize()) + x]; } void Path::ReadCameraMap(IStream& stream) { const u32 numberOfCameras = XSize() * YSize(); mCameras.reserve(numberOfCameras); std::array<u8, 8> nameBuffer; for (u32 i = 0; i < numberOfCameras; i++) { stream.Read(nameBuffer); std::string tmpStr(reinterpret_cast<const char*>(nameBuffer.data()), nameBuffer.size()); if (tmpStr[0] != 0) { tmpStr += ".CAM"; } mCameras.emplace_back(Camera(std::move(tmpStr))); } } void Path::ReadCollisionItems(IStream& stream, u32 numberOfCollisionItems) { mCollisionItems.resize(numberOfCollisionItems); for (u32 i = 0; i < numberOfCollisionItems; i++) { mCollisionItems[i].Read(stream); } } void Path::ReadMapObjects(IStream& stream, u32 objectIndexTableOffset) { const size_t collisionEnd = stream.Pos(); // TODO -16 is for the chunk header, probably shouldn't have this already included in the // pathdb, may also apply to collision info stream.Seek(objectIndexTableOffset-16); // Read the pointers to the object list for each camera const u32 numberOfCameras = XSize() * YSize(); std::vector<u32> cameraObjectOffsets; cameraObjectOffsets.reserve(numberOfCameras); for (u32 i = 0; i < numberOfCameras; i++) { u32 offset = 0; stream.Read(offset); cameraObjectOffsets.push_back(offset); } // Now load the objects for each camera for (auto i = 0u; i < cameraObjectOffsets.size(); i++) { // If max u32/-1 then it means there are no objects for this camera const auto objectsOffset = cameraObjectOffsets[i]; if (objectsOffset != 0xFFFFFFFF) { stream.Seek(collisionEnd + objectsOffset); for (;;) { MapObject mapObject; stream.Read(mapObject.mFlags); stream.Read(mapObject.mLength); stream.Read(mapObject.mType); LOG_INFO("Object TLV: " << mapObject.mType << " " << mapObject.mLength << " " << mapObject.mLength); if (mIsAo) { // Don't know what this is for u32 unknownData = 0; stream.Read(unknownData); } stream.Read(mapObject.mRectTopLeft.mX); stream.Read(mapObject.mRectTopLeft.mY); // Ao duplicated the first two parts of data for some reason if (mIsAo) { u32 duplicatedXY = 0; stream.Read(duplicatedXY); } stream.Read(mapObject.mRectBottomRight.mX); stream.Read(mapObject.mRectBottomRight.mY); if (mapObject.mLength > 0) { const u32 len = mapObject.mLength - (sizeof(u16) * (mIsAo ? 12 : 8)); if (len > 512) { LOG_ERROR("Map object data length " << mapObject.mLength << " is larger than fixed size"); abort(); } stream.ReadBytes(mapObject.mData.data(), len); } mCameras[i].mObjects.emplace_back(mapObject); if (mapObject.mFlags & 0x4) { break; } } } } } }<commit_msg>temp warning fix<commit_after>#include "oddlib/path.hpp" #include "oddlib/stream.hpp" #include "logger.hpp" #include <array> namespace Oddlib { void Path::Point16::Read(IStream& stream) { stream.Read(mX); stream.Read(mY); } void Path::Links::Read(IStream& stream) { stream.Read(mPrevious); stream.Read(mNext); } void Path::CollisionItem::Read(IStream& stream) { mP1.Read(stream); mP2.Read(stream); stream.Read(mType); mLinks[0].Read(stream); mLinks[1].Read(stream); stream.Read(mLineLength); } Path::Path( IStream& pathChunkStream, u32 collisionDataOffset, u32 objectIndexTableOffset, u32 objectDataOffset, u32 mapXSize, u32 mapYSize, bool isAo) : mXSize(mapXSize), mYSize(mapYSize), mIsAo(isAo) { TRACE_ENTRYEXIT; ReadCameraMap(pathChunkStream); if (collisionDataOffset != 0) { //pathChunkStream.BinaryDump("PATH.DUMP"); assert(pathChunkStream.Pos()+16 == collisionDataOffset); } // TODO: Psx data != pc data for Ao //const u32 indexTableOffset = (pathChunkStream.Size() - (mCameras.size() * sizeof(u32))) + 16; //assert(indexTableOffset == objectIndexTableOffset); if (collisionDataOffset != 0) { const u32 numCollisionDataBytes = objectDataOffset - collisionDataOffset; const u32 numCollisionItems = numCollisionDataBytes / kCollisionItemSize; ReadCollisionItems(pathChunkStream, numCollisionItems); ReadMapObjects(pathChunkStream, objectIndexTableOffset); } } u32 Path::XSize() const { return mXSize; } u32 Path::YSize() const { return mYSize; } const Path::Camera& Path::CameraByPosition(u32 x, u32 y) const { if (x >= XSize() || y >= YSize()) { LOG_ERROR("Out of bounds x:y" << std::to_string(x) << " " << std::to_string(y) <<" vs " << std::to_string(XSize()) << " " << std::to_string(YSize())); } return mCameras[(y * XSize()) + x]; } void Path::ReadCameraMap(IStream& stream) { const u32 numberOfCameras = XSize() * YSize(); mCameras.reserve(numberOfCameras); std::array<u8, 8> nameBuffer; for (u32 i = 0; i < numberOfCameras; i++) { stream.Read(nameBuffer); std::string tmpStr(reinterpret_cast<const char*>(nameBuffer.data()), nameBuffer.size()); if (tmpStr[0] != 0) { tmpStr += ".CAM"; } mCameras.emplace_back(Camera(std::move(tmpStr))); } } void Path::ReadCollisionItems(IStream& stream, u32 numberOfCollisionItems) { mCollisionItems.resize(numberOfCollisionItems); for (u32 i = 0; i < numberOfCollisionItems; i++) { mCollisionItems[i].Read(stream); } } void Path::ReadMapObjects(IStream& stream, u32 objectIndexTableOffset) { const size_t collisionEnd = stream.Pos(); // TODO -16 is for the chunk header, probably shouldn't have this already included in the // pathdb, may also apply to collision info stream.Seek(objectIndexTableOffset-16); // Read the pointers to the object list for each camera const u32 numberOfCameras = XSize() * YSize(); std::vector<u32> cameraObjectOffsets; cameraObjectOffsets.reserve(numberOfCameras); for (u32 i = 0; i < numberOfCameras; i++) { u32 offset = 0; stream.Read(offset); cameraObjectOffsets.push_back(offset); } // Now load the objects for each camera for (auto i = 0u; i < cameraObjectOffsets.size(); i++) { // If max u32/-1 then it means there are no objects for this camera const auto objectsOffset = cameraObjectOffsets[i]; if (objectsOffset != 0xFFFFFFFF) { stream.Seek(collisionEnd + objectsOffset); for (;;) { MapObject mapObject; stream.Read(mapObject.mFlags); stream.Read(mapObject.mLength); stream.Read(mapObject.mType); LOG_INFO("Object TLV: " << mapObject.mType << " " << mapObject.mLength << " " << mapObject.mLength); if (mIsAo) { // Don't know what this is for u32 unknownData = 0; stream.Read(unknownData); } stream.Read(mapObject.mRectTopLeft.mX); stream.Read(mapObject.mRectTopLeft.mY); // Ao duplicated the first two parts of data for some reason if (mIsAo) { u32 duplicatedXY = 0; stream.Read(duplicatedXY); } stream.Read(mapObject.mRectBottomRight.mX); stream.Read(mapObject.mRectBottomRight.mY); if (mapObject.mLength > 0) { const u32 len = mapObject.mLength - (sizeof(u16) * (mIsAo ? 12 : 8)); if (len > 512) { LOG_ERROR("Map object data length " << mapObject.mLength << " is larger than fixed size"); abort(); } stream.ReadBytes(mapObject.mData.data(), len); } mCameras[i].mObjects.emplace_back(mapObject); if (mapObject.mFlags & 0x4) { break; } } } } } }<|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. * **************************************************************************/ // root #include <TROOT.h> #include <TSystem.h> #include <TInterpreter.h> #include <TChain.h> #include <TFile.h> #include <Riostream.h> // analysis #include "AliAnalysisTaskParticleCorrelation.h" #include "AliAnalysisManager.h" #include "AliESDInputHandler.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliAnaMaker.h" #include "AliCaloTrackReader.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliAODHandler.h" #include "AliStack.h" #include "AliLog.h" ClassImp(AliAnalysisTaskParticleCorrelation) //////////////////////////////////////////////////////////////////////// AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(): AliAnalysisTaskSE(), fAna(0x0), fOutputContainer(0x0), fAODBranch(0x0), fConfigName(0) { // Default constructor } //_____________________________________________________ AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(const char* name): AliAnalysisTaskSE(name), fAna(0x0), fOutputContainer(0x0), fAODBranch(0x0), fConfigName("ConfigAnalysis") { // Default constructor DefineOutput(1, TList::Class()); } //_____________________________________________________ AliAnalysisTaskParticleCorrelation::~AliAnalysisTaskParticleCorrelation() { // Remove all pointers if(fOutputContainer){ fOutputContainer->Clear() ; delete fOutputContainer ; } } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() { // Create the output container if (fDebug > 1) printf("AnalysisTaskParticleCorrelation::CreateOutputData() \n"); //AODs fAODBranch = new TClonesArray("AliAODParticleCorrelation", 0); fAODBranch->SetName(fAna->GetAODBranchName()); AddAODBranch("TClonesArray", fAODBranch); fAna->SetAODBranch(fAODBranch); //Histograms container OpenFile(1); fOutputContainer = fAna->GetOutputContainer(); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::Init() { // Initialization if (fDebug > 1) printf("AnalysisTaskParticleCorrelation::Init() \n"); // Call configuration file if(fConfigName == ""){ fConfigName="ConfigAnalysis"; } AliInfo(Form("### Configuration file is %s.C ###", fConfigName.Data())); gROOT->LoadMacro(fConfigName+".C"); fAna = (AliAnaMaker*) gInterpreter->ProcessLine("ConfigAnalysis()"); if(!fAna) AliFatal("Analysis pointer not initialized, abort analysis!"); // Initialise analysis fAna->Init(); AliDebug(1,"End"); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::UserExec(Option_t */*option*/) { // Execute analysis for current event // if (fDebug > 1) printf("AnalysisTaskParticleCorrelation::Exec() \n"); //Get the type of data, check if type is correct Int_t datatype = fAna->GetReader()->GetDataType(); if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD && datatype != AliCaloTrackReader::kMC){ AliFatal("Wrong type of data"); return ; } fAna->GetReader()->SetInputEvent(InputEvent(), AODEvent(), MCEvent()); //Process event fAna->ProcessEvent((Int_t) Entry()); PostData(1, fOutputContainer); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::Terminate(Option_t */*option*/) { // Terminate analysis // AliDebug(1,"Do nothing in Terminate"); //fAna->Terminate(); } <commit_msg>provide adress of the pointer to new AOD branch, not the pointer itself Mihaela G.<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. * **************************************************************************/ // root #include <TROOT.h> #include <TSystem.h> #include <TInterpreter.h> #include <TChain.h> #include <TFile.h> #include <Riostream.h> // analysis #include "AliAnalysisTaskParticleCorrelation.h" #include "AliAnalysisManager.h" #include "AliESDInputHandler.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliAnaMaker.h" #include "AliCaloTrackReader.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliAODHandler.h" #include "AliStack.h" #include "AliLog.h" ClassImp(AliAnalysisTaskParticleCorrelation) //////////////////////////////////////////////////////////////////////// AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(): AliAnalysisTaskSE(), fAna(0x0), fOutputContainer(0x0), fAODBranch(0x0), fConfigName(0) { // Default constructor } //_____________________________________________________ AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(const char* name): AliAnalysisTaskSE(name), fAna(0x0), fOutputContainer(0x0), fAODBranch(0x0), fConfigName("ConfigAnalysis") { // Default constructor DefineOutput(1, TList::Class()); } //_____________________________________________________ AliAnalysisTaskParticleCorrelation::~AliAnalysisTaskParticleCorrelation() { // Remove all pointers if(fOutputContainer){ fOutputContainer->Clear() ; delete fOutputContainer ; } } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() { // Create the output container if (fDebug > 1) printf("AnalysisTaskParticleCorrelation::CreateOutputData() \n"); //AODs fAODBranch = new TClonesArray("AliAODParticleCorrelation", 0); fAODBranch->SetName(fAna->GetAODBranchName()); AddAODBranch("TClonesArray", &fAODBranch); fAna->SetAODBranch(fAODBranch); //Histograms container OpenFile(1); fOutputContainer = fAna->GetOutputContainer(); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::Init() { // Initialization if (fDebug > 1) printf("AnalysisTaskParticleCorrelation::Init() \n"); // Call configuration file if(fConfigName == ""){ fConfigName="ConfigAnalysis"; } AliInfo(Form("### Configuration file is %s.C ###", fConfigName.Data())); gROOT->LoadMacro(fConfigName+".C"); fAna = (AliAnaMaker*) gInterpreter->ProcessLine("ConfigAnalysis()"); if(!fAna) AliFatal("Analysis pointer not initialized, abort analysis!"); // Initialise analysis fAna->Init(); AliDebug(1,"End"); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::UserExec(Option_t */*option*/) { // Execute analysis for current event // if (fDebug > 1) printf("AnalysisTaskParticleCorrelation::Exec() \n"); //Get the type of data, check if type is correct Int_t datatype = fAna->GetReader()->GetDataType(); if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD && datatype != AliCaloTrackReader::kMC){ AliFatal("Wrong type of data"); return ; } fAna->GetReader()->SetInputEvent(InputEvent(), AODEvent(), MCEvent()); //Process event fAna->ProcessEvent((Int_t) Entry()); PostData(1, fOutputContainer); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::Terminate(Option_t */*option*/) { // Terminate analysis // AliDebug(1,"Do nothing in Terminate"); //fAna->Terminate(); } <|endoftext|>
<commit_before>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address [email protected]. * */ #include "src/operators/pm.h" #include <string.h> #include <string> #include <algorithm> #include <iterator> #include <sstream> #include <vector> #include <list> #include <memory> #include "src/operators/operator.h" #include "src/utils/acmp.h" #include "src/utils/string.h" namespace modsecurity { namespace operators { Pm::~Pm() { acmp_node_t *root = m_p->root_node; acmp_node_t *node = root; cleanup(root); free(m_p); m_p = NULL; #ifdef MODSEC_MUTEX_ON_PM pthread_mutex_destroy(&m_lock); #endif } void Pm::cleanup(acmp_node_t *n) { if (n == NULL) { return; } cleanup(n->sibling); cleanup(n->child); postOrderTraversal(n->btree); if (n->text && strlen(n->text) > 0) { free(n->text); n->text = NULL; } if (n->pattern && strlen(n->pattern) > 0) { free(n->pattern); n->pattern = NULL; } free(n); } void Pm::postOrderTraversal(acmp_btree_node_t *node) { if (node == NULL) { return; } postOrderTraversal(node->right); postOrderTraversal(node->left); free(node); } bool Pm::evaluate(Transaction *transaction, Rule *rule, const std::string &input, std::shared_ptr<RuleMessage> ruleMessage) { int rc = -1; ACMPT pt; pt.parser = m_p; pt.ptr = NULL; const char *match = NULL; #ifdef MODSEC_MUTEX_ON_PM pthread_mutex_lock(&m_lock); #endif rc = acmp_process_quick(&pt, &match, input.c_str(), input.length()); #ifdef MODSEC_MUTEX_ON_PM pthread_mutex_unlock(&m_lock); #endif if (rc >= 0 && transaction) { std::string match_(match); logOffset(ruleMessage, rc - match_.size() + 1, match_.size()); transaction->m_matched.push_back(match_); } if (rule && rule->m_containsCaptureAction && transaction && rc) { transaction->m_collections.m_tx_collection->storeOrUpdateFirst("0", std::string(match)); ms_dbg_a(transaction, 7, "Added pm match TX.0: " + \ std::string(match)); } return rc >= 0; } bool Pm::init(const std::string &file, std::string *error) { std::vector<std::string> vec; std::istringstream *iss; const char *err = NULL; #ifdef MODSEC_MUTEX_ON_PM pthread_mutex_init(&m_lock, NULL); #endif char *content = parse_pm_content(m_param.c_str(), m_param.length(), &err); if (content == NULL) { iss = new std::istringstream(m_param); } else { iss = new std::istringstream(content); } std::copy(std::istream_iterator<std::string>(*iss), std::istream_iterator<std::string>(), back_inserter(vec)); for (auto &a : vec) { acmp_add_pattern(m_p, a.c_str(), NULL, NULL, a.length()); } while (m_p->is_failtree_done == 0) { acmp_prepare(m_p); } if (content) { free(content); content = NULL; } delete iss; return true; } } // namespace operators } // namespace modsecurity <commit_msg>Avoid using NULL string (match) in Pm::evaluate<commit_after>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address [email protected]. * */ #include "src/operators/pm.h" #include <string.h> #include <string> #include <algorithm> #include <iterator> #include <sstream> #include <vector> #include <list> #include <memory> #include "src/operators/operator.h" #include "src/utils/acmp.h" #include "src/utils/string.h" namespace modsecurity { namespace operators { Pm::~Pm() { acmp_node_t *root = m_p->root_node; acmp_node_t *node = root; cleanup(root); free(m_p); m_p = NULL; #ifdef MODSEC_MUTEX_ON_PM pthread_mutex_destroy(&m_lock); #endif } void Pm::cleanup(acmp_node_t *n) { if (n == NULL) { return; } cleanup(n->sibling); cleanup(n->child); postOrderTraversal(n->btree); if (n->text && strlen(n->text) > 0) { free(n->text); n->text = NULL; } if (n->pattern && strlen(n->pattern) > 0) { free(n->pattern); n->pattern = NULL; } free(n); } void Pm::postOrderTraversal(acmp_btree_node_t *node) { if (node == NULL) { return; } postOrderTraversal(node->right); postOrderTraversal(node->left); free(node); } bool Pm::evaluate(Transaction *transaction, Rule *rule, const std::string &input, std::shared_ptr<RuleMessage> ruleMessage) { int rc = -1; ACMPT pt; pt.parser = m_p; pt.ptr = NULL; const char *match = NULL; #ifdef MODSEC_MUTEX_ON_PM pthread_mutex_lock(&m_lock); #endif rc = acmp_process_quick(&pt, &match, input.c_str(), input.length()); #ifdef MODSEC_MUTEX_ON_PM pthread_mutex_unlock(&m_lock); #endif if (rc >= 0 && transaction) { std::string match_(match); logOffset(ruleMessage, rc - match_.size() + 1, match_.size()); transaction->m_matched.push_back(match_); } if (rule && rule->m_containsCaptureAction && transaction && rc >= 0) { transaction->m_collections.m_tx_collection->storeOrUpdateFirst("0", std::string(match)); ms_dbg_a(transaction, 7, "Added pm match TX.0: " + \ std::string(match)); } return rc >= 0; } bool Pm::init(const std::string &file, std::string *error) { std::vector<std::string> vec; std::istringstream *iss; const char *err = NULL; #ifdef MODSEC_MUTEX_ON_PM pthread_mutex_init(&m_lock, NULL); #endif char *content = parse_pm_content(m_param.c_str(), m_param.length(), &err); if (content == NULL) { iss = new std::istringstream(m_param); } else { iss = new std::istringstream(content); } std::copy(std::istream_iterator<std::string>(*iss), std::istream_iterator<std::string>(), back_inserter(vec)); for (auto &a : vec) { acmp_add_pattern(m_p, a.c_str(), NULL, NULL, a.length()); } while (m_p->is_failtree_done == 0) { acmp_prepare(m_p); } if (content) { free(content); content = NULL; } delete iss; return true; } } // namespace operators } // namespace modsecurity <|endoftext|>
<commit_before>/* accountconfig.cpp - Kopete account config page Copyright (c) 2003-2004 by Olivier Goffart <ogoffart @ kde.org> Copyright (c) 2003 by Martijn Klingens <[email protected]> Kopete (c) 2003-2004 by the Kopete developers <[email protected]> ************************************************************************* * * * 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) any later version. * * * ************************************************************************* */ #include "kopeteaccountconfig.h" #include <qcheckbox.h> #include <qlayout.h> #include <kcolorbutton.h> #include <kpushbutton.h> #include <kdebug.h> #include <kdialogbase.h> #include <kgenericfactory.h> #include <kiconloader.h> #include <klistview.h> #include <klocale.h> #include <kmessagebox.h> #include "addaccountwizard.h" #include "editaccountwidget.h" #include "kopeteaccountconfigbase.h" #include "kopeteaccountmanager.h" #include "kopeteprotocol.h" #include "kopeteaccount.h" class KopeteAccountLVI : public KListViewItem { public: KopeteAccountLVI( Kopete::Account *a, KListView *p ) : KListViewItem( p ){ m_account = a; } Kopete::Account *account() { return m_account; } private: Kopete::Account *m_account; }; typedef KGenericFactory<KopeteAccountConfig, QWidget> KopeteAccountConfigFactory; K_EXPORT_COMPONENT_FACTORY( kcm_kopete_accountconfig, KopeteAccountConfigFactory( "kcm_kopete_accountconfig" ) ) KopeteAccountConfig::KopeteAccountConfig( QWidget *parent, const char * /* name */, const QStringList &args ) : KCModule( KopeteAccountConfigFactory::instance(), parent, args ) { ( new QVBoxLayout( this ) )->setAutoAdd( true ); m_view = new KopeteAccountConfigBase( this, "KopeteAccountConfig::m_view" ); m_view->mButtonUp->setIconSet( SmallIconSet( "up" ) ); m_view->mButtonDown->setIconSet( SmallIconSet( "down" ) ); connect( m_view->mButtonNew, SIGNAL( clicked() ), this, SLOT( slotAddAccount() ) ); connect( m_view->mButtonEdit, SIGNAL( clicked() ), this, SLOT( slotEditAccount() ) ); connect( m_view->mButtonRemove, SIGNAL( clicked() ), this, SLOT( slotRemoveAccount() ) ); connect( m_view->mButtonUp, SIGNAL( clicked() ), this, SLOT( slotAccountUp() ) ); connect( m_view->mButtonDown, SIGNAL( clicked() ), this, SLOT( slotAccountDown() ) ); connect( m_view->mAccountList, SIGNAL( selectionChanged() ), this, SLOT( slotItemSelected() ) ); connect( m_view->mAccountList, SIGNAL( doubleClicked( QListViewItem * ) ), this, SLOT( slotEditAccount() ) ); connect( m_view->mUseColor, SIGNAL( toggled( bool ) ), this, SLOT( slotColorChanged() ) ); connect( m_view->mColorButton, SIGNAL( changed( const QColor & ) ), this, SLOT( slotColorChanged() ) ); m_view->mAccountList->setSorting(-1); setButtons( Help ); load(); } void KopeteAccountConfig::save() { uint priority = m_view->mAccountList->childCount(); KopeteAccountLVI *i = static_cast<KopeteAccountLVI*>( m_view->mAccountList->firstChild() ); while( i ) { i->account()->setPriority( priority-- ); i = static_cast<KopeteAccountLVI*>( i->nextSibling() ); } QMap<Kopete::Account *, QColor>::Iterator it; for(it=m_newColors.begin() ; it != m_newColors.end() ; ++it) it.key()->setColor(it.data()); m_newColors.clear(); Kopete::AccountManager::self()->save(); load(); //refresh the colred accounts (in case of apply) } void KopeteAccountConfig::load() { KopeteAccountLVI *lvi = 0L; m_view->mAccountList->clear(); QPtrList<Kopete::Account> accounts = Kopete::AccountManager::self()->accounts(); for ( Kopete::Account *i = accounts.first() ; i; i = accounts.next() ) { // Insert the item after the previous one lvi = new KopeteAccountLVI( i, m_view->mAccountList ); lvi->setText( 0, i->protocol()->displayName() ); lvi->setPixmap( 0, i->accountIcon() ); lvi->setText( 1, i->accountLabel() ); } m_newColors.clear(); slotItemSelected(); } void KopeteAccountConfig::slotItemSelected() { m_protected=true; KopeteAccountLVI *itemSelected = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); m_view->mButtonEdit->setEnabled( itemSelected ); m_view->mButtonRemove->setEnabled( itemSelected ); if ( itemSelected ) { m_view->mButtonUp->setEnabled( itemSelected->itemAbove() ); m_view->mButtonDown->setEnabled( itemSelected->itemBelow() ); Kopete::Account *account = itemSelected->account(); QColor color= m_newColors.contains(account) ? m_newColors[account] : account->color(); m_view->mUseColor->setEnabled( true ); m_view->mUseColor->setChecked( color.isValid() ); m_view->mColorButton->setColor( color ); m_view->mColorButton->setEnabled( m_view->mUseColor->isChecked() ); } else { m_view->mButtonUp->setEnabled( false ); m_view->mButtonDown->setEnabled( false); m_view->mUseColor->setEnabled( false ); m_view->mColorButton->setEnabled( false ); } m_protected=false; } void KopeteAccountConfig::slotAccountUp() { KopeteAccountLVI *itemSelected = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !itemSelected ) return; if ( itemSelected->itemAbove() ) itemSelected->itemAbove()->moveItem( itemSelected ); slotItemSelected(); emit changed( true ); } void KopeteAccountConfig::slotAccountDown() { KopeteAccountLVI *itemSelected = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !itemSelected ) return; itemSelected->moveItem( itemSelected->itemBelow() ); slotItemSelected(); emit changed( true ); } void KopeteAccountConfig::slotAddAccount() { AddAccountWizard *m_addwizard = new AddAccountWizard( this, "addAccountWizard", true ); connect( m_addwizard, SIGNAL( destroyed( QObject * ) ), this, SLOT( slotAddWizardDone() ) ); m_addwizard->show(); } void KopeteAccountConfig::slotEditAccount() { KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !lvi ) return; Kopete::Account *ident = lvi->account(); Kopete::Protocol *proto = ident->protocol(); KDialogBase *editDialog = new KDialogBase( this, "KopeteAccountConfig::editDialog", true, i18n( "Edit Account" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true ); KopeteEditAccountWidget *m_accountWidget = proto->createEditAccountWidget( ident, editDialog ); if ( !m_accountWidget ) return; // FIXME: Why the #### is EditAccountWidget not a QWidget?!? This sideways casting // is braindead and error-prone. Looking at MSN the only reason I can see is // because it allows direct subclassing of designer widgets. But what is // wrong with embedding the designer widget in an empty QWidget instead? // Also, if this REALLY has to be a pure class and not a widget, then the // class should at least be renamed to EditAccountIface instead - Martijn QWidget *w = dynamic_cast<QWidget *>( m_accountWidget ); if ( !w ) return; editDialog->setMainWidget( w ); if ( editDialog->exec() == QDialog::Accepted ) { if( m_accountWidget->validateData() ) m_accountWidget->apply(); } // FIXME: Why deleteLater? It shouldn't be in use anymore at this point - Martijn editDialog->deleteLater(); load(); Kopete::AccountManager::self()->save(); } void KopeteAccountConfig::slotRemoveAccount() { KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !lvi ) return; Kopete::Account *i = lvi->account(); if ( KMessageBox::warningContinueCancel( this, i18n( "Are you sure you want to remove the account \"%1\"?" ).arg( i->accountLabel() ), i18n( "Remove Account" ), KGuiItem(i18n( "Remove Account" ), "editdelete"), "askRemoveAccount", KMessageBox::Notify | KMessageBox::Dangerous ) == KMessageBox::Continue ) { Kopete::AccountManager::self()->removeAccount( i ); delete lvi; } } void KopeteAccountConfig::slotAddWizardDone() { save(); load(); } void KopeteAccountConfig::slotColorChanged() { if(m_protected) //this slot is called because we changed the button return; // color because another account has been selected KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !lvi ) return; Kopete::Account *account = lvi->account(); if(!account->color().isValid() && !m_view->mUseColor->isChecked() ) { //we don't use color for that account and nothing changed. m_newColors.remove(account); return; } else if(!m_view->mUseColor->isChecked()) { //the user disabled account coloring, but it was activated before m_newColors[account]=QColor(); emit changed(true); return; } else if(account->color() == m_view->mColorButton->color() ) { //The color has not changed. m_newColors.remove(account); return; } else { m_newColors[account]=m_view->mColorButton->color(); emit changed(true); } } #include "kopeteaccountconfig.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>fix crash that happen when removing jabber accounts that have transports<commit_after>/* accountconfig.cpp - Kopete account config page Copyright (c) 2003-2004 by Olivier Goffart <ogoffart @ kde.org> Copyright (c) 2003 by Martijn Klingens <[email protected]> Kopete (c) 2003-2004 by the Kopete developers <[email protected]> ************************************************************************* * * * 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) any later version. * * * ************************************************************************* */ #include "kopeteaccountconfig.h" #include <qcheckbox.h> #include <qlayout.h> #include <qguardedptr.h> #include <kcolorbutton.h> #include <kpushbutton.h> #include <kdebug.h> #include <kdialogbase.h> #include <kgenericfactory.h> #include <kiconloader.h> #include <klistview.h> #include <klocale.h> #include <kmessagebox.h> #include "addaccountwizard.h" #include "editaccountwidget.h" #include "kopeteaccountconfigbase.h" #include "kopeteaccountmanager.h" #include "kopeteprotocol.h" #include "kopeteaccount.h" class KopeteAccountLVI : public KListViewItem { public: KopeteAccountLVI( Kopete::Account *a, KListView *p ) : KListViewItem( p ){ m_account = a; } Kopete::Account *account() { return m_account; } private: //need to be guarded because some accounts may be linked (that's the case of jabber transports) QGuardedPtr<Kopete::Account> m_account; }; typedef KGenericFactory<KopeteAccountConfig, QWidget> KopeteAccountConfigFactory; K_EXPORT_COMPONENT_FACTORY( kcm_kopete_accountconfig, KopeteAccountConfigFactory( "kcm_kopete_accountconfig" ) ) KopeteAccountConfig::KopeteAccountConfig( QWidget *parent, const char * /* name */, const QStringList &args ) : KCModule( KopeteAccountConfigFactory::instance(), parent, args ) { ( new QVBoxLayout( this ) )->setAutoAdd( true ); m_view = new KopeteAccountConfigBase( this, "KopeteAccountConfig::m_view" ); m_view->mButtonUp->setIconSet( SmallIconSet( "up" ) ); m_view->mButtonDown->setIconSet( SmallIconSet( "down" ) ); connect( m_view->mButtonNew, SIGNAL( clicked() ), this, SLOT( slotAddAccount() ) ); connect( m_view->mButtonEdit, SIGNAL( clicked() ), this, SLOT( slotEditAccount() ) ); connect( m_view->mButtonRemove, SIGNAL( clicked() ), this, SLOT( slotRemoveAccount() ) ); connect( m_view->mButtonUp, SIGNAL( clicked() ), this, SLOT( slotAccountUp() ) ); connect( m_view->mButtonDown, SIGNAL( clicked() ), this, SLOT( slotAccountDown() ) ); connect( m_view->mAccountList, SIGNAL( selectionChanged() ), this, SLOT( slotItemSelected() ) ); connect( m_view->mAccountList, SIGNAL( doubleClicked( QListViewItem * ) ), this, SLOT( slotEditAccount() ) ); connect( m_view->mUseColor, SIGNAL( toggled( bool ) ), this, SLOT( slotColorChanged() ) ); connect( m_view->mColorButton, SIGNAL( changed( const QColor & ) ), this, SLOT( slotColorChanged() ) ); m_view->mAccountList->setSorting(-1); setButtons( Help ); load(); } void KopeteAccountConfig::save() { uint priority = m_view->mAccountList->childCount(); KopeteAccountLVI *i = static_cast<KopeteAccountLVI*>( m_view->mAccountList->firstChild() ); while( i ) { if(!i->account()) continue; i->account()->setPriority( priority-- ); i = static_cast<KopeteAccountLVI*>( i->nextSibling() ); } QMap<Kopete::Account *, QColor>::Iterator it; for(it=m_newColors.begin() ; it != m_newColors.end() ; ++it) it.key()->setColor(it.data()); m_newColors.clear(); Kopete::AccountManager::self()->save(); load(); //refresh the colred accounts (in case of apply) } void KopeteAccountConfig::load() { KopeteAccountLVI *lvi = 0L; m_view->mAccountList->clear(); QPtrList<Kopete::Account> accounts = Kopete::AccountManager::self()->accounts(); for ( Kopete::Account *i = accounts.first() ; i; i = accounts.next() ) { // Insert the item after the previous one lvi = new KopeteAccountLVI( i, m_view->mAccountList ); lvi->setText( 0, i->protocol()->displayName() ); lvi->setPixmap( 0, i->accountIcon() ); lvi->setText( 1, i->accountLabel() ); } m_newColors.clear(); slotItemSelected(); } void KopeteAccountConfig::slotItemSelected() { m_protected=true; KopeteAccountLVI *itemSelected = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); m_view->mButtonEdit->setEnabled( itemSelected ); m_view->mButtonRemove->setEnabled( itemSelected ); if ( itemSelected && itemSelected->account() ) { m_view->mButtonUp->setEnabled( itemSelected->itemAbove() ); m_view->mButtonDown->setEnabled( itemSelected->itemBelow() ); Kopete::Account *account = itemSelected->account(); QColor color= m_newColors.contains(account) ? m_newColors[account] : account->color(); m_view->mUseColor->setEnabled( true ); m_view->mUseColor->setChecked( color.isValid() ); m_view->mColorButton->setColor( color ); m_view->mColorButton->setEnabled( m_view->mUseColor->isChecked() ); } else { m_view->mButtonUp->setEnabled( false ); m_view->mButtonDown->setEnabled( false); m_view->mUseColor->setEnabled( false ); m_view->mColorButton->setEnabled( false ); } m_protected=false; } void KopeteAccountConfig::slotAccountUp() { KopeteAccountLVI *itemSelected = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !itemSelected ) return; if ( itemSelected->itemAbove() ) itemSelected->itemAbove()->moveItem( itemSelected ); slotItemSelected(); emit changed( true ); } void KopeteAccountConfig::slotAccountDown() { KopeteAccountLVI *itemSelected = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !itemSelected ) return; itemSelected->moveItem( itemSelected->itemBelow() ); slotItemSelected(); emit changed( true ); } void KopeteAccountConfig::slotAddAccount() { AddAccountWizard *m_addwizard = new AddAccountWizard( this, "addAccountWizard", true ); connect( m_addwizard, SIGNAL( destroyed( QObject * ) ), this, SLOT( slotAddWizardDone() ) ); m_addwizard->show(); } void KopeteAccountConfig::slotEditAccount() { KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !lvi || !lvi->account() ) return; Kopete::Account *ident = lvi->account(); Kopete::Protocol *proto = ident->protocol(); KDialogBase *editDialog = new KDialogBase( this, "KopeteAccountConfig::editDialog", true, i18n( "Edit Account" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true ); KopeteEditAccountWidget *m_accountWidget = proto->createEditAccountWidget( ident, editDialog ); if ( !m_accountWidget ) return; // FIXME: Why the #### is EditAccountWidget not a QWidget?!? This sideways casting // is braindead and error-prone. Looking at MSN the only reason I can see is // because it allows direct subclassing of designer widgets. But what is // wrong with embedding the designer widget in an empty QWidget instead? // Also, if this REALLY has to be a pure class and not a widget, then the // class should at least be renamed to EditAccountIface instead - Martijn QWidget *w = dynamic_cast<QWidget *>( m_accountWidget ); if ( !w ) return; editDialog->setMainWidget( w ); if ( editDialog->exec() == QDialog::Accepted ) { if( m_accountWidget->validateData() ) m_accountWidget->apply(); } // FIXME: Why deleteLater? It shouldn't be in use anymore at this point - Martijn editDialog->deleteLater(); load(); Kopete::AccountManager::self()->save(); } void KopeteAccountConfig::slotRemoveAccount() { KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !lvi || !lvi->account() ) return; Kopete::Account *i = lvi->account(); if ( KMessageBox::warningContinueCancel( this, i18n( "Are you sure you want to remove the account \"%1\"?" ).arg( i->accountLabel() ), i18n( "Remove Account" ), KGuiItem(i18n( "Remove Account" ), "editdelete"), "askRemoveAccount", KMessageBox::Notify | KMessageBox::Dangerous ) == KMessageBox::Continue ) { Kopete::AccountManager::self()->removeAccount( i ); delete lvi; } } void KopeteAccountConfig::slotAddWizardDone() { save(); load(); } void KopeteAccountConfig::slotColorChanged() { if(m_protected) //this slot is called because we changed the button return; // color because another account has been selected KopeteAccountLVI *lvi = static_cast<KopeteAccountLVI*>( m_view->mAccountList->selectedItem() ); if ( !lvi || !lvi->account() ) return; Kopete::Account *account = lvi->account(); if(!account->color().isValid() && !m_view->mUseColor->isChecked() ) { //we don't use color for that account and nothing changed. m_newColors.remove(account); return; } else if(!m_view->mUseColor->isChecked()) { //the user disabled account coloring, but it was activated before m_newColors[account]=QColor(); emit changed(true); return; } else if(account->color() == m_view->mColorButton->color() ) { //The color has not changed. m_newColors.remove(account); return; } else { m_newColors[account]=m_view->mColorButton->color(); emit changed(true); } } #include "kopeteaccountconfig.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/************************************************************************ filename: CEGUIPropertyHelper.cpp created: 6/7/2004 author: Paul D Turner purpose: Implementation of PropertyHelper methods *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net) Copyright (C)2004 Paul D Turner ([email protected]) 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "CEGUIPropertyHelper.h" #include "CEGUIImagesetManager.h" #include "CEGUIImageset.h" #include "CEGUIExceptions.h" #include <cstdio> // Start of CEGUI namespace section namespace CEGUI { float PropertyHelper::stringToFloat(const String& str) { using namespace std; float val = 0; sscanf(str.c_str(), " %f", &val); return val; } uint PropertyHelper::stringToUint(const String& str) { using namespace std; uint val = 0; sscanf(str.c_str(), " %u", &val); return val; } bool PropertyHelper::stringToBool(const String& str) { if (str == (utf8*)"True") { return true; } else { return false; } } Size PropertyHelper::stringToSize(const String& str) { using namespace std; Size val(0,0); sscanf(str.c_str(), " w:%f h:%f", &val.d_width, &val.d_height); return val; } Point PropertyHelper::stringToPoint(const String& str) { using namespace std; Point val(0,0) ; sscanf(str.c_str(), " x:%f y:%f", &val.d_x, &val.d_y); return val; } Rect PropertyHelper::stringToRect(const String& str) { using namespace std; Rect val(0, 0, 0, 0); sscanf(str.c_str(), " l:%f t:%f r:%f b:%f", &val.d_left, &val.d_top, &val.d_right, &val.d_bottom); return val; } MetricsMode PropertyHelper::stringToMetricsMode(const String& str) { if (str == (utf8*)"Relative") { return Relative; } else if (str == (utf8*)"Absolute") { return Absolute; } else { return Inherited; } } const Image* PropertyHelper::stringToImage(const String& str) { using namespace std; char imageSet[128]; char imageName[128]; sscanf(str.c_str(), " set:%127s image:%127s", imageSet, imageName); const Image* image; try { image = &ImagesetManager::getSingleton().getImageset((utf8*)imageSet)->getImage((utf8*)imageName); } catch (UnknownObjectException) { image = NULL; } return image; } String PropertyHelper::floatToString(float val) { using namespace std; char buff[64]; sprintf(buff, "%f", val); return String((utf8*)buff); } String PropertyHelper::uintToString(uint val) { using namespace std; char buff[64]; sprintf(buff, "%u", val); return String((utf8*)buff); } String PropertyHelper::boolToString(bool val) { if (val) { return String((utf8*)"True"); } else { return String ((utf8*)"False"); } } String PropertyHelper::sizeToString(const Size& val) { using namespace std; char buff[128]; sprintf(buff, "w:%f h:%f", val.d_width, val.d_height); return String((utf8*)buff); } String PropertyHelper::pointToString(const Point& val) { using namespace std; char buff[128]; sprintf(buff, "x:%f y:%f", val.d_x, val.d_y); return String((utf8*)buff); } String PropertyHelper::rectToString(const Rect& val) { using namespace std; char buff[256]; sprintf(buff, "l:%f t:%f r:%f b:%f", val.d_left, val.d_top, val.d_right, val.d_bottom); return String((utf8*)buff); } String PropertyHelper::metricsModeToString(MetricsMode val) { if (val == Relative) { return String((utf8*)"Relative"); } else if (val == Absolute) { return String((utf8*)"Absolute"); } else { return String((utf8*)"Inherited"); } } String PropertyHelper::imageToString(const Image* const val) { if (val != NULL) { return String((utf8*)"set:" + val->getImagesetName() + (utf8*)" image:" + val->getName()); } return String((utf8*)""); } String PropertyHelper::colourToString(colour val) { using namespace std; char buff[16]; sprintf(buff, "%.8X", val); return String((utf8*)buff); } colour PropertyHelper::stringToColour(const String& str) { using namespace std; colour val = 0xFF000000; sscanf(str.c_str(), " %8X", &val); return val; } String PropertyHelper::colourRectToString(const ColourRect& val) { using namespace std; char buff[64]; sprintf(buff, "tl:%.8X tr:%.8X bl:%.8X br:%.8X", val.d_top_left, val.d_top_right, val.d_bottom_left, val.d_bottom_right); return String((utf8*)buff); } ColourRect PropertyHelper::stringToColourRect(const String& str) { using namespace std; ColourRect val(0xFF000000); sscanf(str.c_str(), "tl:%8X tr:%8X bl:%8X br:%8X", &val.d_top_left, &val.d_top_right, &val.d_bottom_left, &val.d_bottom_right); return val; } } // End of CEGUI namespace section <commit_msg>Added support so that true for boolean properties can be either "True" or "true" instead of just "True" (anything else still == false).<commit_after>/************************************************************************ filename: CEGUIPropertyHelper.cpp created: 6/7/2004 author: Paul D Turner purpose: Implementation of PropertyHelper methods *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net) Copyright (C)2004 Paul D Turner ([email protected]) 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "CEGUIPropertyHelper.h" #include "CEGUIImagesetManager.h" #include "CEGUIImageset.h" #include "CEGUIExceptions.h" #include <cstdio> // Start of CEGUI namespace section namespace CEGUI { float PropertyHelper::stringToFloat(const String& str) { using namespace std; float val = 0; sscanf(str.c_str(), " %f", &val); return val; } uint PropertyHelper::stringToUint(const String& str) { using namespace std; uint val = 0; sscanf(str.c_str(), " %u", &val); return val; } bool PropertyHelper::stringToBool(const String& str) { if ((str == (utf8*)"True") || (str == (utf8*)"true")) { return true; } else { return false; } } Size PropertyHelper::stringToSize(const String& str) { using namespace std; Size val(0,0); sscanf(str.c_str(), " w:%f h:%f", &val.d_width, &val.d_height); return val; } Point PropertyHelper::stringToPoint(const String& str) { using namespace std; Point val(0,0) ; sscanf(str.c_str(), " x:%f y:%f", &val.d_x, &val.d_y); return val; } Rect PropertyHelper::stringToRect(const String& str) { using namespace std; Rect val(0, 0, 0, 0); sscanf(str.c_str(), " l:%f t:%f r:%f b:%f", &val.d_left, &val.d_top, &val.d_right, &val.d_bottom); return val; } MetricsMode PropertyHelper::stringToMetricsMode(const String& str) { if (str == (utf8*)"Relative") { return Relative; } else if (str == (utf8*)"Absolute") { return Absolute; } else { return Inherited; } } const Image* PropertyHelper::stringToImage(const String& str) { using namespace std; char imageSet[128]; char imageName[128]; sscanf(str.c_str(), " set:%127s image:%127s", imageSet, imageName); const Image* image; try { image = &ImagesetManager::getSingleton().getImageset((utf8*)imageSet)->getImage((utf8*)imageName); } catch (UnknownObjectException) { image = NULL; } return image; } String PropertyHelper::floatToString(float val) { using namespace std; char buff[64]; sprintf(buff, "%f", val); return String((utf8*)buff); } String PropertyHelper::uintToString(uint val) { using namespace std; char buff[64]; sprintf(buff, "%u", val); return String((utf8*)buff); } String PropertyHelper::boolToString(bool val) { if (val) { return String((utf8*)"True"); } else { return String ((utf8*)"False"); } } String PropertyHelper::sizeToString(const Size& val) { using namespace std; char buff[128]; sprintf(buff, "w:%f h:%f", val.d_width, val.d_height); return String((utf8*)buff); } String PropertyHelper::pointToString(const Point& val) { using namespace std; char buff[128]; sprintf(buff, "x:%f y:%f", val.d_x, val.d_y); return String((utf8*)buff); } String PropertyHelper::rectToString(const Rect& val) { using namespace std; char buff[256]; sprintf(buff, "l:%f t:%f r:%f b:%f", val.d_left, val.d_top, val.d_right, val.d_bottom); return String((utf8*)buff); } String PropertyHelper::metricsModeToString(MetricsMode val) { if (val == Relative) { return String((utf8*)"Relative"); } else if (val == Absolute) { return String((utf8*)"Absolute"); } else { return String((utf8*)"Inherited"); } } String PropertyHelper::imageToString(const Image* const val) { if (val != NULL) { return String((utf8*)"set:" + val->getImagesetName() + (utf8*)" image:" + val->getName()); } return String((utf8*)""); } String PropertyHelper::colourToString(colour val) { using namespace std; char buff[16]; sprintf(buff, "%.8X", val); return String((utf8*)buff); } colour PropertyHelper::stringToColour(const String& str) { using namespace std; colour val = 0xFF000000; sscanf(str.c_str(), " %8X", &val); return val; } String PropertyHelper::colourRectToString(const ColourRect& val) { using namespace std; char buff[64]; sprintf(buff, "tl:%.8X tr:%.8X bl:%.8X br:%.8X", val.d_top_left, val.d_top_right, val.d_bottom_left, val.d_bottom_right); return String((utf8*)buff); } ColourRect PropertyHelper::stringToColourRect(const String& str) { using namespace std; ColourRect val(0xFF000000); sscanf(str.c_str(), "tl:%8X tr:%8X bl:%8X br:%8X", &val.d_top_left, &val.d_top_right, &val.d_bottom_left, &val.d_bottom_right); return val; } } // End of CEGUI namespace section <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2019 WandererFan <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <TopoDS_Edge.hxx> # include <gp_Pnt.hxx> # include <BRepBuilderAPI_MakeEdge.hxx> #endif // #ifndef _PreComp_ #include <Base/Console.h> #include <Base/Exception.h> #include <Base/Parameter.h> #include <Base/Tools2D.h> #include <Base/Vector3D.h> #include <App/Application.h> #include <App/Material.h> #include "DrawUtil.h" #include "Geometry.h" #include "Cosmetic.h" using namespace TechDraw; CosmeticVertex::CosmeticVertex() { pageLocation = Base::Vector3d(0.0, 0.0, 0.0); modelLocation = Base::Vector3d(0.0, 0.0, 0.0); Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); App::Color fcColor; fcColor.setPackedValue(hGrp->GetUnsigned("VertexColor", 0x00000000)); linkGeom = -1; color = fcColor; size = 3.0; style = 1; visible = true; } CosmeticVertex::CosmeticVertex(Base::Vector3d loc) { pageLocation = loc; modelLocation = loc; Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); App::Color fcColor; fcColor.setPackedValue(hGrp->GetUnsigned("VertexColor", 0xff000000)); linkGeom = -1; color = fcColor; //TODO: size = hGrp->getFloat("VertexSize",30.0); size = 30.0; style = 1; //TODO: implement styled vertexes visible = true; } std::string CosmeticVertex::toCSV(void) const { std::stringstream ss; ss << pageLocation.x << "," << pageLocation.y << "," << pageLocation.z << "," << modelLocation.x << "," << modelLocation.y << "," << modelLocation.z << "," << linkGeom << "," << color.asHexString() << "," << size << "," << style << "," << visible << std::endl; return ss.str(); } bool CosmeticVertex::fromCSV(std::string& lineSpec) { unsigned int maxCells = 11; if (lineSpec.length() == 0) { Base::Console().Message( "CosmeticVertex::fromCSV - lineSpec empty\n"); return false; } std::vector<std::string> values = split(lineSpec); if (values.size() < maxCells) { Base::Console().Message( "CosmeticVertex::fromCSV(%s) invalid CSV entry\n",lineSpec.c_str() ); return false; } double x = atof(values[0].c_str()); double y = atof(values[1].c_str()); double z = atof(values[2].c_str()); pageLocation = Base::Vector3d (x,y,z); x = atof(values[3].c_str()); y = atof(values[4].c_str()); z = atof(values[5].c_str()); modelLocation = Base::Vector3d (x,y,z); linkGeom = atoi(values[6].c_str()); color.fromHexString(values[7]); size = atof(values[8].c_str()); style = atoi(values[9].c_str()); visible = atoi(values[10].c_str()); return true; } std::vector<std::string> CosmeticVertex::split(std::string csvLine) { // Base::Console().Message("CV::split - csvLine: %s\n",csvLine.c_str()); std::vector<std::string> result; std::stringstream lineStream(csvLine); std::string cell; while(std::getline(lineStream,cell, ',')) { result.push_back(cell); } return result; } void CosmeticVertex::dump(char* title) { Base::Console().Message("CV::dump - %s \n",title); Base::Console().Message("CV::dump - %s \n",toCSV().c_str()); } //****************************************** CosmeticEdge::CosmeticEdge() { geometry = new TechDrawGeometry::BaseGeom(); linkGeom = -1; color = getDefEdgeColor(); width = getDefEdgeWidth(); style = getDefEdgeStyle(); visible = true; } CosmeticEdge::CosmeticEdge(Base::Vector3d p1, Base::Vector3d p2) { gp_Pnt gp1(p1.x,p1.y,p1.z); gp_Pnt gp2(p2.x,p2.y,p2.z); TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); geometry = TechDrawGeometry::BaseGeom::baseFactory(e); linkGeom = -1; color = getDefEdgeColor(); width = getDefEdgeWidth(); style = getDefEdgeStyle(); visible = true; } CosmeticEdge::CosmeticEdge(TopoDS_Edge e) { geometry = TechDrawGeometry::BaseGeom::baseFactory(e); linkGeom = -1; color = getDefEdgeColor(); width = getDefEdgeWidth(); style = getDefEdgeStyle(); visible = true; } double CosmeticEdge::getDefEdgeWidth() { Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); std::string lgName = hGrp->GetASCII("LineGroup","FC 0.70mm"); auto lg = TechDraw::LineGroup::lineGroupFactory(lgName); double width = lg->getWeight("Graphic"); delete lg; return width; } App::Color CosmeticEdge::getDefEdgeColor() { Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Colors"); App::Color fcColor; fcColor.setPackedValue(hGrp->GetUnsigned("NormalColor", 0x00000000)); return fcColor; } int CosmeticEdge::getDefEdgeStyle() { return 1; } std::string CosmeticEdge::toCSV(void) const { std::stringstream ss; Base::Vector3d start, end; if (geometry != nullptr) { Base::Vector2d getStartPoint(); Base::Vector2d getEndPoint(); Base::Vector2d p2d = geometry->getStartPoint(); start = Base::Vector3d(p2d.x, p2d.y, 0.0); p2d = geometry->getEndPoint(); end = Base::Vector3d(p2d.x, p2d.y, 0.0); } ss << start.x << "," << start.y << "," << start.z << "," << end.x << "," << end.y << "," << end.z << "," << linkGeom << "," << color.asHexString() << "," << width << "," << style << "," << visible << std::endl; return ss.str(); } bool CosmeticEdge::fromCSV(std::string& lineSpec) { unsigned int maxCells = 11; if (lineSpec.length() == 0) { Base::Console().Message( "CosmeticEdge::fromCSV - lineSpec empty\n"); return false; } std::vector<std::string> values = split(lineSpec); Base::Console().Message("CE::fromCSV - values: %d\n",values.size()); if (values.size() < maxCells) { Base::Console().Message( "CosmeticEdge::fromCSV(%s) invalid CSV entry\n",lineSpec.c_str() ); return false; } Base::Vector3d start, end; double x = atof(values[0].c_str()); double y = atof(values[1].c_str()); double z = atof(values[2].c_str()); start = Base::Vector3d (x,y,z); x = atof(values[3].c_str()); y = atof(values[4].c_str()); z = atof(values[5].c_str()); end = Base::Vector3d (x,y,z); linkGeom = atoi(values[6].c_str()); color.fromHexString(values[7]); width = atof(values[8].c_str()); style = atoi(values[9].c_str()); visible = atoi(values[10].c_str()); return true; } //duplicate of CV routine. make static? or base class? std::vector<std::string> CosmeticEdge::split(std::string csvLine) { Base::Console().Message("CE::split - csvLine: %s\n",csvLine.c_str()); std::vector<std::string> result; std::stringstream lineStream(csvLine); std::string cell; while(std::getline(lineStream,cell, ',')) { result.push_back(cell); } return result; } //duplicate of CV routine. make static? or base class? void CosmeticEdge::dump(char* title) { Base::Console().Message("CE::dump - %s \n",title); Base::Console().Message("CE::dump - %s \n",toCSV().c_str()); } <commit_msg>fix warning C4930: prototyped function not called<commit_after>/*************************************************************************** * Copyright (c) 2019 WandererFan <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <TopoDS_Edge.hxx> # include <gp_Pnt.hxx> # include <BRepBuilderAPI_MakeEdge.hxx> #endif // #ifndef _PreComp_ #include <Base/Console.h> #include <Base/Exception.h> #include <Base/Parameter.h> #include <Base/Tools2D.h> #include <Base/Vector3D.h> #include <App/Application.h> #include <App/Material.h> #include "DrawUtil.h" #include "Geometry.h" #include "Cosmetic.h" using namespace TechDraw; CosmeticVertex::CosmeticVertex() { pageLocation = Base::Vector3d(0.0, 0.0, 0.0); modelLocation = Base::Vector3d(0.0, 0.0, 0.0); Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); App::Color fcColor; fcColor.setPackedValue(hGrp->GetUnsigned("VertexColor", 0x00000000)); linkGeom = -1; color = fcColor; size = 3.0; style = 1; visible = true; } CosmeticVertex::CosmeticVertex(Base::Vector3d loc) { pageLocation = loc; modelLocation = loc; Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); App::Color fcColor; fcColor.setPackedValue(hGrp->GetUnsigned("VertexColor", 0xff000000)); linkGeom = -1; color = fcColor; //TODO: size = hGrp->getFloat("VertexSize",30.0); size = 30.0; style = 1; //TODO: implement styled vertexes visible = true; } std::string CosmeticVertex::toCSV(void) const { std::stringstream ss; ss << pageLocation.x << "," << pageLocation.y << "," << pageLocation.z << "," << modelLocation.x << "," << modelLocation.y << "," << modelLocation.z << "," << linkGeom << "," << color.asHexString() << "," << size << "," << style << "," << visible << std::endl; return ss.str(); } bool CosmeticVertex::fromCSV(std::string& lineSpec) { unsigned int maxCells = 11; if (lineSpec.length() == 0) { Base::Console().Message( "CosmeticVertex::fromCSV - lineSpec empty\n"); return false; } std::vector<std::string> values = split(lineSpec); if (values.size() < maxCells) { Base::Console().Message( "CosmeticVertex::fromCSV(%s) invalid CSV entry\n",lineSpec.c_str() ); return false; } double x = atof(values[0].c_str()); double y = atof(values[1].c_str()); double z = atof(values[2].c_str()); pageLocation = Base::Vector3d (x,y,z); x = atof(values[3].c_str()); y = atof(values[4].c_str()); z = atof(values[5].c_str()); modelLocation = Base::Vector3d (x,y,z); linkGeom = atoi(values[6].c_str()); color.fromHexString(values[7]); size = atof(values[8].c_str()); style = atoi(values[9].c_str()); visible = atoi(values[10].c_str()); return true; } std::vector<std::string> CosmeticVertex::split(std::string csvLine) { // Base::Console().Message("CV::split - csvLine: %s\n",csvLine.c_str()); std::vector<std::string> result; std::stringstream lineStream(csvLine); std::string cell; while(std::getline(lineStream,cell, ',')) { result.push_back(cell); } return result; } void CosmeticVertex::dump(char* title) { Base::Console().Message("CV::dump - %s \n",title); Base::Console().Message("CV::dump - %s \n",toCSV().c_str()); } //****************************************** CosmeticEdge::CosmeticEdge() { geometry = new TechDrawGeometry::BaseGeom(); linkGeom = -1; color = getDefEdgeColor(); width = getDefEdgeWidth(); style = getDefEdgeStyle(); visible = true; } CosmeticEdge::CosmeticEdge(Base::Vector3d p1, Base::Vector3d p2) { gp_Pnt gp1(p1.x,p1.y,p1.z); gp_Pnt gp2(p2.x,p2.y,p2.z); TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); geometry = TechDrawGeometry::BaseGeom::baseFactory(e); linkGeom = -1; color = getDefEdgeColor(); width = getDefEdgeWidth(); style = getDefEdgeStyle(); visible = true; } CosmeticEdge::CosmeticEdge(TopoDS_Edge e) { geometry = TechDrawGeometry::BaseGeom::baseFactory(e); linkGeom = -1; color = getDefEdgeColor(); width = getDefEdgeWidth(); style = getDefEdgeStyle(); visible = true; } double CosmeticEdge::getDefEdgeWidth() { Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); std::string lgName = hGrp->GetASCII("LineGroup","FC 0.70mm"); auto lg = TechDraw::LineGroup::lineGroupFactory(lgName); double width = lg->getWeight("Graphic"); delete lg; return width; } App::Color CosmeticEdge::getDefEdgeColor() { Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Colors"); App::Color fcColor; fcColor.setPackedValue(hGrp->GetUnsigned("NormalColor", 0x00000000)); return fcColor; } int CosmeticEdge::getDefEdgeStyle() { return 1; } std::string CosmeticEdge::toCSV(void) const { std::stringstream ss; Base::Vector3d start, end; if (geometry != nullptr) { Base::Vector2d p2d = geometry->getStartPoint(); start = Base::Vector3d(p2d.x, p2d.y, 0.0); p2d = geometry->getEndPoint(); end = Base::Vector3d(p2d.x, p2d.y, 0.0); } ss << start.x << "," << start.y << "," << start.z << "," << end.x << "," << end.y << "," << end.z << "," << linkGeom << "," << color.asHexString() << "," << width << "," << style << "," << visible << std::endl; return ss.str(); } bool CosmeticEdge::fromCSV(std::string& lineSpec) { unsigned int maxCells = 11; if (lineSpec.length() == 0) { Base::Console().Message( "CosmeticEdge::fromCSV - lineSpec empty\n"); return false; } std::vector<std::string> values = split(lineSpec); Base::Console().Message("CE::fromCSV - values: %d\n",values.size()); if (values.size() < maxCells) { Base::Console().Message( "CosmeticEdge::fromCSV(%s) invalid CSV entry\n",lineSpec.c_str() ); return false; } Base::Vector3d start, end; double x = atof(values[0].c_str()); double y = atof(values[1].c_str()); double z = atof(values[2].c_str()); start = Base::Vector3d (x,y,z); x = atof(values[3].c_str()); y = atof(values[4].c_str()); z = atof(values[5].c_str()); end = Base::Vector3d (x,y,z); linkGeom = atoi(values[6].c_str()); color.fromHexString(values[7]); width = atof(values[8].c_str()); style = atoi(values[9].c_str()); visible = atoi(values[10].c_str()); return true; } //duplicate of CV routine. make static? or base class? std::vector<std::string> CosmeticEdge::split(std::string csvLine) { Base::Console().Message("CE::split - csvLine: %s\n",csvLine.c_str()); std::vector<std::string> result; std::stringstream lineStream(csvLine); std::string cell; while(std::getline(lineStream,cell, ',')) { result.push_back(cell); } return result; } //duplicate of CV routine. make static? or base class? void CosmeticEdge::dump(char* title) { Base::Console().Message("CE::dump - %s \n",title); Base::Console().Message("CE::dump - %s \n",toCSV().c_str()); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) Jürgen Riegel ([email protected]) 2002 * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <Standard_Failure.hxx> #endif #include <strstream> #include <App/Application.h> #include <Base/Writer.h> #include <Base/Reader.h> #include <Base/Exception.h> #include <Base/FileInfo.h> #include <Base/Console.h> #include "DrawView.h" #include "DrawPage.h" #include "DrawViewCollection.h" #include "DrawViewClip.h" #include "DrawViewPy.h" // generated from DrawViewPy.xml using namespace TechDraw; //=========================================================================== // DrawView //=========================================================================== const char* DrawView::ScaleTypeEnums[]= {"Document", "Automatic", "Custom", NULL}; PROPERTY_SOURCE(TechDraw::DrawView, App::DocumentObject) DrawView::DrawView(void) { static const char *group = "Drawing view"; ADD_PROPERTY_TYPE(X ,(0),group,App::Prop_None,"X position of the view on the page in modelling units (mm)"); ADD_PROPERTY_TYPE(Y ,(0),group,App::Prop_None,"Y position of the view on the page in modelling units (mm)"); ADD_PROPERTY_TYPE(Rotation ,(0),group,App::Prop_None,"Rotation of the view on the page in degrees counterclockwise"); ScaleType.setEnums(ScaleTypeEnums); ADD_PROPERTY_TYPE(ScaleType,((long)0),group, App::Prop_None, "Scale Type"); ADD_PROPERTY_TYPE(Scale ,(1.0),group,App::Prop_None,"Scale factor of the view"); //Scale.setStatus(App::Property::ReadOnly,true); autoPos = true; } DrawView::~DrawView() { } App::DocumentObjectExecReturn *DrawView::recompute(void) { try { return App::DocumentObject::recompute(); } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); App::DocumentObjectExecReturn* ret = new App::DocumentObjectExecReturn(e->GetMessageString()); if (ret->Why.empty()) ret->Why = "Unknown OCC exception"; return ret; } } App::DocumentObjectExecReturn *DrawView::execute(void) { //right way to handle this? can't do it at creation since don't have a parent. if (ScaleType.isValue("Document")) { TechDraw::DrawPage *page = findParentPage(); if(page) { if(std::abs(page->Scale.getValue() - Scale.getValue()) > FLT_EPSILON) { Scale.setValue(page->Scale.getValue()); Scale.touch(); } } } return App::DocumentObject::execute(); } /// get called by the container when a Property was changed void DrawView::onChanged(const App::Property* prop) { if (!isRestoring()) { if (prop == &ScaleType || prop == &Scale) { if (ScaleType.isValue("Document")) { TechDraw::DrawPage *page = findParentPage(); if(page) { if(std::abs(page->Scale.getValue() - Scale.getValue()) > FLT_EPSILON) { Scale.setValue(page->Scale.getValue()); // Reset scale from page Scale.touch(); } } Scale.setStatus(App::Property::ReadOnly,true); App::GetApplication().signalChangePropertyEditor(Scale); } else if ( ScaleType.isValue("Custom") ) { // } else if (ScaleType.isValue("Custom") && // Scale.testStatus(App::Property::ReadOnly)) { Scale.setStatus(App::Property::ReadOnly,false); App::GetApplication().signalChangePropertyEditor(Scale); } //TODO else if (ScaleType.isValue("Automatic"))... DrawView::execute(); } else if (prop == &X || prop == &Y) { setAutoPos(false); DrawView::execute(); } else if (prop == &Rotation) { DrawView::execute(); } } App::DocumentObject::onChanged(prop); } void DrawView::onDocumentRestored() { // Rebuild the view execute(); } DrawPage* DrawView::findParentPage() const { // Get Feature Page DrawPage *page = 0; DrawViewCollection *collection = 0; std::vector<App::DocumentObject*> parent = getInList(); for (std::vector<App::DocumentObject*>::iterator it = parent.begin(); it != parent.end(); ++it) { if ((*it)->getTypeId().isDerivedFrom(DrawPage::getClassTypeId())) { page = dynamic_cast<TechDraw::DrawPage *>(*it); } if ((*it)->getTypeId().isDerivedFrom(DrawViewCollection::getClassTypeId())) { collection = dynamic_cast<TechDraw::DrawViewCollection *>(*it); page = collection->findParentPage(); } if(page) break; // Found page so leave } return page; } bool DrawView::isInClip() { std::vector<App::DocumentObject*> parent = getInList(); for (std::vector<App::DocumentObject*>::iterator it = parent.begin(); it != parent.end(); ++it) { if ((*it)->getTypeId().isDerivedFrom(DrawViewClip::getClassTypeId())) { return true; } } return false; } PyObject *DrawView::getPyObject(void) { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new DrawViewPy(this),true); } return Py::new_reference_to(PythonObject); } // Python Drawing feature --------------------------------------------------------- namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewPython, TechDraw::DrawView) template<> const char* TechDraw::DrawViewPython::getViewProviderName(void) const { return "TechDrawGui::ViewProviderDrawingView"; } /// @endcond // explicit template instantiation template class TechDrawExport FeaturePythonT<TechDraw::DrawView>; } <commit_msg>Fix #58 ProjectionGroupItem positioning after restore<commit_after>/*************************************************************************** * Copyright (c) Jürgen Riegel ([email protected]) 2002 * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <Standard_Failure.hxx> #endif #include <strstream> #include <App/Application.h> #include <Base/Writer.h> #include <Base/Reader.h> #include <Base/Exception.h> #include <Base/FileInfo.h> #include <Base/Console.h> #include "DrawView.h" #include "DrawPage.h" #include "DrawViewCollection.h" #include "DrawViewClip.h" #include "DrawViewPy.h" // generated from DrawViewPy.xml using namespace TechDraw; //=========================================================================== // DrawView //=========================================================================== const char* DrawView::ScaleTypeEnums[]= {"Document", "Automatic", "Custom", NULL}; PROPERTY_SOURCE(TechDraw::DrawView, App::DocumentObject) DrawView::DrawView(void) { static const char *group = "Drawing view"; ADD_PROPERTY_TYPE(X ,(0),group,App::Prop_None,"X position of the view on the page in modelling units (mm)"); ADD_PROPERTY_TYPE(Y ,(0),group,App::Prop_None,"Y position of the view on the page in modelling units (mm)"); ADD_PROPERTY_TYPE(Rotation ,(0),group,App::Prop_None,"Rotation of the view on the page in degrees counterclockwise"); ScaleType.setEnums(ScaleTypeEnums); ADD_PROPERTY_TYPE(ScaleType,((long)0),group, App::Prop_None, "Scale Type"); ADD_PROPERTY_TYPE(Scale ,(1.0),group,App::Prop_None,"Scale factor of the view"); if (isRestoring()) { autoPos = false; } else { autoPos = true; } } DrawView::~DrawView() { } App::DocumentObjectExecReturn *DrawView::recompute(void) { try { return App::DocumentObject::recompute(); } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); App::DocumentObjectExecReturn* ret = new App::DocumentObjectExecReturn(e->GetMessageString()); if (ret->Why.empty()) ret->Why = "Unknown OCC exception"; return ret; } } App::DocumentObjectExecReturn *DrawView::execute(void) { //right way to handle this? can't do it at creation since don't have a parent. if (ScaleType.isValue("Document")) { TechDraw::DrawPage *page = findParentPage(); if(page) { if(std::abs(page->Scale.getValue() - Scale.getValue()) > FLT_EPSILON) { Scale.setValue(page->Scale.getValue()); Scale.touch(); } } } return App::DocumentObject::execute(); } /// get called by the container when a Property was changed void DrawView::onChanged(const App::Property* prop) { if (!isRestoring()) { if (prop == &ScaleType || prop == &Scale) { if (ScaleType.isValue("Document")) { TechDraw::DrawPage *page = findParentPage(); if(page) { if(std::abs(page->Scale.getValue() - Scale.getValue()) > FLT_EPSILON) { Scale.setValue(page->Scale.getValue()); // Reset scale from page Scale.touch(); } } Scale.setStatus(App::Property::ReadOnly,true); App::GetApplication().signalChangePropertyEditor(Scale); } else if ( ScaleType.isValue("Custom") ) { Scale.setStatus(App::Property::ReadOnly,false); App::GetApplication().signalChangePropertyEditor(Scale); } //TODO else if (ScaleType.isValue("Automatic"))... DrawView::execute(); } else if (prop == &X || prop == &Y) { setAutoPos(false); DrawView::execute(); } else if (prop == &Rotation) { DrawView::execute(); } } App::DocumentObject::onChanged(prop); } void DrawView::onDocumentRestored() { // Rebuild the view execute(); } DrawPage* DrawView::findParentPage() const { // Get Feature Page DrawPage *page = 0; DrawViewCollection *collection = 0; std::vector<App::DocumentObject*> parent = getInList(); for (std::vector<App::DocumentObject*>::iterator it = parent.begin(); it != parent.end(); ++it) { if ((*it)->getTypeId().isDerivedFrom(DrawPage::getClassTypeId())) { page = dynamic_cast<TechDraw::DrawPage *>(*it); } if ((*it)->getTypeId().isDerivedFrom(DrawViewCollection::getClassTypeId())) { collection = dynamic_cast<TechDraw::DrawViewCollection *>(*it); page = collection->findParentPage(); } if(page) break; // Found page so leave } return page; } bool DrawView::isInClip() { std::vector<App::DocumentObject*> parent = getInList(); for (std::vector<App::DocumentObject*>::iterator it = parent.begin(); it != parent.end(); ++it) { if ((*it)->getTypeId().isDerivedFrom(DrawViewClip::getClassTypeId())) { return true; } } return false; } PyObject *DrawView::getPyObject(void) { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new DrawViewPy(this),true); } return Py::new_reference_to(PythonObject); } // Python Drawing feature --------------------------------------------------------- namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewPython, TechDraw::DrawView) template<> const char* TechDraw::DrawViewPython::getViewProviderName(void) const { return "TechDrawGui::ViewProviderDrawingView"; } /// @endcond // explicit template instantiation template class TechDrawExport FeaturePythonT<TechDraw::DrawView>; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <map> #include <node.h> #include "PSATResult.h" #include "calculator/EstimateFLA.h" #include "calculator/MotorCurrent.h" #include "calculator/MotorPowerFactor.h" #include "calculator/OptimalPrePumpEff.h" #include "calculator/OptimalSpecificSpeedCorrection.h" #include "calculator/OptimalDeviationFactor.h" using namespace v8; using namespace std; Isolate* iso; Local<Object> inp; Local<Object> r; double Get(const char *nm) { auto rObj = inp->ToObject()->Get(String::NewFromUtf8(iso,nm)); if (rObj->IsUndefined()) { cout << nm << endl;; assert(!"defined"); } return rObj->NumberValue(); } Motor::LineFrequency line; Motor::EfficiencyClass effCls; Pump::Drive drive; double motorRatedPower; void Setup(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); inp = args[0]->ToObject(); r = Object::New(iso); args.GetReturnValue().Set(r); line = (Motor::LineFrequency)(int)(!Get("line")); effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class"); drive = (Pump::Drive)(int)Get("drive"); motorRatedPower = Get("motor_rated_power"); } void Results(const FunctionCallbackInfo<Value>& args) { Setup(args); Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_specified"),Get("pump_rated_speed"),drive, Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed"))); Motor motor(line,motorRatedPower,Get("motor_rated_speed"), effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin")); Financial fin(Get("fraction"),Get("cost")); FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1), Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage")); PSATResult psat(pump,motor,fin,fd); psat.calculateExisting(); psat.calculateOptimal(); auto ex = psat.getExisting(), opt = psat.getOptimal(); map<const char *,vector<double>> out = { {"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}}, {"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}}, {"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}}, {"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}}, {"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}}, {"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}}, {"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}}, {"Motor Power", {ex.motorPower_,opt.motorPower_}}, {"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}}, {"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}}, {"Savings Potential", {psat.getAnnualSavingsPotential(),-1}}, {"Optimization Rating", {psat.getOptimizationRating(),-1}} }; for(auto p: out) { auto a = Array::New(iso); a->Set(0,Number::New(iso,p.second[0])); a->Set(1,Number::New(iso,p.second[1])); r->Set(String::NewFromUtf8(iso,p.first),a); } } void EstFLA(const FunctionCallbackInfo<Value>& args) { Setup(args); EstimateFLA fla(motorRatedPower,Get("motor_rated_speed"),line,effCls, Get("efficiency"),Get("motor_rated_voltage")); fla.calculate(); args.GetReturnValue().Set(fla.getEstimatedFLA()); } void MotorPerformance(const FunctionCallbackInfo<Value>& args) { Setup(args); MotorEfficiency mef(line,Get("motor_rated_speed"),effCls,Get("efficiency"),motorRatedPower,Get("load_factor")); auto mefVal = mef.calculate(); r->Set(String::NewFromUtf8(iso,"efficiency"),Number::New(iso,mefVal*100)); MotorCurrent mc(motorRatedPower,Get("motor_rated_speed"),line,effCls,Get("efficiency"),Get("load_factor"),Get("motor_rated_voltage"),Get("flc")); auto mcVal = mc.calculate(); r->Set(String::NewFromUtf8(iso,"current"),Number::New(iso,mcVal/225.8*100)); MotorPowerFactor pf(motorRatedPower,Get("load_factor"),mcVal,mefVal,Get("motor_rated_voltage")); r->Set(String::NewFromUtf8(iso,"pf"),Number::New(iso,pf.calculate()*100)); } //TODO round vs js round; loosen up to make next test case void Check(double exp, double act, const char* nm="") { //cout << "e " << exp << "; a " << act << endl; // if (isnan(act) || (abs(exp-act)>.01*exp)) { auto p = 10; if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) { printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act); assert(!"equal"); } } void Check100(double exp, double act, const char* nm="") { Check(exp,act*100,nm); } void Test(const FunctionCallbackInfo<Value>& args) { EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460); fla.calculate(); Check(225.8,fla.getEstimatedFLA()); // motor perf { MotorEfficiency mef(Motor::LineFrequency::FREQ60,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,.75); auto mefVal = mef.calculate(); Check100(95.69,mefVal); MotorCurrent mc(200,1780,Motor::LineFrequency::FREQ60,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,.75,460,225.8); auto mcVal = mc.calculate(); Check100(76.63,mcVal/225.8); MotorPowerFactor pf(200,.75,mcVal,mefVal,460); Check100(84.82,pf.calculate()); } //nema { MotorEfficiency mef(Motor::LineFrequency::FREQ60,1200, Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,1); //Check100(95,mef.calculate()); } //pump eff { OptimalPrePumpEff pef(Pump::Style::END_SUCTION_ANSI_API, 0, 2000); OptimalDeviationFactor df(2000); // Check(87.1,pef.calculate()*df.calculate()); } //spec speed { OptimalSpecificSpeedCorrection cor(Pump::Style::END_SUCTION_ANSI_API, 1170); //Check100(2.3,cor.calculate()); } return; #define BASE \ Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\ 1,1,1,Pump::Speed::NOT_FIXED_SPEED);\ Motor motor(Motor::LineFrequency::FREQ60,200,1780,\ Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\ Financial fin(1,.05);\ FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\ 150,0,460); #define CALC \ PSATResult psat(pump,motor,fin,fd);\ psat.calculateExisting();\ auto ex = psat.getExisting(); for (int i=1; i<=10000; i=i+2) { BASE CALC Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME"); } { BASE motor.setMotorRpm(1786); fd.setMotorPower(80); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(79.1,ex.motorPowerFactor_); Check(127,ex.motorCurrent_); } { BASE fd.setMotorPower(80); motor.setMotorRatedPower(100); motor.setFullLoadAmps(113.8); CALC Check(101.8,ex.motorShaftPower_); Check100(94.9,ex.motorEfficiency_); Check100(86.7,ex.motorPowerFactor_); Check(115.8,ex.motorCurrent_); } { BASE fd.setMotorPower(80); fd.setVoltage(260); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(138.8,ex.motorPowerFactor_); Check(128,ex.motorCurrent_); } { BASE motor.setMotorRpm(1200); fd.setMotorPower(80); motor.setFullLoadAmps(235.3); CALC Check(101.4,ex.motorShaftPower_); Check100(94.5,ex.motorEfficiency_); Check100(74.3,ex.motorPowerFactor_); Check(135.1,ex.motorCurrent_); } { BASE fd.setMotorPower(111.855); CALC Check(143.4,ex.motorShaftPower_); Check100(95.6,ex.motorEfficiency_); Check100(84.3,ex.motorPowerFactor_); Check(166.5,ex.motorCurrent_); } { BASE fd.setMotorPower(80); motor.setMotorRatedVoltage(200); motor.setFullLoadAmps(519.3); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(35.2,ex.motorPowerFactor_); Check(284.9,ex.motorCurrent_); } { BASE CALC Check(217.5,ex.motorCurrent_); } { BASE fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT); fd.setMotorAmps(218); fd.setMotorPower(0); CALC Check(150.4,ex.motorPower_); Check100(72.5,ex.pumpEfficiency_); } { BASE fd.setMotorPower(80); CALC Check(700.8,ex.annualEnergy_); } { BASE fin.setOperatingFraction(.25); CALC Check(328.5,ex.annualEnergy_); Check(16.4,ex.annualCost_); } { BASE motor.setFullLoadAmps(300); CALC Check(288.9,ex.motorCurrent_); } { BASE motor.setEfficiencyClass(Motor::EfficiencyClass(0)); CALC Check(213.7,ex.motorCurrent_); } { BASE motor.setEfficiencyClass(Motor::EfficiencyClass(2)); motor.setSpecifiedEfficiency(75); CALC Check(173.7,ex.motorCurrent_); } cout << "done"; } void Wtf(const FunctionCallbackInfo<Value>& args) { } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); NODE_SET_METHOD(exports, "estFLA", EstFLA); NODE_SET_METHOD(exports, "motorPerformance", MotorPerformance); NODE_SET_METHOD(exports, "test", Test); NODE_SET_METHOD(exports, "wtf", Wtf); } NODE_MODULE(bridge, Init) <commit_msg>no message<commit_after>#include <iostream> #include <vector> #include <map> #include <node.h> #include "PSATResult.h" #include "calculator/EstimateFLA.h" #include "calculator/MotorCurrent.h" #include "calculator/MotorPowerFactor.h" #include "calculator/OptimalPrePumpEff.h" #include "calculator/OptimalSpecificSpeedCorrection.h" #include "calculator/OptimalDeviationFactor.h" using namespace v8; using namespace std; Isolate* iso; Local<Object> inp; Local<Object> r; double Get(const char *nm) { auto rObj = inp->ToObject()->Get(String::NewFromUtf8(iso,nm)); if (rObj->IsUndefined()) { cout << nm << endl;; assert(!"defined"); } return rObj->NumberValue(); } Motor::LineFrequency line() { return (Motor::LineFrequency)(int)(!Get("line")); } Motor::EfficiencyClass effCls() { return (Motor::EfficiencyClass)(int)Get("efficiency_class"); } Pump::Drive drive() { return (Pump::Drive)(int)Get("drive"); } void Setup(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); inp = args[0]->ToObject(); r = Object::New(iso); args.GetReturnValue().Set(r); } void Results(const FunctionCallbackInfo<Value>& args) { Setup(args); Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_specified"),Get("pump_rated_speed"),drive(), Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed"))); Motor motor(line(),Get("motor_rated_power"),Get("motor_rated_speed"),effCls(), Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin")); Financial fin(Get("fraction"),Get("cost")); FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1), Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage")); PSATResult psat(pump,motor,fin,fd); psat.calculateExisting(); psat.calculateOptimal(); auto ex = psat.getExisting(), opt = psat.getOptimal(); map<const char *,vector<double>> out = { {"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}}, {"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}}, {"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}}, {"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}}, {"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}}, {"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}}, {"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}}, {"Motor Power", {ex.motorPower_,opt.motorPower_}}, {"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}}, {"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}}, {"Savings Potential", {psat.getAnnualSavingsPotential(),-1}}, {"Optimization Rating", {psat.getOptimizationRating(),-1}} }; for(auto p: out) { auto a = Array::New(iso); a->Set(0,Number::New(iso,p.second[0])); a->Set(1,Number::New(iso,p.second[1])); r->Set(String::NewFromUtf8(iso,p.first),a); } } void EstFLA(const FunctionCallbackInfo<Value>& args) { Setup(args); EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),line(),effCls(), Get("efficiency"),Get("motor_rated_voltage")); fla.calculate(); args.GetReturnValue().Set(fla.getEstimatedFLA()); } void MotorPerformance(const FunctionCallbackInfo<Value>& args) { Setup(args); MotorEfficiency mef(line(),Get("motor_rated_speed"),effCls(),Get("efficiency"),Get("motor_rated_power"),Get("load_factor")); auto mefVal = mef.calculate(); r->Set(String::NewFromUtf8(iso,"efficiency"),Number::New(iso,mefVal*100)); MotorCurrent mc(Get("motor_rated_power"),Get("motor_rated_speed"),line(),effCls(),Get("efficiency"),Get("load_factor"),Get("motor_rated_voltage"),Get("flc")); auto mcVal = mc.calculate(); r->Set(String::NewFromUtf8(iso,"current"),Number::New(iso,mcVal/225.8*100)); MotorPowerFactor pf(Get("motor_rated_power"),Get("load_factor"),mcVal,mefVal,Get("motor_rated_voltage")); r->Set(String::NewFromUtf8(iso,"pf"),Number::New(iso,pf.calculate()*100)); } //TODO round vs js round; loosen up to make next test case void Check(double exp, double act, const char* nm="") { //cout << "e " << exp << "; a " << act << endl; // if (isnan(act) || (abs(exp-act)>.01*exp)) { auto p = 10; if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) { printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act); assert(!"equal"); } } void Check100(double exp, double act, const char* nm="") { Check(exp,act*100,nm); } void Test(const FunctionCallbackInfo<Value>& args) { EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460); fla.calculate(); Check(225.8,fla.getEstimatedFLA()); // motor perf { MotorEfficiency mef(Motor::LineFrequency::FREQ60,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,.75); auto mefVal = mef.calculate(); Check100(95.69,mefVal); MotorCurrent mc(200,1780,Motor::LineFrequency::FREQ60,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,.75,460,225.8); auto mcVal = mc.calculate(); Check100(76.63,mcVal/225.8); MotorPowerFactor pf(200,.75,mcVal,mefVal,460); Check100(84.82,pf.calculate()); } //nema { MotorEfficiency mef(Motor::LineFrequency::FREQ60,1200, Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,1); //Check100(95,mef.calculate()); } //pump eff { OptimalPrePumpEff pef(Pump::Style::END_SUCTION_ANSI_API, 0, 2000); OptimalDeviationFactor df(2000); // Check(87.1,pef.calculate()*df.calculate()); } //spec speed { OptimalSpecificSpeedCorrection cor(Pump::Style::END_SUCTION_ANSI_API, 1170); //Check100(2.3,cor.calculate()); } return; #define BASE \ Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\ 1,1,1,Pump::Speed::NOT_FIXED_SPEED);\ Motor motor(Motor::LineFrequency::FREQ60,200,1780,\ Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\ Financial fin(1,.05);\ FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\ 150,0,460); #define CALC \ PSATResult psat(pump,motor,fin,fd);\ psat.calculateExisting();\ auto ex = psat.getExisting(); for (int i=1; i<=10000; i=i+2) { BASE CALC Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME"); } { BASE motor.setMotorRpm(1786); fd.setMotorPower(80); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(79.1,ex.motorPowerFactor_); Check(127,ex.motorCurrent_); } { BASE fd.setMotorPower(80); motor.setMotorRatedPower(100); motor.setFullLoadAmps(113.8); CALC Check(101.8,ex.motorShaftPower_); Check100(94.9,ex.motorEfficiency_); Check100(86.7,ex.motorPowerFactor_); Check(115.8,ex.motorCurrent_); } { BASE fd.setMotorPower(80); fd.setVoltage(260); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(138.8,ex.motorPowerFactor_); Check(128,ex.motorCurrent_); } { BASE motor.setMotorRpm(1200); fd.setMotorPower(80); motor.setFullLoadAmps(235.3); CALC Check(101.4,ex.motorShaftPower_); Check100(94.5,ex.motorEfficiency_); Check100(74.3,ex.motorPowerFactor_); Check(135.1,ex.motorCurrent_); } { BASE fd.setMotorPower(111.855); CALC Check(143.4,ex.motorShaftPower_); Check100(95.6,ex.motorEfficiency_); Check100(84.3,ex.motorPowerFactor_); Check(166.5,ex.motorCurrent_); } { BASE fd.setMotorPower(80); motor.setMotorRatedVoltage(200); motor.setFullLoadAmps(519.3); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(35.2,ex.motorPowerFactor_); Check(284.9,ex.motorCurrent_); } { BASE CALC Check(217.5,ex.motorCurrent_); } { BASE fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT); fd.setMotorAmps(218); fd.setMotorPower(0); CALC Check(150.4,ex.motorPower_); Check100(72.5,ex.pumpEfficiency_); } { BASE fd.setMotorPower(80); CALC Check(700.8,ex.annualEnergy_); } { BASE fin.setOperatingFraction(.25); CALC Check(328.5,ex.annualEnergy_); Check(16.4,ex.annualCost_); } { BASE motor.setFullLoadAmps(300); CALC Check(288.9,ex.motorCurrent_); } { BASE motor.setEfficiencyClass(Motor::EfficiencyClass(0)); CALC Check(213.7,ex.motorCurrent_); } { BASE motor.setEfficiencyClass(Motor::EfficiencyClass(2)); motor.setSpecifiedEfficiency(75); CALC Check(173.7,ex.motorCurrent_); } cout << "done"; } void Wtf(const FunctionCallbackInfo<Value>& args) { } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); NODE_SET_METHOD(exports, "estFLA", EstFLA); NODE_SET_METHOD(exports, "motorPerformance", MotorPerformance); NODE_SET_METHOD(exports, "test", Test); NODE_SET_METHOD(exports, "wtf", Wtf); } NODE_MODULE(bridge, Init) <|endoftext|>
<commit_before>/************************************* ** Tsunagari Tile Engine ** ** ui-log.cpp ** ** Copyright 2016-2017 Paul Merrill ** *************************************/ // ********** // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ********** #include "pack/ui.h" #include "pack/pool.h" #include "util/unique.h" static Unique<Pool> pool(Pool::makePool("ui", 1)); void uiShowAddingFile(const std::string& path) { pool->schedule([=] { printf("Adding %s\n", path.c_str()); }); } void uiShowWritingArchive(const std::string& archivePath) { pool->schedule([=] { printf("Writing to %s\n", archivePath.c_str()); }); } void uiShowListingEntry(const std::string& blobPath, uint64_t blobSize) { pool->schedule([=] { printf("%s: %llu bytes\n", blobPath.c_str(), blobSize); }); } void uiShowExtractingFile(const std::string& blobPath, uint64_t blobSize) { pool->schedule([=] { printf("Extracting %s: %llu bytes\n", blobPath.c_str(), blobSize); }); } <commit_msg>ui-log: Fix warning on GCC<commit_after>/************************************* ** Tsunagari Tile Engine ** ** ui-log.cpp ** ** Copyright 2016-2017 Paul Merrill ** *************************************/ // ********** // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ********** #include "pack/ui.h" #include "pack/pool.h" #include "util/unique.h" static Unique<Pool> pool(Pool::makePool("ui", 1)); void uiShowAddingFile(const std::string& path) { pool->schedule([=] { printf("Adding %s\n", path.c_str()); }); } void uiShowWritingArchive(const std::string& archivePath) { pool->schedule([=] { printf("Writing to %s\n", archivePath.c_str()); }); } void uiShowListingEntry(const std::string& blobPath, uint64_t blobSize) { pool->schedule([=] { printf("%s: %lu bytes\n", blobPath.c_str(), blobSize); }); } void uiShowExtractingFile(const std::string& blobPath, uint64_t blobSize) { pool->schedule([=] { printf("Extracting %s: %lu bytes\n", blobPath.c_str(), blobSize); }); } <|endoftext|>
<commit_before>#ifndef slic3r_Preferences_hpp_ #define slic3r_Preferences_hpp_ #include "GUI.hpp" #include "GUI_Utils.hpp" #include <wx/dialog.h> #include <map> namespace Slic3r { namespace GUI { class ConfigOptionsGroup; class PreferencesDialog : public DPIDialog { std::map<std::string, std::string> m_values; std::shared_ptr<ConfigOptionsGroup> m_optgroup_general; std::shared_ptr<ConfigOptionsGroup> m_optgroup_camera; std::shared_ptr<ConfigOptionsGroup> m_optgroup_gui; wxSizer* m_icon_size_sizer; wxRadioBox* m_layout_mode_box; bool isOSX {false}; public: PreferencesDialog(wxWindow* parent); ~PreferencesDialog() {} void build(); void accept(); protected: void on_dpi_changed(const wxRect &suggested_rect) override; void layout(); void create_icon_size_slider(); void create_settings_mode_widget(); }; } // GUI } // Slic3r #endif /* slic3r_Preferences_hpp_ */ <commit_msg>Fixed OSX build<commit_after>#ifndef slic3r_Preferences_hpp_ #define slic3r_Preferences_hpp_ #include "GUI.hpp" #include "GUI_Utils.hpp" #include <wx/dialog.h> #include <map> class wxRadioBox; namespace Slic3r { namespace GUI { class ConfigOptionsGroup; class PreferencesDialog : public DPIDialog { std::map<std::string, std::string> m_values; std::shared_ptr<ConfigOptionsGroup> m_optgroup_general; std::shared_ptr<ConfigOptionsGroup> m_optgroup_camera; std::shared_ptr<ConfigOptionsGroup> m_optgroup_gui; wxSizer* m_icon_size_sizer; wxRadioBox* m_layout_mode_box; bool isOSX {false}; public: PreferencesDialog(wxWindow* parent); ~PreferencesDialog() {} void build(); void accept(); protected: void on_dpi_changed(const wxRect &suggested_rect) override; void layout(); void create_icon_size_slider(); void create_settings_mode_widget(); }; } // GUI } // Slic3r #endif /* slic3r_Preferences_hpp_ */ <|endoftext|>
<commit_before>#include <nan.h> #include <node.h> #include <string> #include <cstring> #include "../include/str_array_converter.h" #include "git2/strarray.h" using namespace v8; using namespace node; git_strarray *StrArrayConverter::Convert(Handle<v8::Value> val) { if (!val->BooleanValue()) { return NULL; } else if (val->IsArray()) { return ConvertArray(Array::Cast(*val)); } else if (val->IsString() || val->IsStringObject()) { return ConvertString(val->ToString()); } else { return NULL; } } static git_strarray * StrArrayConverter::AllocStrArray(const size_t count) { const size_t size = sizeof(git_strarray) + (sizeof(char*) * count); uint8_t* memory = reinterpret_cast<uint8_t*>(malloc(size)); git_strarray *result = reinterpret_cast<git_strarray *>(memory); result->count = count; result->strings = reinterpret_cast<char**>(memory + sizeof(git_strarray)); return result; } git_strarray *StrArrayConverter::ConvertArray(Array *val) { git_strarray *result = AllocStrArray(val->Length()); for(size_t i = 0; i < result->count; i++) { NanUtf8String entry(val->Get(i)); result->strings[i] = strdup(*entry); } return result; } git_strarray* StrArrayConverter::ConvertString(Handle<String> val) { char *strings[1]; NanUtf8String utf8String(val); strings[0] = *utf8String; return ConstructStrArray(1, strings); } git_strarray *StrArrayConverter::ConstructStrArray(int argc, char** argv) { git_strarray *result = AllocStrArray(argc); for(size_t i = 0; i < result->count; i++) { result->strings[i] = strdup(argv[i]); } return result; } <commit_msg>Fix to the StrConverter<commit_after>#include <nan.h> #include <node.h> #include <string> #include <cstring> #include "../include/str_array_converter.h" #include "git2/strarray.h" using namespace v8; using namespace node; git_strarray *StrArrayConverter::Convert(Handle<v8::Value> val) { if (!val->BooleanValue()) { return NULL; } else if (val->IsArray()) { return ConvertArray(Array::Cast(*val)); } else if (val->IsString() || val->IsStringObject()) { return ConvertString(val->ToString()); } else { return NULL; } } git_strarray * StrArrayConverter::AllocStrArray(const size_t count) { const size_t size = sizeof(git_strarray) + (sizeof(char*) * count); uint8_t* memory = reinterpret_cast<uint8_t*>(malloc(size)); git_strarray *result = reinterpret_cast<git_strarray *>(memory); result->count = count; result->strings = reinterpret_cast<char**>(memory + sizeof(git_strarray)); return result; } git_strarray *StrArrayConverter::ConvertArray(Array *val) { git_strarray *result = AllocStrArray(val->Length()); for(size_t i = 0; i < result->count; i++) { NanUtf8String entry(val->Get(i)); result->strings[i] = strdup(*entry); } return result; } git_strarray* StrArrayConverter::ConvertString(Handle<String> val) { char *strings[1]; NanUtf8String utf8String(val); strings[0] = *utf8String; return ConstructStrArray(1, strings); } git_strarray *StrArrayConverter::ConstructStrArray(int argc, char** argv) { git_strarray *result = AllocStrArray(argc); for(size_t i = 0; i < result->count; i++) { result->strings[i] = strdup(argv[i]); } return result; } <|endoftext|>
<commit_before>/** * pty.cc * This file is responsible for starting processes * with pseudo-terminal file descriptors. * * man pty * man tty_ioctl * man tcsetattr * man forkpty */ #include <v8.h> #include <node.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> /* forkpty */ /* http://www.gnu.org/software/gnulib/manual/html_node/forkpty.html */ #if defined(__GLIBC__) || defined(__CYGWIN__) #include <pty.h> #elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__) #include <util.h> #elif defined(__FreeBSD__) #include <libutil.h> #else #include <pty.h> #endif #include <utmp.h> /* login_tty */ #include <termios.h> /* tcgetattr, tty_ioctl */ using namespace std; using namespace node; using namespace v8; static Handle<Value> PtyFork(const Arguments&); static Handle<Value> PtyResize(const Arguments&); static int pty_execvpe(const char *file, char **argv, char **envp); static int pty_nonblock(int fd); extern "C" void init(Handle<Object>); static Handle<Value> PtyFork(const Arguments& args) { HandleScope scope; if (args.Length() < 6) { return ThrowException(Exception::Error( String::New("Not enough arguments."))); } if (!args[0]->IsString()) { return ThrowException(Exception::Error( String::New("file must be a string."))); } if (!args[1]->IsArray()) { return ThrowException(Exception::Error( String::New("args must be an array."))); } if (!args[2]->IsArray()) { return ThrowException(Exception::Error( String::New("env must be an array."))); } if (!args[3]->IsString()) { return ThrowException(Exception::Error( String::New("cwd must be a string."))); } if (!args[4]->IsNumber() || !args[5]->IsNumber()) { return ThrowException(Exception::Error( String::New("cols and rows must be numbers."))); } // node/src/node_child_process.cc // file String::Utf8Value file(args[0]->ToString()); // args int i = 0; Local<Array> argv_ = Local<Array>::Cast(args[1]); int argc = argv_->Length(); int argl = argc + 1 + 1; char **argv = new char*[argl]; argv[0] = strdup(*file); argv[argl-1] = NULL; for (; i < argc; i++) { String::Utf8Value arg(argv_->Get(Integer::New(i))->ToString()); argv[i+1] = strdup(*arg); } // env i = 0; Local<Array> env_ = Local<Array>::Cast(args[2]); int envc = env_->Length(); char **env = new char*[envc+1]; env[envc] = NULL; for (; i < envc; i++) { String::Utf8Value pair(env_->Get(Integer::New(i))->ToString()); env[i] = strdup(*pair); } // cwd String::Utf8Value cwd_(args[3]->ToString()); char *cwd = strdup(*cwd_); // size struct winsize winp = {}; Local<Integer> cols = args[4]->ToInteger(); Local<Integer> rows = args[5]->ToInteger(); winp.ws_col = cols->Value(); winp.ws_row = rows->Value(); // fork the pty int master; char name[40]; pid_t pid = forkpty(&master, name, NULL, &winp); switch (pid) { case -1: return ThrowException(Exception::Error( String::New("forkpty failed."))); case 0: if (strlen(cwd)) chdir(cwd); pty_execvpe(argv[0], argv, env); perror("execvp failed"); _exit(1); default: // cleanup for (i = 0; i < argl; i++) free(argv[i]); delete[] argv; for (i = 0; i < envc; i++) free(env[i]); delete[] env; free(cwd); // nonblocking if (pty_nonblock(master) == -1) { return ThrowException(Exception::Error( String::New("Could not set master fd to nonblocking."))); } Local<Object> obj = Object::New(); obj->Set(String::New("fd"), Number::New(master)); obj->Set(String::New("pid"), Number::New(pid)); obj->Set(String::New("pty"), String::New(name)); return scope.Close(obj); } return Undefined(); } /** * Expose Resize Functionality */ static Handle<Value> PtyResize(const Arguments& args) { HandleScope scope; if (args.Length() > 0 && !args[0]->IsNumber()) { return ThrowException(Exception::Error( String::New("First argument must be a number."))); } struct winsize winp = {}; winp.ws_col = 80; winp.ws_row = 30; int fd = args[0]->ToInteger()->Value(); if (args.Length() == 3) { if (args[1]->IsNumber() && args[2]->IsNumber()) { Local<Integer> cols = args[1]->ToInteger(); Local<Integer> rows = args[2]->ToInteger(); winp.ws_col = cols->Value(); winp.ws_row = rows->Value(); } else { return ThrowException(Exception::Error( String::New("cols and rows need to be numbers."))); } } if (ioctl(fd, TIOCSWINSZ, &winp) == -1) { return ThrowException(Exception::Error( String::New("ioctl failed."))); } return Undefined(); } /** * execvpe */ // execvpe(3) is not portable. // http://www.gnu.org/software/gnulib/manual/html_node/execvpe.html static int pty_execvpe(const char *file, char **argv, char **envp) { char **old = environ; environ = envp; int ret = execvp(file, argv); environ = old; return ret; } /** * FD to nonblocking */ static int pty_nonblock(int fd) { int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) return -1; return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } /** * Init */ extern "C" void init(Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "fork", PtyFork); NODE_SET_METHOD(target, "resize", PtyResize); } <commit_msg>fix build on mac. closes #4.<commit_after>/** * pty.cc * This file is responsible for starting processes * with pseudo-terminal file descriptors. * * man pty * man tty_ioctl * man tcsetattr * man forkpty */ #include <v8.h> #include <node.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> /* forkpty */ /* http://www.gnu.org/software/gnulib/manual/html_node/forkpty.html */ #if defined(__GLIBC__) || defined(__CYGWIN__) #include <pty.h> #elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__) #include <util.h> #elif defined(__FreeBSD__) #include <libutil.h> #else #include <pty.h> #endif #include <utmp.h> /* login_tty */ #include <termios.h> /* tcgetattr, tty_ioctl */ // environ for execvpe #ifdef __APPLE__ #include <crt_externs.h> #define environ (*_NSGetEnviron()) #else extern char **environ; #endif using namespace std; using namespace node; using namespace v8; static Handle<Value> PtyFork(const Arguments&); static Handle<Value> PtyResize(const Arguments&); static int pty_execvpe(const char *file, char **argv, char **envp); static int pty_nonblock(int fd); extern "C" void init(Handle<Object>); static Handle<Value> PtyFork(const Arguments& args) { HandleScope scope; if (args.Length() < 6) { return ThrowException(Exception::Error( String::New("Not enough arguments."))); } if (!args[0]->IsString()) { return ThrowException(Exception::Error( String::New("file must be a string."))); } if (!args[1]->IsArray()) { return ThrowException(Exception::Error( String::New("args must be an array."))); } if (!args[2]->IsArray()) { return ThrowException(Exception::Error( String::New("env must be an array."))); } if (!args[3]->IsString()) { return ThrowException(Exception::Error( String::New("cwd must be a string."))); } if (!args[4]->IsNumber() || !args[5]->IsNumber()) { return ThrowException(Exception::Error( String::New("cols and rows must be numbers."))); } // node/src/node_child_process.cc // file String::Utf8Value file(args[0]->ToString()); // args int i = 0; Local<Array> argv_ = Local<Array>::Cast(args[1]); int argc = argv_->Length(); int argl = argc + 1 + 1; char **argv = new char*[argl]; argv[0] = strdup(*file); argv[argl-1] = NULL; for (; i < argc; i++) { String::Utf8Value arg(argv_->Get(Integer::New(i))->ToString()); argv[i+1] = strdup(*arg); } // env i = 0; Local<Array> env_ = Local<Array>::Cast(args[2]); int envc = env_->Length(); char **env = new char*[envc+1]; env[envc] = NULL; for (; i < envc; i++) { String::Utf8Value pair(env_->Get(Integer::New(i))->ToString()); env[i] = strdup(*pair); } // cwd String::Utf8Value cwd_(args[3]->ToString()); char *cwd = strdup(*cwd_); // size struct winsize winp = {}; Local<Integer> cols = args[4]->ToInteger(); Local<Integer> rows = args[5]->ToInteger(); winp.ws_col = cols->Value(); winp.ws_row = rows->Value(); // fork the pty int master; char name[40]; pid_t pid = forkpty(&master, name, NULL, &winp); switch (pid) { case -1: return ThrowException(Exception::Error( String::New("forkpty failed."))); case 0: if (strlen(cwd)) chdir(cwd); pty_execvpe(argv[0], argv, env); perror("execvp failed"); _exit(1); default: // cleanup for (i = 0; i < argl; i++) free(argv[i]); delete[] argv; for (i = 0; i < envc; i++) free(env[i]); delete[] env; free(cwd); // nonblocking if (pty_nonblock(master) == -1) { return ThrowException(Exception::Error( String::New("Could not set master fd to nonblocking."))); } Local<Object> obj = Object::New(); obj->Set(String::New("fd"), Number::New(master)); obj->Set(String::New("pid"), Number::New(pid)); obj->Set(String::New("pty"), String::New(name)); return scope.Close(obj); } return Undefined(); } /** * Expose Resize Functionality */ static Handle<Value> PtyResize(const Arguments& args) { HandleScope scope; if (args.Length() > 0 && !args[0]->IsNumber()) { return ThrowException(Exception::Error( String::New("First argument must be a number."))); } struct winsize winp = {}; winp.ws_col = 80; winp.ws_row = 30; int fd = args[0]->ToInteger()->Value(); if (args.Length() == 3) { if (args[1]->IsNumber() && args[2]->IsNumber()) { Local<Integer> cols = args[1]->ToInteger(); Local<Integer> rows = args[2]->ToInteger(); winp.ws_col = cols->Value(); winp.ws_row = rows->Value(); } else { return ThrowException(Exception::Error( String::New("cols and rows need to be numbers."))); } } if (ioctl(fd, TIOCSWINSZ, &winp) == -1) { return ThrowException(Exception::Error( String::New("ioctl failed."))); } return Undefined(); } /** * execvpe */ // execvpe(3) is not portable. // http://www.gnu.org/software/gnulib/manual/html_node/execvpe.html static int pty_execvpe(const char *file, char **argv, char **envp) { char **old = environ; environ = envp; int ret = execvp(file, argv); environ = old; return ret; } /** * FD to nonblocking */ static int pty_nonblock(int fd) { int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) return -1; return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } /** * Init */ extern "C" void init(Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "fork", PtyFork); NODE_SET_METHOD(target, "resize", PtyResize); } <|endoftext|>
<commit_before>/******************************************************************** * AUTHORS: Vijay Ganesh * * BEGIN DATE: November, 2005 * * LICENSE: Please view LICENSE file in the home dir of this Program ********************************************************************/ // -*- c++ -*- #include <iostream> #include <sstream> #include <string> #include <algorithm> #include <ctime> #include <unistd.h> #include <signal.h> //#include <zlib.h> #include <stdio.h> #include "../AST/AST.h" #include "../sat/core/Solver.h" #include "../sat/core/SolverTypes.h" //#include "../sat/VarOrder.h" #include <unistd.h> #ifdef EXT_HASH_MAP using namespace __gnu_cxx; #endif /* GLOBAL FUNCTION: parser */ extern int smtparse(); extern int cvcparse(); namespace BEEV { extern BEEV::ASTNode SingleBitOne; extern BEEV::ASTNode SingleBitZero; } /* GLOBAL VARS: Some global vars for the Main function. * */ const char * prog = "stp"; int linenum = 1; const char * usage = "Usage: %s [-option] [infile]\n"; std::string helpstring = "\n\n"; // Amount of memory to ask for at beginning of main. static const intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE = 4000000; /****************************************************************************** * MAIN FUNCTION: * * step 0. Parse the input into an ASTVec. * step 1. Do BV Rewrites * step 2. Bitblasts the ASTNode. * step 3. Convert to CNF * step 4. Convert to SAT * step 5. Call SAT to determine if input is SAT or UNSAT ******************************************************************************/ int main(int argc, char ** argv) { char * infile; extern FILE *cvcin; extern FILE *smtin; // Grab some memory from the OS upfront to reduce system time when individual // hash tables are being allocated if (sbrk(INITIAL_MEMORY_PREALLOCATION_SIZE) == ((void *) -1)) { // FIXME: figure out how to get and print the real error message. BEEV::FatalError("Initial allocation of memory failed."); } //populate the help string helpstring += "-r : switch refinement off (optimizations are ON by default)\n"; helpstring += "-w : switch wordlevel solver off (optimizations are ON by default)\n"; helpstring += "-a : switch optimizations off (optimizations are ON by default)\n"; helpstring += "-s : print function statistics\n"; helpstring += "-v : print nodes \n"; helpstring += "-c : construct counterexample\n"; helpstring += "-d : check counterexample\n"; helpstring += "-p : print counterexample\n"; helpstring += "-y : print counterexample in binary\n"; helpstring += "-b : STP input read back\n"; helpstring += "-x : flatten nested XORs\n"; helpstring += "-h : help\n"; helpstring += "-m : use the SMTLIB parser\n"; for(int i=1; i < argc;i++) { if(argv[i][0] == '-') { switch(argv[i][1]) { case 'a' : BEEV::optimize_flag = false; break; case 'b': BEEV::print_STPinput_back_flag = true; break; case 'c': BEEV::construct_counterexample_flag = true; break; case 'd': BEEV::construct_counterexample_flag = true; BEEV::check_counterexample_flag = true; break; case 'h': fprintf(stderr,usage,prog); cout << helpstring; //BEEV::FatalError(""); return -1; break; case 'n': BEEV::print_output_flag = true; break; case 'm': BEEV::smtlib_parser_flag=true; BEEV::division_by_zero_returns_one = true; break; case 'p': BEEV::print_counterexample_flag = true; break; case 'y': BEEV::print_binary_flag = true; break; case 'q': BEEV::print_arrayval_declaredorder_flag = true; break; case 'r': BEEV::arrayread_refinement_flag = false; break; case 's' : BEEV::stats_flag = true; break; case 'u': BEEV::arraywrite_refinement_flag = false; break; case 'v' : BEEV::print_nodes_flag = true; break; case 'w': BEEV::wordlevel_solve_flag = false; break; case 'x': BEEV::xor_flatten_flag = true; break; case 'z': BEEV::print_sat_varorder_flag = true; break; default: fprintf(stderr,usage,prog); cout << helpstring; //BEEV::FatalError(""); return -1; break; } if(argv[i][2]) { fprintf(stderr, "Multiple character options are not allowed.\n"); fprintf(stderr, "(for example: -ab is not an abbreviation for -a -b)\n"); fprintf(stderr,usage,prog); cout << helpstring; return -1; } } else { infile = argv[i]; if (BEEV::smtlib_parser_flag) { smtin = fopen(infile,"r"); if(smtin == NULL) { fprintf(stderr,"%s: Error: cannot open %s\n",prog,infile); BEEV::FatalError(""); } } else { cvcin = fopen(infile,"r"); if(cvcin == NULL) { fprintf(stderr,"%s: Error: cannot open %s\n",prog,infile); BEEV::FatalError(""); } } } } CONSTANTBV::ErrCode c = CONSTANTBV::BitVector_Boot(); if(0 != c) { cout << CONSTANTBV::BitVector_Error(c) << endl; return 0; } //want to print the output always from the commandline. BEEV::print_output_flag = true; BEEV::globalBeevMgr_for_parser = new BEEV::BeevMgr(); BEEV::SingleBitOne = BEEV::globalBeevMgr_for_parser->CreateOneConst(1); BEEV::SingleBitZero = BEEV::globalBeevMgr_for_parser->CreateZeroConst(1); if (BEEV::smtlib_parser_flag) smtparse(); else cvcparse(); }//end of Main <commit_msg>Trying to get version number in the executable<commit_after>/******************************************************************** * AUTHORS: Vijay Ganesh * * BEGIN DATE: November, 2005 * * LICENSE: Please view LICENSE file in the home dir of this Program ********************************************************************/ // -*- c++ -*- #include <iostream> #include <sstream> #include <string> #include <algorithm> #include <ctime> #include <unistd.h> #include <signal.h> //#include <zlib.h> #include <stdio.h> #include "../AST/AST.h" #include "../sat/core/Solver.h" #include "../sat/core/SolverTypes.h" //#include "../sat/VarOrder.h" #include <unistd.h> #ifdef EXT_HASH_MAP using namespace __gnu_cxx; #endif /* GLOBAL FUNCTION: parser */ extern int smtparse(); extern int cvcparse(); namespace BEEV { extern BEEV::ASTNode SingleBitOne; extern BEEV::ASTNode SingleBitZero; } const string version = "$Id$"; /* GLOBAL VARS: Some global vars for the Main function. * */ const char * prog = "stp"; int linenum = 1; const char * usage = "Usage: %s [-option] [infile]\n"; std::string helpstring = "\n\n"; // Amount of memory to ask for at beginning of main. static const intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE = 4000000; /****************************************************************************** * MAIN FUNCTION: * * step 0. Parse the input into an ASTVec. * step 1. Do BV Rewrites * step 2. Bitblasts the ASTNode. * step 3. Convert to CNF * step 4. Convert to SAT * step 5. Call SAT to determine if input is SAT or UNSAT ******************************************************************************/ int main(int argc, char ** argv) { char * infile; extern FILE *cvcin; extern FILE *smtin; // Grab some memory from the OS upfront to reduce system time when individual // hash tables are being allocated if (sbrk(INITIAL_MEMORY_PREALLOCATION_SIZE) == ((void *) -1)) { // FIXME: figure out how to get and print the real error message. BEEV::FatalError("Initial allocation of memory failed."); } //populate the help string helpstring += "-r : switch refinement off (optimizations are ON by default)\n"; helpstring += "-w : switch wordlevel solver off (optimizations are ON by default)\n"; helpstring += "-a : switch optimizations off (optimizations are ON by default)\n"; helpstring += "-s : print function statistics\n"; helpstring += "-v : print nodes \n"; helpstring += "-c : construct counterexample\n"; helpstring += "-d : check counterexample\n"; helpstring += "-p : print counterexample\n"; helpstring += "-y : print counterexample in binary\n"; helpstring += "-b : STP input read back\n"; helpstring += "-x : flatten nested XORs\n"; helpstring += "-h : help\n"; helpstring += "-m : use the SMTLIB parser\n"; for(int i=1; i < argc;i++) { if(argv[i][0] == '-') { switch(argv[i][1]) { case 'a' : BEEV::optimize_flag = false; break; case 'b': BEEV::print_STPinput_back_flag = true; break; case 'c': BEEV::construct_counterexample_flag = true; break; case 'd': BEEV::construct_counterexample_flag = true; BEEV::check_counterexample_flag = true; break; case 'h': fprintf(stderr,usage,prog); cout << helpstring; //BEEV::FatalError(""); return -1; break; case 'n': BEEV::print_output_flag = true; break; case 'm': BEEV::smtlib_parser_flag=true; BEEV::division_by_zero_returns_one = true; break; case 'p': BEEV::print_counterexample_flag = true; break; case 'y': BEEV::print_binary_flag = true; break; case 'q': BEEV::print_arrayval_declaredorder_flag = true; break; case 'r': BEEV::arrayread_refinement_flag = false; break; case 's' : BEEV::stats_flag = true; break; case 'u': BEEV::arraywrite_refinement_flag = false; break; case 'v' : BEEV::print_nodes_flag = true; break; case 'w': BEEV::wordlevel_solve_flag = false; break; case 'x': BEEV::xor_flatten_flag = true; break; case 'z': BEEV::print_sat_varorder_flag = true; break; default: fprintf(stderr,usage,prog); cout << helpstring; //BEEV::FatalError(""); return -1; break; } if(argv[i][2]) { fprintf(stderr, "Multiple character options are not allowed.\n"); fprintf(stderr, "(for example: -ab is not an abbreviation for -a -b)\n"); fprintf(stderr,usage,prog); cout << helpstring; return -1; } } else { infile = argv[i]; if (BEEV::smtlib_parser_flag) { smtin = fopen(infile,"r"); if(smtin == NULL) { fprintf(stderr,"%s: Error: cannot open %s\n",prog,infile); BEEV::FatalError(""); } } else { cvcin = fopen(infile,"r"); if(cvcin == NULL) { fprintf(stderr,"%s: Error: cannot open %s\n",prog,infile); BEEV::FatalError(""); } } } } CONSTANTBV::ErrCode c = CONSTANTBV::BitVector_Boot(); if(0 != c) { cout << CONSTANTBV::BitVector_Error(c) << endl; return 0; } //want to print the output always from the commandline. BEEV::print_output_flag = true; BEEV::globalBeevMgr_for_parser = new BEEV::BeevMgr(); BEEV::SingleBitOne = BEEV::globalBeevMgr_for_parser->CreateOneConst(1); BEEV::SingleBitZero = BEEV::globalBeevMgr_for_parser->CreateZeroConst(1); if (BEEV::smtlib_parser_flag) smtparse(); else cvcparse(); }//end of Main <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Victor Gaydov * * 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 <CppUTest/TestHarness.h> #include "roc_config/config.h" #include "roc_core/scoped_ptr.h" #include "roc_rtp/composer.h" #include "roc_rtp/parser.h" #include "roc_datagram/datagram_queue.h" #include "roc_pipeline/client.h" #include "roc_pipeline/server.h" #include "test_sample_stream.h" #include "test_sample_queue.h" #include "test_datagram.h" namespace roc { namespace test { using namespace pipeline; TEST_GROUP(client_server) { enum { // Sending port. ClientPort = 501, // Receiving port. ServerPort = 502, // Number of samples in every channel per packet. PktSamples = ROC_CONFIG_DEFAULT_PACKET_SAMPLES, // Number of samples in input/output buffers. BufSamples = SampleStream::ReadBufsz, // Number of packets to read per tick. PacketsPerTick = 20, // Maximum number of sample buffers. MaxBuffers = PktSamples * 100 / BufSamples, // Percentage of packets to be lost. RandomLoss = 1 }; SampleQueue<MaxBuffers> input; SampleQueue<MaxBuffers> output; datagram::DatagramQueue network; TestDatagramComposer datagram_composer; rtp::Composer packet_composer; rtp::Parser packet_parser; core::ScopedPtr<Client> client; core::ScopedPtr<Server> server; void setup() { } void teardown() { LONGS_EQUAL(0, input.size()); LONGS_EQUAL(0, output.size()); LONGS_EQUAL(0, network.size()); } void init_client(int options, size_t random_loss = 0) { ClientConfig config; config.options = options; config.channels = ChannelMask; config.samples_per_packet = PktSamples; config.random_loss_rate = random_loss; client.reset( new Client(input, network, datagram_composer, packet_composer, config)); client->set_sender(new_address(ClientPort)); client->set_receiver(new_address(ServerPort)); } void init_server(int options) { ServerConfig config; config.options = options; config.channels = ChannelMask; config.latency = BufSamples; config.timeout = MaxBuffers; server.reset(new Server(network, output, config)); server->add_port(new_address(ServerPort), packet_parser); } void flow_client_server() { SampleStream si; for (size_t n = 0; n < MaxBuffers; n++) { si.write(input, BufSamples); } LONGS_EQUAL(MaxBuffers, input.size()); while (input.size() != 0) { CHECK(client->tick()); } client->flush(); CHECK(network.size() >= MaxBuffers * BufSamples / PktSamples); SampleStream so; for (size_t n = 0; n < MaxBuffers; n++) { CHECK(server->tick(PacketsPerTick, 1, BufSamples)); LONGS_EQUAL(1, output.size()); so.read(output, BufSamples); LONGS_EQUAL(0, output.size()); } LONGS_EQUAL(0, network.size()); } }; TEST(client_server, bare) { init_client(0); init_server(0); flow_client_server(); } TEST(client_server, interleaving) { init_client(EnableInterleaving); init_server(0); flow_client_server(); } TEST(client_server, ldpc_only_client) { init_client(EnableLDPC); init_server(0); flow_client_server(); } TEST(client_server, ldpc_only_server) { init_client(0); init_server(EnableLDPC); flow_client_server(); } TEST(client_server, ldpc) { init_client(EnableLDPC); init_server(EnableLDPC); flow_client_server(); } TEST(client_server, ldpc_interleaving) { init_client(EnableLDPC | EnableInterleaving); init_server(EnableLDPC); flow_client_server(); } TEST(client_server, ldpc_random_loss) { init_client(EnableLDPC, RandomLoss); init_server(EnableLDPC); flow_client_server(); } TEST(client_server, ldpc_interleaving_random_loss) { init_client(EnableLDPC | EnableInterleaving, RandomLoss); init_server(EnableLDPC); flow_client_server(); } } // namespace test } // namespace roc <commit_msg>Disable ldpc tests when built w/o openfec<commit_after>/* * Copyright (c) 2015 Victor Gaydov * * 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 <CppUTest/TestHarness.h> #include "roc_config/config.h" #include "roc_core/scoped_ptr.h" #include "roc_rtp/composer.h" #include "roc_rtp/parser.h" #include "roc_datagram/datagram_queue.h" #include "roc_pipeline/client.h" #include "roc_pipeline/server.h" #include "test_sample_stream.h" #include "test_sample_queue.h" #include "test_datagram.h" namespace roc { namespace test { using namespace pipeline; TEST_GROUP(client_server) { enum { // Sending port. ClientPort = 501, // Receiving port. ServerPort = 502, // Number of samples in every channel per packet. PktSamples = ROC_CONFIG_DEFAULT_PACKET_SAMPLES, // Number of samples in input/output buffers. BufSamples = SampleStream::ReadBufsz, // Number of packets to read per tick. PacketsPerTick = 20, // Maximum number of sample buffers. MaxBuffers = PktSamples * 100 / BufSamples, // Percentage of packets to be lost. RandomLoss = 1 }; SampleQueue<MaxBuffers> input; SampleQueue<MaxBuffers> output; datagram::DatagramQueue network; TestDatagramComposer datagram_composer; rtp::Composer packet_composer; rtp::Parser packet_parser; core::ScopedPtr<Client> client; core::ScopedPtr<Server> server; void setup() { } void teardown() { LONGS_EQUAL(0, input.size()); LONGS_EQUAL(0, output.size()); LONGS_EQUAL(0, network.size()); } void init_client(int options, size_t random_loss = 0) { ClientConfig config; config.options = options; config.channels = ChannelMask; config.samples_per_packet = PktSamples; config.random_loss_rate = random_loss; client.reset( new Client(input, network, datagram_composer, packet_composer, config)); client->set_sender(new_address(ClientPort)); client->set_receiver(new_address(ServerPort)); } void init_server(int options) { ServerConfig config; config.options = options; config.channels = ChannelMask; config.latency = BufSamples; config.timeout = MaxBuffers; server.reset(new Server(network, output, config)); server->add_port(new_address(ServerPort), packet_parser); } void flow_client_server() { SampleStream si; for (size_t n = 0; n < MaxBuffers; n++) { si.write(input, BufSamples); } LONGS_EQUAL(MaxBuffers, input.size()); while (input.size() != 0) { CHECK(client->tick()); } client->flush(); CHECK(network.size() >= MaxBuffers * BufSamples / PktSamples); SampleStream so; for (size_t n = 0; n < MaxBuffers; n++) { CHECK(server->tick(PacketsPerTick, 1, BufSamples)); LONGS_EQUAL(1, output.size()); so.read(output, BufSamples); LONGS_EQUAL(0, output.size()); } LONGS_EQUAL(0, network.size()); } }; TEST(client_server, bare) { init_client(0); init_server(0); flow_client_server(); } TEST(client_server, interleaving) { init_client(EnableInterleaving); init_server(0); flow_client_server(); } #ifdef ROC_TARGET_OPENFEC TEST(client_server, ldpc_only_client) { init_client(EnableLDPC); init_server(0); flow_client_server(); } TEST(client_server, ldpc_only_server) { init_client(0); init_server(EnableLDPC); flow_client_server(); } TEST(client_server, ldpc) { init_client(EnableLDPC); init_server(EnableLDPC); flow_client_server(); } TEST(client_server, ldpc_interleaving) { init_client(EnableLDPC | EnableInterleaving); init_server(EnableLDPC); flow_client_server(); } TEST(client_server, ldpc_random_loss) { init_client(EnableLDPC, RandomLoss); init_server(EnableLDPC); flow_client_server(); } TEST(client_server, ldpc_interleaving_random_loss) { init_client(EnableLDPC | EnableInterleaving, RandomLoss); init_server(EnableLDPC); flow_client_server(); } #endif // ROC_TARGET_OPENFEC } // namespace test } // namespace roc <|endoftext|>
<commit_before> // // Copyright (c) 2012 Jonathan Topf // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if defined __APPLE__ #include <maya/OpenMayaMac.h> #endif #include <maya/MIOStream.h> #include <maya/MSimple.h> #include <maya/MGlobal.h> #include <maya/MSelectionList.h> #include <maya/MDagPath.h> #include <maya/MSelectionList.h> #include <maya/MFnMesh.h> #include <maya/MItMeshPolygon.h> #include <maya/MPointArray.h> #include <maya/MFloatArray.h> #include <maya/MFloatVectorArray.h> #include <maya/MArgList.h> #include <maya/MString.h> #include <fstream> const MString Version("0.1.1"); DeclareSimpleCommand(ms_export_obj, "mayaseed", Version.asChar()); MStatus ms_export_obj::doIt(const MArgList& args) { // Get the args. MString mesh_name; MString file_path; for (unsigned int i = 0; i < args.length(); i++) { MGlobal::displayInfo(args.asString(i)); if (args.asString(i) == "-mesh") { mesh_name = args.asString(i+1); } else if (args.asString(i) == "-filePath") { file_path = args.asString(i+1); } } MString display_info; display_info.format("Exporting ^1s using ms_export_obj", mesh_name); MGlobal::displayInfo(display_info); MSelectionList sel; sel.add(mesh_name); MDagPath mesh_dag_path; sel.getDagPath(0, mesh_dag_path); MFnMesh mesh(mesh_dag_path); MItMeshPolygon iter_polys(mesh.object()); // Open file for writing, overwriting previous contents. std::ofstream out_file; out_file.open(file_path.asChar(), ios::trunc); out_file << "# File generated by ms_export_obj version " << Version.asChar() << "\n\n"; // Write vertices. MPointArray point_array; mesh.getPoints(point_array); for (unsigned int i = 0; i < point_array.length(); i++) { const MPoint& p = point_array[i]; out_file << "v " << p.x << " " << p.y << " " << p.z << "\n"; } // Write UVs. MFloatArray u_array; MFloatArray v_array; mesh.getUVs(u_array, v_array); for (unsigned int i = 0; i < u_array.length(); i++) { out_file << "vt " << u_array[i] << " " << v_array[i] << "\n"; } // Write normals. MFloatVectorArray normal_array; mesh.getNormals(normal_array, MSpace::kTransform); for (unsigned int i = 0; i < normal_array.length(); i++) { const MFloatVector& n = normal_array[i]; out_file << "vn " << n.x << " " << n.y << " " << n.z << "\n"; } // Write polys. while (!iter_polys.isDone()) { out_file << "f "; unsigned int vert_count = iter_polys.polygonVertexCount(); for (unsigned int i = 0; i < vert_count; i++) { int uv_index; iter_polys.getUVIndex(i, uv_index); out_file << (iter_polys.vertexIndex(i) + 1) << "/" << (uv_index + 1) << "/" << (iter_polys.normalIndex(i) + 1) << " "; } out_file << "\n"; iter_polys.next(); } out_file.close(); return MS::kSuccess; } <commit_msg>removed debug output.<commit_after> // // Copyright (c) 2012 Jonathan Topf // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if defined __APPLE__ #include <maya/OpenMayaMac.h> #endif #include <maya/MIOStream.h> #include <maya/MSimple.h> #include <maya/MGlobal.h> #include <maya/MSelectionList.h> #include <maya/MDagPath.h> #include <maya/MSelectionList.h> #include <maya/MFnMesh.h> #include <maya/MItMeshPolygon.h> #include <maya/MPointArray.h> #include <maya/MFloatArray.h> #include <maya/MFloatVectorArray.h> #include <maya/MArgList.h> #include <maya/MString.h> #include <fstream> const MString Version("0.1.1"); DeclareSimpleCommand(ms_export_obj, "mayaseed", Version.asChar()); MStatus ms_export_obj::doIt(const MArgList& args) { // Get the args. MString mesh_name; MString file_path; for (unsigned int i = 0; i < args.length(); i++) { if (args.asString(i) == "-mesh") mesh_name = args.asString(i+1); else if (args.asString(i) == "-filePath") file_path = args.asString(i+1); } MString display_info; display_info.format("Exporting ^1s using ms_export_obj", mesh_name); MGlobal::displayInfo(display_info); MSelectionList sel; sel.add(mesh_name); MDagPath mesh_dag_path; sel.getDagPath(0, mesh_dag_path); MFnMesh mesh(mesh_dag_path); MItMeshPolygon iter_polys(mesh.object()); // Open file for writing, overwriting previous contents. std::ofstream out_file; out_file.open(file_path.asChar(), ios::trunc); out_file << "# File generated by ms_export_obj version " << Version.asChar() << "\n\n"; // Write vertices. MPointArray point_array; mesh.getPoints(point_array); for (unsigned int i = 0; i < point_array.length(); i++) { const MPoint& p = point_array[i]; out_file << "v " << p.x << " " << p.y << " " << p.z << "\n"; } // Write UVs. MFloatArray u_array; MFloatArray v_array; mesh.getUVs(u_array, v_array); for (unsigned int i = 0; i < u_array.length(); i++) { out_file << "vt " << u_array[i] << " " << v_array[i] << "\n"; } // Write normals. MFloatVectorArray normal_array; mesh.getNormals(normal_array, MSpace::kTransform); for (unsigned int i = 0; i < normal_array.length(); i++) { const MFloatVector& n = normal_array[i]; out_file << "vn " << n.x << " " << n.y << " " << n.z << "\n"; } // Write polys. while (!iter_polys.isDone()) { out_file << "f "; unsigned int vert_count = iter_polys.polygonVertexCount(); for (unsigned int i = 0; i < vert_count; i++) { int uv_index; iter_polys.getUVIndex(i, uv_index); out_file << (iter_polys.vertexIndex(i) + 1) << "/" << (uv_index + 1) << "/" << (iter_polys.normalIndex(i) + 1) << " "; } out_file << "\n"; iter_polys.next(); } out_file.close(); return MS::kSuccess; } <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit 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 <QApplication> #include "CodeExamples.h" #include "CodeViewer/Dialog.h" #include "SyntaxHighlighter/Cpp.h" class DummyCodeReport : public CodeReport { public: explicit DummyCodeReport(uint32_t num_samples) : num_samples_{num_samples} {} [[nodiscard]] uint32_t GetNumSamplesInFunction() const override { return num_samples_; } [[nodiscard]] uint32_t GetNumSamples() const override { return num_samples_; } [[nodiscard]] std::optional<uint32_t> GetNumSamplesAtLine(size_t line) const override { return line; } private: uint32_t num_samples_ = 0; }; int main(int argc, char* argv[]) { QApplication app{argc, argv}; orbit_code_viewer::Dialog dialog{}; // Example file const QString content = testing_example; dialog.SetMainContent(content, std::make_unique<orbit_syntax_highlighter::Cpp>()); const auto line_numbers = content.count('\n'); const DummyCodeReport code_report{static_cast<uint32_t>(line_numbers)}; dialog.SetHeatmap(orbit_code_viewer::FontSizeInEm{1.2f}, &code_report); dialog.SetLineNumberTypes(orbit_code_viewer::Dialog::LineNumberTypes::kOnlyMainContent); dialog.SetEnableSampleCounters(true); dialog.GoToLineNumber(10); dialog.SetHighlightCurrentLine(true); return dialog.exec(); }<commit_msg>Integrate annotation into CodeViewerDemo<commit_after>// Copyright (c) 2020 The Orbit 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 <QApplication> #include "CodeExamples.h" #include "CodeViewer/Dialog.h" #include "SyntaxHighlighter/X86Assembly.h" class DummyCodeReport : public CodeReport { public: explicit DummyCodeReport(uint32_t num_samples) : num_samples_{num_samples} {} [[nodiscard]] uint32_t GetNumSamplesInFunction() const override { return num_samples_; } [[nodiscard]] uint32_t GetNumSamples() const override { return num_samples_; } [[nodiscard]] std::optional<uint32_t> GetNumSamplesAtLine(size_t line) const override { return line; } private: uint32_t num_samples_ = 0; }; int main(int argc, char* argv[]) { QApplication app{argc, argv}; orbit_code_viewer::Dialog dialog{}; // Example file const QString content = x86Assembly_example; dialog.SetMainContent(content, std::make_unique<orbit_syntax_highlighter::X86Assembly>()); std::vector<orbit_code_viewer::AnnotatingLine> lines{}; lines.emplace_back(); lines.back().reference_line = 9; lines.back().line_number = 42; lines.back().line_contents = "void main() {"; lines.emplace_back(); lines.back().reference_line = 14; lines.back().line_number = 43; lines.back().line_contents = "echo \"Hello World!\";"; dialog.SetAnnotatingContent(lines); const auto line_numbers = content.count('\n'); const DummyCodeReport code_report{static_cast<uint32_t>(line_numbers)}; dialog.SetHeatmap(orbit_code_viewer::FontSizeInEm{1.2f}, &code_report); dialog.SetLineNumberTypes(orbit_code_viewer::Dialog::LineNumberTypes::kOnlyAnnotatingLines); dialog.SetEnableSampleCounters(true); dialog.GoToLineNumber(10); dialog.SetHighlightCurrentLine(true); return dialog.exec(); }<|endoftext|>
<commit_before>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh 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 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ //============================================================================= // // Implements the OpenMesh IOManager singleton // //============================================================================= //== INCLUDES ================================================================= #include <OpenMesh/Core/System/config.h> #include <OpenMesh/Core/IO/IOManager.hh> //== NAMESPACES =============================================================== namespace OpenMesh { namespace IO { //============================================================================= _IOManager_ *__IOManager_instance = 0; _IOManager_& IOManager() { if (!__IOManager_instance) __IOManager_instance = new _IOManager_(); return *__IOManager_instance; } //----------------------------------------------------------------------------- bool _IOManager_:: read(const std::string& _filename, BaseImporter& _bi, Options& _opt) { std::set<BaseReader*>::const_iterator it = reader_modules_.begin(); std::set<BaseReader*>::const_iterator it_end = reader_modules_.end(); // Try all registered modules for(; it != it_end; ++it) if ((*it)->can_u_read(_filename)) { _bi.prepare(); bool ok = (*it)->read(_filename, _bi, _opt); _bi.finish(); return ok; } // All modules failed to read return false; } //----------------------------------------------------------------------------- bool _IOManager_:: read(std::istream& _is, const std::string& _ext, BaseImporter& _bi, Options& _opt) { std::set<BaseReader*>::const_iterator it = reader_modules_.begin(); std::set<BaseReader*>::const_iterator it_end = reader_modules_.end(); // Try all registered modules for(; it != it_end; ++it) if ((*it)->BaseReader::can_u_read(_ext)) //Use the extension check only (no file existence) { _bi.prepare(); bool ok = (*it)->read(_is, _bi, _opt); _bi.finish(); return ok; } // All modules failed to read return false; } //----------------------------------------------------------------------------- bool _IOManager_:: write(const std::string& _filename, BaseExporter& _be, Options _opt) { std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(); std::set<BaseWriter*>::const_iterator it_end = writer_modules_.end(); if ( it == it_end ) { omerr() << "[OpenMesh::IO::_IOManager_] No writing modules available!\n"; return false; } // Try all registered modules for(; it != it_end; ++it) { if ((*it)->can_u_write(_filename)) { return (*it)->write(_filename, _be, _opt); } } // All modules failed to save return false; } //----------------------------------------------------------------------------- bool _IOManager_:: write(std::ostream& _os,const std::string &_ext, BaseExporter& _be, Options _opt) { std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(); std::set<BaseWriter*>::const_iterator it_end = writer_modules_.end(); if ( it == it_end ) { omerr() << "[OpenMesh::IO::_IOManager_] No writing modules available!\n"; return false; } // Try all registered modules for(; it != it_end; ++it) { if ((*it)->BaseWriter::can_u_write(_ext)) //Restrict test to the extension check { return (*it)->write(_os, _be, _opt); } } // All modules failed to save return false; } //----------------------------------------------------------------------------- bool _IOManager_:: can_read( const std::string& _format ) const { std::set<BaseReader*>::const_iterator it = reader_modules_.begin(); std::set<BaseReader*>::const_iterator it_end = reader_modules_.end(); std::string filename = "dummy." + _format; for(; it != it_end; ++it) if ((*it)->can_u_read(filename)) return true; return false; } //----------------------------------------------------------------------------- bool _IOManager_:: can_write( const std::string& _format ) const { std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(); std::set<BaseWriter*>::const_iterator it_end = writer_modules_.end(); std::string filename = "dummy." + _format; // Try all registered modules for(; it != it_end; ++it) if ((*it)->can_u_write(filename)) return true; return false; } //----------------------------------------------------------------------------- const BaseWriter* _IOManager_:: find_writer(const std::string& _format) { using std::string; string::size_type dot = _format.rfind('.'); string ext; if (dot == string::npos) ext = _format; else ext = _format.substr(dot+1,_format.length()-(dot+1)); std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(); std::set<BaseWriter*>::const_iterator it_end = writer_modules_.end(); std::string filename = "dummy." + ext; // Try all registered modules for(; it != it_end; ++it) if ((*it)->can_u_write(filename)) return *it; return NULL; } //----------------------------------------------------------------------------- void _IOManager_:: update_read_filters() { std::set<BaseReader*>::const_iterator it = reader_modules_.begin(), it_end = reader_modules_.end(); std::string s, all, filters; for(; it != it_end; ++it) { filters += (*it)->get_description() + " ("; std::istringstream iss((*it)->get_extensions()); while (iss && !iss.eof() && (iss >> s)) { s = " *." + s; filters += s; all += s; } filters += " );;"; } all = "All files ( " + all + " );;"; read_filters_ = all + filters; } //----------------------------------------------------------------------------- void _IOManager_:: update_write_filters() { std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(), it_end = writer_modules_.end(); std::string s, all, filters; for(; it != it_end; ++it) { filters += (*it)->get_description() + " ("; std::istringstream iss((*it)->get_extensions()); while (iss && !iss.eof() && (iss >> s)) { s = " *." + s; filters += s; all += s; } filters += " );;"; } all = "All files ( " + all + " );;"; write_filters_ = all + filters; } //============================================================================= } // namespace IO } // namespace OpenMesh //============================================================================= <commit_msg>Fixed debug build crash on mac, reading from stringstream into emtpy string crashed when compiling with clang<commit_after>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh 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 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ //============================================================================= // // Implements the OpenMesh IOManager singleton // //============================================================================= //== INCLUDES ================================================================= #include <OpenMesh/Core/System/config.h> #include <OpenMesh/Core/IO/IOManager.hh> //== NAMESPACES =============================================================== namespace OpenMesh { namespace IO { //============================================================================= _IOManager_ *__IOManager_instance = 0; _IOManager_& IOManager() { if (!__IOManager_instance) __IOManager_instance = new _IOManager_(); return *__IOManager_instance; } //----------------------------------------------------------------------------- bool _IOManager_:: read(const std::string& _filename, BaseImporter& _bi, Options& _opt) { std::set<BaseReader*>::const_iterator it = reader_modules_.begin(); std::set<BaseReader*>::const_iterator it_end = reader_modules_.end(); // Try all registered modules for(; it != it_end; ++it) if ((*it)->can_u_read(_filename)) { _bi.prepare(); bool ok = (*it)->read(_filename, _bi, _opt); _bi.finish(); return ok; } // All modules failed to read return false; } //----------------------------------------------------------------------------- bool _IOManager_:: read(std::istream& _is, const std::string& _ext, BaseImporter& _bi, Options& _opt) { std::set<BaseReader*>::const_iterator it = reader_modules_.begin(); std::set<BaseReader*>::const_iterator it_end = reader_modules_.end(); // Try all registered modules for(; it != it_end; ++it) if ((*it)->BaseReader::can_u_read(_ext)) //Use the extension check only (no file existence) { _bi.prepare(); bool ok = (*it)->read(_is, _bi, _opt); _bi.finish(); return ok; } // All modules failed to read return false; } //----------------------------------------------------------------------------- bool _IOManager_:: write(const std::string& _filename, BaseExporter& _be, Options _opt) { std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(); std::set<BaseWriter*>::const_iterator it_end = writer_modules_.end(); if ( it == it_end ) { omerr() << "[OpenMesh::IO::_IOManager_] No writing modules available!\n"; return false; } // Try all registered modules for(; it != it_end; ++it) { if ((*it)->can_u_write(_filename)) { return (*it)->write(_filename, _be, _opt); } } // All modules failed to save return false; } //----------------------------------------------------------------------------- bool _IOManager_:: write(std::ostream& _os,const std::string &_ext, BaseExporter& _be, Options _opt) { std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(); std::set<BaseWriter*>::const_iterator it_end = writer_modules_.end(); if ( it == it_end ) { omerr() << "[OpenMesh::IO::_IOManager_] No writing modules available!\n"; return false; } // Try all registered modules for(; it != it_end; ++it) { if ((*it)->BaseWriter::can_u_write(_ext)) //Restrict test to the extension check { return (*it)->write(_os, _be, _opt); } } // All modules failed to save return false; } //----------------------------------------------------------------------------- bool _IOManager_:: can_read( const std::string& _format ) const { std::set<BaseReader*>::const_iterator it = reader_modules_.begin(); std::set<BaseReader*>::const_iterator it_end = reader_modules_.end(); std::string filename = "dummy." + _format; for(; it != it_end; ++it) if ((*it)->can_u_read(filename)) return true; return false; } //----------------------------------------------------------------------------- bool _IOManager_:: can_write( const std::string& _format ) const { std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(); std::set<BaseWriter*>::const_iterator it_end = writer_modules_.end(); std::string filename = "dummy." + _format; // Try all registered modules for(; it != it_end; ++it) if ((*it)->can_u_write(filename)) return true; return false; } //----------------------------------------------------------------------------- const BaseWriter* _IOManager_:: find_writer(const std::string& _format) { using std::string; string::size_type dot = _format.rfind('.'); string ext; if (dot == string::npos) ext = _format; else ext = _format.substr(dot+1,_format.length()-(dot+1)); std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(); std::set<BaseWriter*>::const_iterator it_end = writer_modules_.end(); std::string filename = "dummy." + ext; // Try all registered modules for(; it != it_end; ++it) if ((*it)->can_u_write(filename)) return *it; return NULL; } //----------------------------------------------------------------------------- void _IOManager_:: update_read_filters() { std::set<BaseReader*>::const_iterator it = reader_modules_.begin(), it_end = reader_modules_.end(); std::string all = ""; std::string filters = ""; for(; it != it_end; ++it) { // Initialized with space, as a workaround for debug build with clang on mac // which crashes if tmp is initialized with an empty string ?! std::string tmp = " "; filters += (*it)->get_description() + " ("; std::istringstream iss((*it)->get_extensions()); while (iss && !iss.eof() && (iss >> tmp) ) { tmp = " *." + tmp; filters += tmp; all += tmp; } filters += " );;"; } all = "All files ( " + all + " );;"; read_filters_ = all + filters; } //----------------------------------------------------------------------------- void _IOManager_:: update_write_filters() { std::set<BaseWriter*>::const_iterator it = writer_modules_.begin(), it_end = writer_modules_.end(); std::string all; std::string filters; for(; it != it_end; ++it) { // Initialized with space, as a workaround for debug build with clang on mac // which crashes if tmp is initialized with an empty string ?! std::string s = " "; filters += (*it)->get_description() + " ("; std::istringstream iss((*it)->get_extensions()); while (iss && !iss.eof() && (iss >> s)) { s = " *." + s; filters += s; all += s; } filters += " );;"; } all = "All files ( " + all + " );;"; write_filters_ = all + filters; } //============================================================================= } // namespace IO } // namespace OpenMesh //============================================================================= <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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 "sink_rubber.hxx" #include "istream/Sink.hxx" #include "istream/UnusedPtr.hxx" #include "rubber.hxx" #include "pool/pool.hxx" #include "util/Cancellable.hxx" #include <assert.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> class RubberSink final : IstreamSink, Cancellable { Rubber &rubber; unsigned rubber_id; const size_t max_size; size_t position = 0; RubberSinkHandler &handler; public: template<typename I> RubberSink(Rubber &_rubber, unsigned _rubber_id, size_t _max_size, RubberSinkHandler &_handler, I &&_input, CancellablePointer &cancel_ptr) :IstreamSink(std::forward<I>(_input), FD_ANY), rubber(_rubber), rubber_id(_rubber_id), max_size(_max_size), handler(_handler) { cancel_ptr = *this; } void Read() noexcept { input.Read(); } private: void FailTooLarge(); void InvokeEof(); /* virtual methods from class Cancellable */ void Cancel() noexcept override; /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) override; ssize_t OnDirect(FdType type, int fd, size_t max_length) override; void OnEof() noexcept override; void OnError(std::exception_ptr ep) noexcept override; }; static ssize_t fd_read(FdType type, int fd, void *p, size_t size) { return IsAnySocket(type) ? recv(fd, p, size, MSG_DONTWAIT) : read(fd, p, size); } void RubberSink::FailTooLarge() { rubber.Remove(rubber_id); if (input.IsDefined()) input.ClearAndClose(); handler.RubberTooLarge(); } void RubberSink::InvokeEof() { if (input.IsDefined()) input.ClearAndClose(); if (position == 0) { /* the stream was empty; remove the object from the rubber allocator */ rubber.Remove(rubber_id); rubber_id = 0; } else rubber.Shrink(rubber_id, position); handler.RubberDone(RubberAllocation(rubber, rubber_id), position); } /* * istream handler * */ inline size_t RubberSink::OnData(const void *data, size_t length) { assert(position <= max_size); if (position + length > max_size) { /* too large, abort and invoke handler */ FailTooLarge(); return 0; } uint8_t *p = (uint8_t *)rubber.Write(rubber_id); memcpy(p + position, data, length); position += length; return length; } inline ssize_t RubberSink::OnDirect(FdType type, int fd, size_t max_length) { assert(position <= max_size); size_t length = max_size - position; if (length == 0) { /* already full, see what the file descriptor says */ uint8_t dummy; ssize_t nbytes = fd_read(type, fd, &dummy, sizeof(dummy)); if (nbytes > 0) { FailTooLarge(); return ISTREAM_RESULT_CLOSED; } if (nbytes == 0) { InvokeEof(); return ISTREAM_RESULT_CLOSED; } return ISTREAM_RESULT_ERRNO; } if (length > max_length) length = max_length; uint8_t *p = (uint8_t *)rubber.Write(rubber_id); p += position; ssize_t nbytes = fd_read(type, fd, p, length); if (nbytes > 0) position += (size_t)nbytes; return nbytes; } void RubberSink::OnEof() noexcept { assert(input.IsDefined()); input.Clear(); InvokeEof(); } void RubberSink::OnError(std::exception_ptr ep) noexcept { assert(input.IsDefined()); input.Clear(); rubber.Remove(rubber_id); handler.RubberError(ep); } /* * async operation * */ void RubberSink::Cancel() noexcept { rubber.Remove(rubber_id); if (input.IsDefined()) input.ClearAndClose(); } /* * constructor * */ RubberSink * sink_rubber_new(struct pool &pool, UnusedIstreamPtr input, Rubber &rubber, size_t max_size, RubberSinkHandler &handler, CancellablePointer &cancel_ptr) { const off_t available = input.GetAvailable(true); if (available > (off_t)max_size) { input.Clear(); handler.RubberTooLarge(); return nullptr; } const off_t size = input.GetAvailable(false); assert(size == -1 || size >= available); assert(size <= (off_t)max_size); if (size == 0) { input.Clear(); handler.RubberDone({}, 0); return nullptr; } const size_t allocate = size == -1 ? max_size : (size_t)size; unsigned rubber_id = rubber.Add(allocate); if (rubber_id == 0) { input.Clear(); handler.RubberOutOfMemory(); return nullptr; } return NewFromPool<RubberSink>(pool, rubber, rubber_id, allocate, handler, std::move(input), cancel_ptr); } void sink_rubber_read(RubberSink &sink) noexcept { sink.Read(); } <commit_msg>sink_rubber: call destructor<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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 "sink_rubber.hxx" #include "istream/Sink.hxx" #include "istream/UnusedPtr.hxx" #include "rubber.hxx" #include "pool/pool.hxx" #include "util/Cancellable.hxx" #include "util/LeakDetector.hxx" #include <assert.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> class RubberSink final : IstreamSink, Cancellable, LeakDetector { Rubber &rubber; unsigned rubber_id; const size_t max_size; size_t position = 0; RubberSinkHandler &handler; public: template<typename I> RubberSink(Rubber &_rubber, unsigned _rubber_id, size_t _max_size, RubberSinkHandler &_handler, I &&_input, CancellablePointer &cancel_ptr) :IstreamSink(std::forward<I>(_input), FD_ANY), rubber(_rubber), rubber_id(_rubber_id), max_size(_max_size), handler(_handler) { cancel_ptr = *this; } void Read() noexcept { input.Read(); } private: void Destroy() { this->~RubberSink(); } void FailTooLarge(); void InvokeEof(); /* virtual methods from class Cancellable */ void Cancel() noexcept override; /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) override; ssize_t OnDirect(FdType type, int fd, size_t max_length) override; void OnEof() noexcept override; void OnError(std::exception_ptr ep) noexcept override; }; static ssize_t fd_read(FdType type, int fd, void *p, size_t size) { return IsAnySocket(type) ? recv(fd, p, size, MSG_DONTWAIT) : read(fd, p, size); } void RubberSink::FailTooLarge() { rubber.Remove(rubber_id); if (input.IsDefined()) input.ClearAndClose(); handler.RubberTooLarge(); } void RubberSink::InvokeEof() { if (input.IsDefined()) input.ClearAndClose(); if (position == 0) { /* the stream was empty; remove the object from the rubber allocator */ rubber.Remove(rubber_id); rubber_id = 0; } else rubber.Shrink(rubber_id, position); handler.RubberDone(RubberAllocation(rubber, rubber_id), position); } /* * istream handler * */ inline size_t RubberSink::OnData(const void *data, size_t length) { assert(position <= max_size); if (position + length > max_size) { /* too large, abort and invoke handler */ FailTooLarge(); Destroy(); return 0; } uint8_t *p = (uint8_t *)rubber.Write(rubber_id); memcpy(p + position, data, length); position += length; return length; } inline ssize_t RubberSink::OnDirect(FdType type, int fd, size_t max_length) { assert(position <= max_size); size_t length = max_size - position; if (length == 0) { /* already full, see what the file descriptor says */ uint8_t dummy; ssize_t nbytes = fd_read(type, fd, &dummy, sizeof(dummy)); if (nbytes > 0) { FailTooLarge(); Destroy(); return ISTREAM_RESULT_CLOSED; } if (nbytes == 0) { InvokeEof(); Destroy(); return ISTREAM_RESULT_CLOSED; } return ISTREAM_RESULT_ERRNO; } if (length > max_length) length = max_length; uint8_t *p = (uint8_t *)rubber.Write(rubber_id); p += position; ssize_t nbytes = fd_read(type, fd, p, length); if (nbytes > 0) position += (size_t)nbytes; return nbytes; } void RubberSink::OnEof() noexcept { assert(input.IsDefined()); input.Clear(); InvokeEof(); Destroy(); } void RubberSink::OnError(std::exception_ptr ep) noexcept { assert(input.IsDefined()); input.Clear(); rubber.Remove(rubber_id); handler.RubberError(ep); Destroy(); } /* * async operation * */ void RubberSink::Cancel() noexcept { rubber.Remove(rubber_id); if (input.IsDefined()) input.ClearAndClose(); Destroy(); } /* * constructor * */ RubberSink * sink_rubber_new(struct pool &pool, UnusedIstreamPtr input, Rubber &rubber, size_t max_size, RubberSinkHandler &handler, CancellablePointer &cancel_ptr) { const off_t available = input.GetAvailable(true); if (available > (off_t)max_size) { input.Clear(); handler.RubberTooLarge(); return nullptr; } const off_t size = input.GetAvailable(false); assert(size == -1 || size >= available); assert(size <= (off_t)max_size); if (size == 0) { input.Clear(); handler.RubberDone({}, 0); return nullptr; } const size_t allocate = size == -1 ? max_size : (size_t)size; unsigned rubber_id = rubber.Add(allocate); if (rubber_id == 0) { input.Clear(); handler.RubberOutOfMemory(); return nullptr; } return NewFromPool<RubberSink>(pool, rubber, rubber_id, allocate, handler, std::move(input), cancel_ptr); } void sink_rubber_read(RubberSink &sink) noexcept { sink.Read(); } <|endoftext|>
<commit_before>/* http_header.cc Mathieu Stefani, 19 August 2015 Implementation of common HTTP headers described by the RFC */ #include "http_header.h" #include "common.h" #include "http.h" #include <stdexcept> #include <iterator> #include <cstring> #include <iostream> using namespace std; namespace Net { namespace Http { namespace Mime { std::string Q::toString() const { if (val_ == 0) return "q=0"; else if (val_ == 100) return "q=1"; char buff[sizeof("q=0.99")]; memset(buff, sizeof buff, 0); if (val_ % 10 == 0) snprintf(buff, sizeof buff, "q=%.1f", val_ / 100.0); else snprintf(buff, sizeof buff, "q=%.2f", val_ / 100.0); return std::string(buff); } MediaType MediaType::fromString(const std::string& str) { return fromRaw(str.c_str(), str.size()); } MediaType MediaType::fromString(std::string&& str) { return fromRaw(str.c_str(), str.size()); } MediaType MediaType::fromRaw(const char* str, size_t len) { MediaType res; res.parseRaw(str, len); return res; } void MediaType::parseRaw(const char* str, size_t len) { auto eof = [&](const char *p) { return p - str == len; }; auto offset = [&](const char* ptr) { return static_cast<size_t>(ptr - str); }; auto raise = [&](const char* str) { throw HttpError(Http::Code::Unsupported_Media_Type, str); }; #define MAX_SIZE(s) std::min(sizeof(s) - 1, offset(p)) // Parse type const char *p = strchr(str, '/'); if (p == NULL) { raise("Malformated Media Type"); } raw_ = string(str, len); Mime::Type top; // The reason we are using a do { } while (0); syntax construct here is to emulate // if / else-if. Since we are using items-list macros to compare the strings, // we want to avoid evaluating all the branches when one of them evaluates to true. // // Instead, we break the loop when a branch evaluates to true so that we do // not evaluate all the subsequent ones. // // Watch out, this pattern is repeated throughout the function do { #define TYPE(val, s) \ if (memcmp(str, s, MAX_SIZE(s)) == 0) { \ top = Type::val; \ break; \ } MIME_TYPES #undef TYPE throw HttpError(Http::Code::Unsupported_Media_Type, "Unknown Media Type"); } while (0); top_ = top; // Parse subtype Mime::Subtype sub; ++p; if (eof(p)) raise("Malformed Media Type"); if (memcmp(p, "vnd.", 4) == 0) { sub = Subtype::Vendor; } else { do { #define SUB_TYPE(val, s) \ if (memcmp(p, s, MAX_SIZE(s)) == 0) { \ sub = Subtype::val; \ p += sizeof(s) - 1; \ break; \ } MIME_SUBTYPES #undef SUB_TYPE sub = Subtype::Ext; } while (0); } if (sub == Subtype::Ext || sub == Subtype::Vendor) { rawSubIndex.beg = offset(p); while (!eof(p) && (*p != ';' && *p != '+')) ++p; rawSubIndex.end = offset(p) - 1; } sub_ = sub; if (eof(p)) return; // Parse suffix Mime::Suffix suffix = Suffix::None; if (*p == '+') { ++p; if (eof(p)) raise("Malformed Media Type"); do { #define SUFFIX(val, s, _) \ if (memcmp(p, s, MAX_SIZE(s)) == 0) { \ suffix = Suffix::val; \ p += sizeof(s) - 1; \ break; \ } MIME_SUFFIXES #undef SUFFIX suffix = Suffix::Ext; } while (0); if (suffix == Suffix::Ext) { rawSuffixIndex.beg = offset(p); while (!eof(p) && (*p != ';' && *p != '+')) ++p; rawSuffixIndex.end = offset(p) - 1; } suffix_ = suffix; } if (eof(p)) return; if (*p == ';') ++p; if (eof(p)) { raise("Malformed Media Type"); } while (*p == ' ') ++p; if (eof(p)) { raise("Malformed Media Type"); }; Optional<Q> q = None(); if (*p == 'q') { ++p; if (eof(p)) { raise("Invalid quality factor"); } if (*p == '=') { char *end; double val = strtod(p + 1, &end); if (!eof(end) && *end != ';' && *end != ' ') { raise("Invalid quality factor"); } q = Some(Q::fromFloat(val)); } else { raise("Invalid quality factor"); } } q_ = std::move(q); #undef MAX_SIZE } void MediaType::setQuality(Q quality) { q_ = Some(quality); } std::string MediaType::toString() const { if (!raw_.empty()) return raw_; auto topString = [](Mime::Type top) -> const char * { switch (top) { #define TYPE(val, str) \ case Mime::Type::val: \ return str; MIME_TYPES #undef TYPE } }; auto subString = [](Mime::Subtype sub) -> const char * { switch (sub) { #define SUB_TYPE(val, str) \ case Mime::Subtype::val: \ return str; MIME_SUBTYPES #undef TYPE } }; auto suffixString = [](Mime::Suffix suffix) -> const char * { switch (suffix) { #define SUFFIX(val, str, _) \ case Mime::Suffix::val: \ return "+" str; MIME_SUFFIXES #undef SUFFIX } }; std::string res; res += topString(top_); res += "/"; res += subString(sub_); if (suffix_ != Suffix::None) { res += suffixString(suffix_); } optionally_do(q_, [&res](Q quality) { res += "; "; res += quality.toString(); }); return res; } } // namespace Mime const char* encodingString(Encoding encoding) { switch (encoding) { case Encoding::Gzip: return "gzip"; case Encoding::Compress: return "compress"; case Encoding::Deflate: return "deflate"; case Encoding::Identity: return "identity"; case Encoding::Unknown: return "unknown"; } unreachable(); } void Header::parse(const std::string& data) { parseRaw(data.c_str(), data.size()); } void Header::parseRaw(const char *str, size_t len) { parse(std::string(str, len)); } void ContentLength::parse(const std::string& data) { try { size_t pos; uint64_t val = std::stoi(data, &pos); if (pos != 0) { } value_ = val; } catch (const std::invalid_argument& e) { } } void ContentLength::write(std::ostream& os) const { os << "Content-Length: " << value_; } void Host::parse(const std::string& data) { auto pos = data.find(':'); if (pos != std::string::npos) { std::string h = data.substr(0, pos); int16_t p = std::stoi(data.substr(pos + 1)); host_ = h; port_ = p; } else { host_ = data; port_ = -1; } } void Host::write(std::ostream& os) const { os << host_; if (port_ != -1) { os << ":" << port_; } } void UserAgent::parse(const std::string& data) { ua_ = data; } void UserAgent::write(std::ostream& os) const { os << "User-Agent: " << ua_; } void Accept::parseRaw(const char *str, size_t len) { } void Accept::write(std::ostream& os) const { } void ContentEncoding::parseRaw(const char* str, size_t len) { // TODO: case-insensitive // if (!strncmp(str, "gzip", len)) { encoding_ = Encoding::Gzip; } else if (!strncmp(str, "deflate", len)) { encoding_ = Encoding::Deflate; } else if (!strncmp(str, "compress", len)) { encoding_ = Encoding::Compress; } else if (!strncmp(str, "identity", len)) { encoding_ = Encoding::Identity; } else { encoding_ = Encoding::Unknown; } } void ContentEncoding::write(std::ostream& os) const { os << "Content-Encoding: " << encodingString(encoding_); } Server::Server(const std::vector<std::string>& tokens) : tokens_(tokens) { } Server::Server(const std::string& token) { tokens_.push_back(token); } Server::Server(const char* token) { tokens_.emplace_back(token); } void Server::parse(const std::string& data) { } void Server::write(std::ostream& os) const { os << "Server: "; std::copy(std::begin(tokens_), std::end(tokens_), std::ostream_iterator<std::string>(os, " ")); } void ContentType::parseRaw(const char* str, size_t len) { } void ContentType::write(std::ostream& os) const { os << "Content-Type: "; os << mime_.toString(); } } // namespace Http } // namespace Net <commit_msg>Fixed the MAX_SIZE macro that was incorrectly calculating the maximum remaining size<commit_after>/* http_header.cc Mathieu Stefani, 19 August 2015 Implementation of common HTTP headers described by the RFC */ #include "http_header.h" #include "common.h" #include "http.h" #include <stdexcept> #include <iterator> #include <cstring> #include <iostream> using namespace std; namespace Net { namespace Http { namespace Mime { std::string Q::toString() const { if (val_ == 0) return "q=0"; else if (val_ == 100) return "q=1"; char buff[sizeof("q=0.99")]; memset(buff, sizeof buff, 0); if (val_ % 10 == 0) snprintf(buff, sizeof buff, "q=%.1f", val_ / 100.0); else snprintf(buff, sizeof buff, "q=%.2f", val_ / 100.0); return std::string(buff); } MediaType MediaType::fromString(const std::string& str) { return fromRaw(str.c_str(), str.size()); } MediaType MediaType::fromString(std::string&& str) { return fromRaw(str.c_str(), str.size()); } MediaType MediaType::fromRaw(const char* str, size_t len) { MediaType res; res.parseRaw(str, len); return res; } void MediaType::parseRaw(const char* str, size_t len) { auto eof = [&](const char *p) { return p - str == len; }; auto offset = [&](const char* ptr) { return static_cast<size_t>(ptr - str); }; auto raise = [&](const char* str) { // TODO: eventually, we should throw a more generic exception // that could then be catched in lower stack frames to rethrow // an HttpError throw HttpError(Http::Code::Unsupported_Media_Type, str); }; // Macro to ensure that we do not overflow when comparing strings // The trick here is to use sizeof on a raw string literal of type // const char[N] instead of strlen to avoid additional // runtime computation #define MAX_SIZE(s) std::min(sizeof(s) - 1, len - offset(p)) // Parse type const char *p = strchr(str, '/'); if (p == NULL) { raise("Malformated Media Type"); } raw_ = string(str, len); Mime::Type top; // The reason we are using a do { } while (0); syntax construct here is to emulate // if / else-if. Since we are using items-list macros to compare the strings, // we want to avoid evaluating all the branches when one of them evaluates to true. // // Instead, we break the loop when a branch evaluates to true so that we do // not evaluate all the subsequent ones. // // Watch out, this pattern is repeated throughout the function do { #define TYPE(val, s) \ if (memcmp(str, s, MAX_SIZE(s)) == 0) { \ top = Type::val; \ break; \ } MIME_TYPES #undef TYPE raise("Unknown Media Type"); } while (0); top_ = top; // Parse subtype Mime::Subtype sub; ++p; if (eof(p)) raise("Malformed Media Type"); if (memcmp(p, "vnd.", MAX_SIZE("vnd.")) == 0) { sub = Subtype::Vendor; } else { do { #define SUB_TYPE(val, s) \ if (memcmp(p, s, MAX_SIZE(s)) == 0) { \ sub = Subtype::val; \ p += sizeof(s) - 1; \ break; \ } MIME_SUBTYPES #undef SUB_TYPE sub = Subtype::Ext; } while (0); } if (sub == Subtype::Ext || sub == Subtype::Vendor) { rawSubIndex.beg = offset(p); while (!eof(p) && (*p != ';' && *p != '+')) ++p; rawSubIndex.end = offset(p) - 1; } sub_ = sub; if (eof(p)) return; // Parse suffix Mime::Suffix suffix = Suffix::None; if (*p == '+') { ++p; if (eof(p)) raise("Malformed Media Type"); do { #define SUFFIX(val, s, _) \ if (memcmp(p, s, MAX_SIZE(s)) == 0) { \ suffix = Suffix::val; \ p += sizeof(s) - 1; \ break; \ } MIME_SUFFIXES #undef SUFFIX suffix = Suffix::Ext; } while (0); if (suffix == Suffix::Ext) { rawSuffixIndex.beg = offset(p); while (!eof(p) && (*p != ';' && *p != '+')) ++p; rawSuffixIndex.end = offset(p) - 1; } suffix_ = suffix; } if (eof(p)) return; if (*p == ';') ++p; if (eof(p)) { raise("Malformed Media Type"); } while (*p == ' ') ++p; if (eof(p)) { raise("Malformed Media Type"); }; Optional<Q> q = None(); if (*p == 'q') { ++p; if (eof(p)) { raise("Invalid quality factor"); } if (*p == '=') { char *end; double val = strtod(p + 1, &end); if (!eof(end) && *end != ';' && *end != ' ') { raise("Invalid quality factor"); } q = Some(Q::fromFloat(val)); } else { raise("Invalid quality factor"); } } q_ = std::move(q); #undef MAX_SIZE } void MediaType::setQuality(Q quality) { q_ = Some(quality); } std::string MediaType::toString() const { if (!raw_.empty()) return raw_; auto topString = [](Mime::Type top) -> const char * { switch (top) { #define TYPE(val, str) \ case Mime::Type::val: \ return str; MIME_TYPES #undef TYPE } }; auto subString = [](Mime::Subtype sub) -> const char * { switch (sub) { #define SUB_TYPE(val, str) \ case Mime::Subtype::val: \ return str; MIME_SUBTYPES #undef TYPE } }; auto suffixString = [](Mime::Suffix suffix) -> const char * { switch (suffix) { #define SUFFIX(val, str, _) \ case Mime::Suffix::val: \ return "+" str; MIME_SUFFIXES #undef SUFFIX } }; std::string res; res += topString(top_); res += "/"; res += subString(sub_); if (suffix_ != Suffix::None) { res += suffixString(suffix_); } optionally_do(q_, [&res](Q quality) { res += "; "; res += quality.toString(); }); return res; } } // namespace Mime const char* encodingString(Encoding encoding) { switch (encoding) { case Encoding::Gzip: return "gzip"; case Encoding::Compress: return "compress"; case Encoding::Deflate: return "deflate"; case Encoding::Identity: return "identity"; case Encoding::Unknown: return "unknown"; } unreachable(); } void Header::parse(const std::string& data) { parseRaw(data.c_str(), data.size()); } void Header::parseRaw(const char *str, size_t len) { parse(std::string(str, len)); } void ContentLength::parse(const std::string& data) { try { size_t pos; uint64_t val = std::stoi(data, &pos); if (pos != 0) { } value_ = val; } catch (const std::invalid_argument& e) { } } void ContentLength::write(std::ostream& os) const { os << "Content-Length: " << value_; } void Host::parse(const std::string& data) { auto pos = data.find(':'); if (pos != std::string::npos) { std::string h = data.substr(0, pos); int16_t p = std::stoi(data.substr(pos + 1)); host_ = h; port_ = p; } else { host_ = data; port_ = -1; } } void Host::write(std::ostream& os) const { os << host_; if (port_ != -1) { os << ":" << port_; } } void UserAgent::parse(const std::string& data) { ua_ = data; } void UserAgent::write(std::ostream& os) const { os << "User-Agent: " << ua_; } void Accept::parseRaw(const char *str, size_t len) { } void Accept::write(std::ostream& os) const { } void ContentEncoding::parseRaw(const char* str, size_t len) { // TODO: case-insensitive // if (!strncmp(str, "gzip", len)) { encoding_ = Encoding::Gzip; } else if (!strncmp(str, "deflate", len)) { encoding_ = Encoding::Deflate; } else if (!strncmp(str, "compress", len)) { encoding_ = Encoding::Compress; } else if (!strncmp(str, "identity", len)) { encoding_ = Encoding::Identity; } else { encoding_ = Encoding::Unknown; } } void ContentEncoding::write(std::ostream& os) const { os << "Content-Encoding: " << encodingString(encoding_); } Server::Server(const std::vector<std::string>& tokens) : tokens_(tokens) { } Server::Server(const std::string& token) { tokens_.push_back(token); } Server::Server(const char* token) { tokens_.emplace_back(token); } void Server::parse(const std::string& data) { } void Server::write(std::ostream& os) const { os << "Server: "; std::copy(std::begin(tokens_), std::end(tokens_), std::ostream_iterator<std::string>(os, " ")); } void ContentType::parseRaw(const char* str, size_t len) { } void ContentType::write(std::ostream& os) const { os << "Content-Type: "; os << mime_.toString(); } } // namespace Http } // namespace Net <|endoftext|>
<commit_before>// TODO(ralntdir): // Think how to clean SDL if the programs ends with some crash // Finished the program if there is a problem at SDL/IMG init or // when creating the window or the renderer // // Features to add: // ray->sphere intersection (check if it's completed) // shadows // reflection // read llc, hoffset and voffset from file // Files manipulation #include <iostream> #include <fstream> #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> // NOTE(ralntdir): For number types #include <stdint.h> // NOTE(ralntdir): For rand #include <random> // NOTE(ralntdir): For FLT_MAX #include <float.h> typedef int32_t int32; typedef float real32; typedef double real64; // TODO(ralntdir): read this from a scene file? #define WIDTH 500 #define HEIGHT 500 #define MAX_COLOR 255 #define MAX_SAMPLES 100 #define MAX_DEPTH 5 #include <math.h> #include "myMath.h" struct ray { vec3 origin; vec3 direction; }; struct sphere { vec3 center; real32 radius; vec3 ka; vec3 kd; vec3 ks; vec3 kr; real32 alpha; }; enum light_type { point, directional, }; struct light { vec3 position; vec3 intensity; light_type type; }; struct scene { vec3 camera; vec3 ul; vec3 ur; vec3 lr; vec3 ll; int32 maxSpheres = 8; int32 maxLights = 2; int32 numSpheres; int32 numLights; light lights[2]; sphere spheres[8]; }; bool hitSphere(sphere mySphere, ray myRay, real32 *t) { bool result = false; vec3 originCenter = myRay.origin - mySphere.center; real32 a = dotProduct(myRay.direction, myRay.direction); real32 b = 2 * dotProduct(originCenter, myRay.direction); real32 c = dotProduct(originCenter, originCenter) - mySphere.radius*mySphere.radius; real32 discriminant = b*b - 4*a*c; if (discriminant < 0) { return(result); } else { result = true; real32 root1 = (-b + sqrt(discriminant))/(2*a); real32 root2 = (-b - sqrt(discriminant))/(2*a); if ((root1 < root2) && (root1 > 0.0)) { *t = root1; } else if ((root2 < root1) && (root2 > 0.0)) { *t = root2; } else if ((root1 < 0) && (root2 < 0)) { result = false; } } return(result); } // TODO(ralntdir): add attenuation for point lights // TODO(ralntdir): technically this is not Phong Shading vec3 phongShading(light myLight, sphere mySphere, vec3 camera, vec3 hitPoint, real32 visible, int32 depth) { vec3 result; // *N vector (normal at hit point) // *L vector (lightPosition - hitPoint) vec3 N = normalize(hitPoint - mySphere.center); vec3 L = {}; if (myLight.type == point) { L = normalize(myLight.position - hitPoint); } else if (myLight.type == directional) { L = normalize(-myLight.position); } real32 dotProductLN = max(dotProduct(L, N), 0.0); real32 filterSpecular = dotProductLN > 0.0 ? 1.0 : 0.0; // *R vector (reflection of L -> 2(L·N)N - L) // *V vector (camera - hitPoint) vec3 R = normalize(2*dotProduct(L, N)*N - L); vec3 V = normalize(camera - hitPoint); // Only add specular component if you have diffuse, // if dotProductLN > 0.0 if (depth == 1) { result = mySphere.ka*myLight.intensity + visible*mySphere.kd*myLight.intensity*dotProductLN + visible*filterSpecular*mySphere.ks*myLight.intensity*pow(max(dotProduct(R, V), 0.0), mySphere.alpha); } else if (depth > 1) { result = visible*mySphere.kd*myLight.intensity*dotProductLN + visible*filterSpecular*mySphere.ks*myLight.intensity*pow(max(dotProduct(R, V), 0.0), mySphere.alpha); } return(result); } ray getShadowRay(light myLight, vec3 hitPoint, vec3 normalAtHitPoint) { ray result = {}; // NOTE(ralntdir): delta to avoid shadow acne. real32 bias = 0.01; result.origin = hitPoint + normalAtHitPoint*bias; if (myLight.type == directional) { result.direction = normalize(-myLight.position); } else if (myLight.type == point) { result.direction = normalize(myLight.position - hitPoint); } return(result); } vec3 color(ray myRay, scene *myScene, vec3 backgroundColor, int32 depth) { // vec3 result = backgroundColor; vec3 result = { 0.0, 0.0, 0.0 }; if (depth <= MAX_DEPTH) { real32 maxt = FLT_MAX; real32 t = -1.0; for (int i = 0; i < myScene->numSpheres; i++) { sphere mySphere = myScene->spheres[i]; if (hitSphere(mySphere, myRay, &t)) { if ((t >= 0.0) && (t < maxt)) { result = {}; maxt = t; vec3 hitPoint = myRay.origin + t*myRay.direction; vec3 N = normalize(hitPoint - mySphere.center); for (int j = 0; j < myScene->numLights; j++) { light myLight = myScene->lights[j]; ray shadowRay = getShadowRay(myLight, hitPoint, N); real32 visible = 1.0; for (int k = 0; k < myScene->numSpheres; k++) { if (i != k) { sphere mySphere1 = myScene->spheres[k]; real32 t1 = -1.0; if (hitSphere(mySphere1, shadowRay, &t1)) { visible = 0.0; break; } } } result += phongShading(myLight, mySphere, myScene->camera, hitPoint, visible, depth); } // Add reflection ray reflectedRay = {}; reflectedRay.origin = hitPoint + N*0.01; reflectedRay.direction = 2*dotProduct(-myRay.direction, N)*N + myRay.direction; result += mySphere.kr*color(reflectedRay, myScene, backgroundColor, depth+1); } } } } return(result); } void readSceneFile(scene *myScene, char *filename) { std::string line; std::ifstream scene(filename); if (scene.is_open()) { while (!scene.eof()) { scene >> line; // If line is not a comment if (line[0] == '#') { std::getline(scene, line); std::cout << line << "\n"; } else { std::cout << line << "\n"; if (line == "camera") { scene >> myScene->camera.x; scene >> myScene->camera.y; scene >> myScene->camera.z; } else if (line == "sphere") { sphere mySphere = {}; scene >> line; // center scene >> mySphere.center.x; scene >> mySphere.center.y; scene >> mySphere.center.z; scene >> line; // radius scene >> mySphere.radius; scene >> line; // ka scene >> mySphere.ka.x; scene >> mySphere.ka.y; scene >> mySphere.ka.z; scene >> line; // kd scene >> mySphere.kd.x; scene >> mySphere.kd.y; scene >> mySphere.kd.z; scene >> line; // ks scene >> mySphere.ks.x; scene >> mySphere.ks.y; scene >> mySphere.ks.z; scene >> line; // kr || alpha if (line == "kr") { scene >> mySphere.kr.x; scene >> mySphere.kr.y; scene >> mySphere.kr.z; scene >> line; // alpha scene >> mySphere.alpha; } else if (line == "alpha") { scene >> mySphere.alpha; } myScene->numSpheres++; if (myScene->numSpheres <= myScene->maxSpheres) { myScene->spheres[myScene->numSpheres-1] = mySphere; } } else if (line == "light") { light myLight = {}; scene >> line; // position scene >> myLight.position.x; scene >> myLight.position.y; scene >> myLight.position.z; scene >> line; // intensity scene >> myLight.intensity.x; scene >> myLight.intensity.y; scene >> myLight.intensity.z; scene >> line; // type scene >> line; if (line.compare("point") == 0) { myLight.type = point; } else if (line.compare("directional") == 0) { myLight.type = directional; } myScene->numLights++; if (myScene->numLights <= myScene->maxLights) { myScene->lights[myScene->numLights-1] = myLight; } } else if (line == "ul") { vec3 ul = {}; scene >> ul.x; scene >> ul.y; scene >> ul.z; myScene->ul = ul; } else if (line == "ur") { vec3 ur = {}; scene >> ur.x; scene >> ur.y; scene >> ur.z; myScene->ur = ur; } else if (line == "lr") { vec3 lr = {}; scene >> lr.x; scene >> lr.y; scene >> lr.z; myScene->lr = lr; } else if (line == "ll") { vec3 ll = {}; scene >> ll.x; scene >> ll.y; scene >> ll.z; myScene->ll = ll; } } } scene.close(); } else { std::cout << "There was a problem opening the scene file\n"; } } int main(int argc, char* argv[]) { SDL_Window *window; SDL_Renderer *renderer; SDL_Surface *surface; SDL_Texture *texture; if (argc < 2) { std::cout << "Missing scene file. Usage: ./program sceneFile\n"; return(1); } char *sceneFileName = argv[1]; // Init SDL if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "Error in SDL_Init(): " << SDL_GetError() << "\n"; } // Init SDL_Image if (IMG_Init(0) < 0) { std::cout << "Error in IMG_Init(): " << IMG_GetError() << "\n"; } // Create a Window // NOTE(ralntdir): SDL_WINDOW_SHOWN is ignored by SDL_CreateWindow(). // The SDL_Window is implicitly shown if SDL_WINDOW_HIDDEN is not set. window = SDL_CreateWindow("Devember RT", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN); if (window == 0) { std::cout << "Error in SDL_CreateWindow(): " << SDL_GetError() << "\n"; } // Create a Renderer renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == 0) { std::cout << "Error in SDL_CreateRenderer(): " << SDL_GetError() << "\n"; } scene myScene = {}; // Read scene file readSceneFile(&myScene, sceneFileName); // Create a .ppm file std::ofstream ofs("image.ppm", std::ofstream::out | std::ofstream::binary); ofs << "P3\n"; ofs << "# image.ppm\n"; ofs << WIDTH << " " << HEIGHT << "\n"; ofs << MAX_COLOR << "\n"; vec3 horizontalOffset = myScene.ur - myScene.ul; vec3 verticalOffset = myScene.ul - myScene.ll; vec3 lowerLeftCorner = myScene.ll; // NOTE(ralntdir): generates random unsigned integers std::default_random_engine engine; // NOTE(ralntdir): generates random floats between [0, 1) std::uniform_real_distribution<real32> distribution(0, 1); int32 depth = 1; // NOTE(ralntdir): From top to bottom for (int32 i = HEIGHT-1; i >= 0 ; i--) { for (int32 j = 0; j < WIDTH; j++) { vec3 backgroundColor = { 0.0, ((real32)i/HEIGHT), ((real32)j/WIDTH) }; vec3 col = {}; for (int32 samples = 0; samples < MAX_SAMPLES; samples++) { real32 u = real32(j + distribution(engine))/real32(WIDTH); real32 v = real32(i + distribution(engine))/real32(HEIGHT); ray cameraRay = {}; cameraRay.origin = myScene.camera; cameraRay.direction = lowerLeftCorner + u*horizontalOffset + v*verticalOffset; vec3 tempCol = color(cameraRay, &myScene, backgroundColor, depth); clamp(&tempCol); col += tempCol; } col /= (real32)MAX_SAMPLES; int32 r = int32(255.0*col.e[0]); int32 g = int32(255.0*col.e[1]); int32 b = int32(255.0*col.e[2]); ofs << r << " " << g << " " << b << "\n"; } } ofs.close(); // Load the image surface = IMG_Load("image.ppm"); if (surface == 0) { std::cout << "Error in IMG_Load(): " << IMG_GetError() << "\n"; } texture = SDL_CreateTextureFromSurface(renderer, surface); if (texture == 0) { std::cout << "Error in SDL_CreateTextureFromSurface(): " << SDL_GetError() << "\n"; } SDL_FreeSurface(surface); SDL_Event event; bool running = true; while (running) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; } else if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { running = false; } } } // Show the texture SDL_RenderCopy(renderer, texture, 0, 0); SDL_RenderPresent(renderer); } // Free the texture SDL_DestroyTexture(texture); // Quit IMG IMG_Quit(); // Quit SDL SDL_Quit(); return(0); } <commit_msg>Ambient contribution should be added only once, not for every light!!! Fixed<commit_after>// TODO(ralntdir): // Think how to clean SDL if the programs ends with some crash // Finished the program if there is a problem at SDL/IMG init or // when creating the window or the renderer // // Features to add: // ray->sphere intersection (check if it's completed) // shadows // reflection // read llc, hoffset and voffset from file // Files manipulation #include <iostream> #include <fstream> #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> // NOTE(ralntdir): For number types #include <stdint.h> // NOTE(ralntdir): For rand #include <random> // NOTE(ralntdir): For FLT_MAX #include <float.h> typedef int32_t int32; typedef float real32; typedef double real64; // TODO(ralntdir): read this from a scene file? #define WIDTH 500 #define HEIGHT 500 #define MAX_COLOR 255 #define MAX_SAMPLES 100 #define MAX_DEPTH 5 #include <math.h> #include "myMath.h" struct ray { vec3 origin; vec3 direction; }; struct sphere { vec3 center; real32 radius; vec3 ka; vec3 kd; vec3 ks; vec3 kr; real32 alpha; }; enum light_type { point, directional, }; struct light { vec3 position; vec3 intensity; light_type type; }; struct scene { vec3 camera; vec3 ul; vec3 ur; vec3 lr; vec3 ll; int32 maxSpheres = 8; int32 maxLights = 2; int32 numSpheres; int32 numLights; light lights[2]; sphere spheres[8]; }; bool hitSphere(sphere mySphere, ray myRay, real32 *t) { bool result = false; vec3 originCenter = myRay.origin - mySphere.center; real32 a = dotProduct(myRay.direction, myRay.direction); real32 b = 2 * dotProduct(originCenter, myRay.direction); real32 c = dotProduct(originCenter, originCenter) - mySphere.radius*mySphere.radius; real32 discriminant = b*b - 4*a*c; if (discriminant < 0) { return(result); } else { result = true; real32 root1 = (-b + sqrt(discriminant))/(2*a); real32 root2 = (-b - sqrt(discriminant))/(2*a); if ((root1 < root2) && (root1 > 0.0)) { *t = root1; } else if ((root2 < root1) && (root2 > 0.0)) { *t = root2; } else if ((root1 < 0) && (root2 < 0)) { result = false; } } return(result); } // TODO(ralntdir): add attenuation for point lights // TODO(ralntdir): technically this is not Phong Shading vec3 phongShading(light myLight, sphere mySphere, vec3 camera, vec3 hitPoint, real32 visible, int32 depth) { vec3 result; // *N vector (normal at hit point) // *L vector (lightPosition - hitPoint) vec3 N = normalize(hitPoint - mySphere.center); vec3 L = {}; if (myLight.type == point) { L = normalize(myLight.position - hitPoint); } else if (myLight.type == directional) { L = normalize(-myLight.position); } real32 dotProductLN = max(dotProduct(L, N), 0.0); real32 filterSpecular = dotProductLN > 0.0 ? 1.0 : 0.0; // *R vector (reflection of L -> 2(L·N)N - L) // *V vector (camera - hitPoint) vec3 R = normalize(2*dotProduct(L, N)*N - L); vec3 V = normalize(camera - hitPoint); // Only add specular component if you have diffuse, // if dotProductLN > 0.0 // if (depth == -1) // { // result = mySphere.ka*myLight.intensity + // visible*mySphere.kd*myLight.intensity*dotProductLN + // visible*filterSpecular*mySphere.ks*myLight.intensity*pow(max(dotProduct(R, V), 0.0), mySphere.alpha); // } // else if (depth > 1) // { result = visible*mySphere.kd*myLight.intensity*dotProductLN + visible*filterSpecular*mySphere.ks*myLight.intensity*pow(max(dotProduct(R, V), 0.0), mySphere.alpha); // } return(result); } ray getShadowRay(light myLight, vec3 hitPoint, vec3 normalAtHitPoint) { ray result = {}; // NOTE(ralntdir): delta to avoid shadow acne. real32 bias = 0.01; result.origin = hitPoint + normalAtHitPoint*bias; if (myLight.type == directional) { result.direction = normalize(-myLight.position); } else if (myLight.type == point) { result.direction = normalize(myLight.position - hitPoint); } return(result); } vec3 color(ray myRay, scene *myScene, vec3 backgroundColor, int32 depth) { // vec3 result = backgroundColor; vec3 result = { 0.0, 0.0, 0.0 }; if (depth <= MAX_DEPTH) { real32 maxt = FLT_MAX; real32 t = -1.0; for (int i = 0; i < myScene->numSpheres; i++) { sphere mySphere = myScene->spheres[i]; if (hitSphere(mySphere, myRay, &t)) { if ((t >= 0.0) && (t < maxt)) { result = {}; // NOTE(ralntdir): Let's suppose that ia is (1.0, 1.0, 1.0) result += mySphere.ka; maxt = t; vec3 hitPoint = myRay.origin + t*myRay.direction; vec3 N = normalize(hitPoint - mySphere.center); for (int j = 0; j < myScene->numLights; j++) { light myLight = myScene->lights[j]; ray shadowRay = getShadowRay(myLight, hitPoint, N); real32 visible = 1.0; for (int k = 0; k < myScene->numSpheres; k++) { if (i != k) { sphere mySphere1 = myScene->spheres[k]; real32 t1 = -1.0; if (hitSphere(mySphere1, shadowRay, &t1)) { visible = 0.0; break; } } } result += phongShading(myLight, mySphere, myScene->camera, hitPoint, visible, depth); } // Add reflection ray reflectedRay = {}; reflectedRay.origin = hitPoint + N*0.01; reflectedRay.direction = 2*dotProduct(-myRay.direction, N)*N + myRay.direction; result += mySphere.kr*color(reflectedRay, myScene, backgroundColor, depth+1); } } } } return(result); } void readSceneFile(scene *myScene, char *filename) { std::string line; std::ifstream scene(filename); if (scene.is_open()) { while (!scene.eof()) { scene >> line; // If line is not a comment if (line[0] == '#') { std::getline(scene, line); std::cout << line << "\n"; } else { std::cout << line << "\n"; if (line == "camera") { scene >> myScene->camera.x; scene >> myScene->camera.y; scene >> myScene->camera.z; } else if (line == "sphere") { sphere mySphere = {}; scene >> line; // center scene >> mySphere.center.x; scene >> mySphere.center.y; scene >> mySphere.center.z; scene >> line; // radius scene >> mySphere.radius; scene >> line; // ka scene >> mySphere.ka.x; scene >> mySphere.ka.y; scene >> mySphere.ka.z; scene >> line; // kd scene >> mySphere.kd.x; scene >> mySphere.kd.y; scene >> mySphere.kd.z; scene >> line; // ks scene >> mySphere.ks.x; scene >> mySphere.ks.y; scene >> mySphere.ks.z; scene >> line; // kr || alpha if (line == "kr") { scene >> mySphere.kr.x; scene >> mySphere.kr.y; scene >> mySphere.kr.z; scene >> line; // alpha scene >> mySphere.alpha; } else if (line == "alpha") { scene >> mySphere.alpha; } myScene->numSpheres++; if (myScene->numSpheres <= myScene->maxSpheres) { myScene->spheres[myScene->numSpheres-1] = mySphere; } } else if (line == "light") { light myLight = {}; scene >> line; // position scene >> myLight.position.x; scene >> myLight.position.y; scene >> myLight.position.z; scene >> line; // intensity scene >> myLight.intensity.x; scene >> myLight.intensity.y; scene >> myLight.intensity.z; scene >> line; // type scene >> line; if (line.compare("point") == 0) { myLight.type = point; } else if (line.compare("directional") == 0) { myLight.type = directional; } myScene->numLights++; if (myScene->numLights <= myScene->maxLights) { myScene->lights[myScene->numLights-1] = myLight; } } else if (line == "ul") { vec3 ul = {}; scene >> ul.x; scene >> ul.y; scene >> ul.z; myScene->ul = ul; } else if (line == "ur") { vec3 ur = {}; scene >> ur.x; scene >> ur.y; scene >> ur.z; myScene->ur = ur; } else if (line == "lr") { vec3 lr = {}; scene >> lr.x; scene >> lr.y; scene >> lr.z; myScene->lr = lr; } else if (line == "ll") { vec3 ll = {}; scene >> ll.x; scene >> ll.y; scene >> ll.z; myScene->ll = ll; } } } scene.close(); } else { std::cout << "There was a problem opening the scene file\n"; } } int main(int argc, char* argv[]) { SDL_Window *window; SDL_Renderer *renderer; SDL_Surface *surface; SDL_Texture *texture; if (argc < 2) { std::cout << "Missing scene file. Usage: ./program sceneFile\n"; return(1); } char *sceneFileName = argv[1]; // Init SDL if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "Error in SDL_Init(): " << SDL_GetError() << "\n"; } // Init SDL_Image if (IMG_Init(0) < 0) { std::cout << "Error in IMG_Init(): " << IMG_GetError() << "\n"; } // Create a Window // NOTE(ralntdir): SDL_WINDOW_SHOWN is ignored by SDL_CreateWindow(). // The SDL_Window is implicitly shown if SDL_WINDOW_HIDDEN is not set. window = SDL_CreateWindow("Devember RT", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN); if (window == 0) { std::cout << "Error in SDL_CreateWindow(): " << SDL_GetError() << "\n"; } // Create a Renderer renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == 0) { std::cout << "Error in SDL_CreateRenderer(): " << SDL_GetError() << "\n"; } scene myScene = {}; // Read scene file readSceneFile(&myScene, sceneFileName); // Create a .ppm file std::ofstream ofs("image.ppm", std::ofstream::out | std::ofstream::binary); ofs << "P3\n"; ofs << "# image.ppm\n"; ofs << WIDTH << " " << HEIGHT << "\n"; ofs << MAX_COLOR << "\n"; vec3 horizontalOffset = myScene.ur - myScene.ul; vec3 verticalOffset = myScene.ul - myScene.ll; vec3 lowerLeftCorner = myScene.ll; // NOTE(ralntdir): generates random unsigned integers std::default_random_engine engine; // NOTE(ralntdir): generates random floats between [0, 1) std::uniform_real_distribution<real32> distribution(0, 1); int32 depth = 1; // NOTE(ralntdir): From top to bottom for (int32 i = HEIGHT-1; i >= 0 ; i--) { for (int32 j = 0; j < WIDTH; j++) { vec3 backgroundColor = { 0.0, ((real32)i/HEIGHT), ((real32)j/WIDTH) }; vec3 col = {}; for (int32 samples = 0; samples < MAX_SAMPLES; samples++) { real32 u = real32(j + distribution(engine))/real32(WIDTH); real32 v = real32(i + distribution(engine))/real32(HEIGHT); ray cameraRay = {}; cameraRay.origin = myScene.camera; cameraRay.direction = lowerLeftCorner + u*horizontalOffset + v*verticalOffset; vec3 tempCol = color(cameraRay, &myScene, backgroundColor, depth); clamp(&tempCol); col += tempCol; } col /= (real32)MAX_SAMPLES; int32 r = int32(255.0*col.e[0]); int32 g = int32(255.0*col.e[1]); int32 b = int32(255.0*col.e[2]); ofs << r << " " << g << " " << b << "\n"; } } ofs.close(); // Load the image surface = IMG_Load("image.ppm"); if (surface == 0) { std::cout << "Error in IMG_Load(): " << IMG_GetError() << "\n"; } texture = SDL_CreateTextureFromSurface(renderer, surface); if (texture == 0) { std::cout << "Error in SDL_CreateTextureFromSurface(): " << SDL_GetError() << "\n"; } SDL_FreeSurface(surface); SDL_Event event; bool running = true; while (running) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; } else if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { running = false; } } } // Show the texture SDL_RenderCopy(renderer, texture, 0, 0); SDL_RenderPresent(renderer); } // Free the texture SDL_DestroyTexture(texture); // Quit IMG IMG_Quit(); // Quit SDL SDL_Quit(); return(0); } <|endoftext|>
<commit_before>/*********************************************************************** row.cpp - Implements the Row class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "row.h" #include "result.h" #include "exceptions.h" namespace mysqlpp { Row::size_type Row::size() const { return res->num_fields(); } const ColData Row::operator[] (size_type i) const { if (!initialized) { if (throw_exceptions) throw BadQuery("Row not initialized"); else return ColData(); } return ColData(data.at(i).c_str(), res->types(i), is_nulls[i]); } const ColData Row::lookup_by_name(const char* i) const { int si = res->field_num(std::string(i)); if (si < res->num_fields()) { return (*this)[si]; } else { throw BadFieldName(i); } } } // end namespace mysqlpp <commit_msg>Whitespace change<commit_after>/*********************************************************************** row.cpp - Implements the Row class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "row.h" #include "result.h" #include "exceptions.h" namespace mysqlpp { Row::size_type Row::size() const { return res->num_fields(); } const ColData Row::operator [](size_type i) const { if (!initialized) { if (throw_exceptions) throw BadQuery("Row not initialized"); else return ColData(); } return ColData(data.at(i).c_str(), res->types(i), is_nulls[i]); } const ColData Row::lookup_by_name(const char* i) const { int si = res->field_num(std::string(i)); if (si < res->num_fields()) { return (*this)[si]; } else { throw BadFieldName(i); } } } // end namespace mysqlpp <|endoftext|>
<commit_before>// Copyright © 2018 Dmitriy Khaustov // // 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. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2018.10.08 // MysqlRow.hpp #pragma once #include <mysql.h> #include "../DbRow.hpp" #include <type_traits> #include <string> class MysqlRow final : public DbRow { private: MYSQL_ROW _data; public: MysqlRow(MysqlRow&&) noexcept = delete; // Move-constructor MysqlRow(const MysqlRow&) = delete; // Copy-constructor MysqlRow& operator=(MysqlRow&&) noexcept = delete; // Move-assignment MysqlRow& operator=(MysqlRow const&) = delete; // Copy-assignment MysqlRow() // Default-constructor : _data(nullptr) { } virtual ~MysqlRow() override = default; // Destructor void set(MYSQL_ROW value) { _data = value; } MYSQL_ROW get() { return _data; } class FieldValue final { private: const char * const _data; public: FieldValue(const char *const data): _data(data) {} template<typename T, typename std::enable_if<std::is_integral<T>::value, void>::type* = nullptr> operator T() const { typename std::enable_if<std::is_integral<T>::value, bool>::type detect(); return static_cast<T>(_data ? std::atoll(_data) : 0); } template<typename T, typename std::enable_if<std::is_floating_point<T>::value, void>::type* = nullptr> operator T() const { typename std::enable_if<std::is_floating_point<T>::value, bool>::type detect(); return static_cast<T>(_data ? std::atof(_data) : 0); } template<typename T, typename std::enable_if<std::is_same<std::string, T>::value, void>::type* = nullptr> operator T() const { typename std::enable_if<std::is_same<std::string, T>::value, void>::type detect(); return T(_data ? _data : ""); } }; FieldValue operator[](size_t index) const { return _data[index]; } }; <commit_msg>Little improve MysqlRow class<commit_after>// Copyright © 2018 Dmitriy Khaustov // // 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. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2018.10.08 // MysqlRow.hpp #pragma once #include <mysql.h> #include "../DbRow.hpp" #include <type_traits> #include <string> class MysqlRow final : public DbRow { private: MYSQL_ROW _data; public: MysqlRow(MysqlRow&&) noexcept = delete; // Move-constructor MysqlRow(const MysqlRow&) = delete; // Copy-constructor MysqlRow& operator=(MysqlRow&&) noexcept = delete; // Move-assignment MysqlRow& operator=(MysqlRow const&) = delete; // Copy-assignment MysqlRow() // Default-constructor : _data(nullptr) { } ~MysqlRow() override = default; // Destructor void set(MYSQL_ROW value) { _data = value; } MYSQL_ROW get() { return _data; } class FieldValue final { private: const char * const _data; public: FieldValue(const char *const data): _data(data) {} bool isNull() const { return _data == nullptr; } template<typename T, typename std::enable_if<std::is_integral<T>::value, void>::type* = nullptr> operator T() const { typename std::enable_if<std::is_integral<T>::value, bool>::type detect(); return static_cast<T>(_data ? std::atoll(_data) : 0); } template<typename T, typename std::enable_if<std::is_floating_point<T>::value, void>::type* = nullptr> operator T() const { typename std::enable_if<std::is_floating_point<T>::value, bool>::type detect(); return static_cast<T>(_data ? std::atof(_data) : 0); } template<typename T, typename std::enable_if<std::is_same<std::string, T>::value, void>::type* = nullptr> operator T() const { typename std::enable_if<std::is_same<std::string, T>::value, void>::type detect(); return T(_data ? _data : ""); } }; FieldValue operator[](size_t index) const { return _data[index]; } }; <|endoftext|>
<commit_before>#pragma once class local_datagram_client final { public: local_datagram_client(const char* _Nonnull path) : endpoint_(path), io_service_(), work_(io_service_), socket_(io_service_) { socket_.open(); thread_ = std::thread([this] { (this->io_service_).run(); }); } ~local_datagram_client(void) { io_service_.post(boost::bind(&local_datagram_client::do_stop, this)); thread_.join(); } void send_to(const uint8_t* _Nonnull p, size_t length) { auto ptr = std::make_shared<buffer>(p, length); io_service_.post(boost::bind(&local_datagram_client::do_send, this, ptr)); } private: class buffer final { public: buffer(const uint8_t* _Nonnull p, size_t length) { v_.resize(length); memcpy(&(v_[0]), p, length); } const std::vector<uint8_t>& get_vector(void) const { return v_; } private: std::vector<uint8_t> v_; }; void do_send(const std::shared_ptr<buffer>& ptr) { socket_.async_send_to(boost::asio::buffer(ptr->get_vector()), endpoint_, boost::bind(&local_datagram_client::handle_send, this, ptr)); } void handle_send(const std::shared_ptr<buffer>& ptr) { // buffer will be released. } void do_stop(void) { io_service_.stop(); } boost::asio::local::datagram_protocol::endpoint endpoint_; boost::asio::io_service io_service_; boost::asio::io_service::work work_; boost::asio::local::datagram_protocol::socket socket_; std::thread thread_; }; <commit_msg>change send_to args<commit_after>#pragma once class local_datagram_client final { public: local_datagram_client(const char* _Nonnull path) : endpoint_(path), io_service_(), work_(io_service_), socket_(io_service_) { socket_.open(); thread_ = std::thread([this] { (this->io_service_).run(); }); } ~local_datagram_client(void) { io_service_.post(boost::bind(&local_datagram_client::do_stop, this)); thread_.join(); } void send_to(const std::vector<uint8_t>& v) { auto ptr = std::make_shared<buffer>(v); io_service_.post(boost::bind(&local_datagram_client::do_send, this, ptr)); } private: class buffer final { public: buffer(const std::vector<uint8_t> v) { v_ = v; } buffer(const uint8_t* _Nonnull p, size_t length) { v_.resize(length); memcpy(&(v_[0]), p, length); } const std::vector<uint8_t>& get_vector(void) const { return v_; } private: std::vector<uint8_t> v_; }; void do_send(const std::shared_ptr<buffer>& ptr) { socket_.async_send_to(boost::asio::buffer(ptr->get_vector()), endpoint_, boost::bind(&local_datagram_client::handle_send, this, ptr)); } void handle_send(const std::shared_ptr<buffer>& ptr) { // buffer will be released. } void do_stop(void) { io_service_.stop(); } boost::asio::local::datagram_protocol::endpoint endpoint_; boost::asio::io_service io_service_; boost::asio::io_service::work work_; boost::asio::local::datagram_protocol::socket socket_; std::thread thread_; }; <|endoftext|>
<commit_before>// Copyright (C) 2014 sails Authors. // All rights reserved. // // Filename: saf.cc // // Author: sailsxu <[email protected]> // Created: 2014-10-13 17:10:36 #include <sails/net/epoll_server.h> #include <sails/net/connector.h> #include <signal.h> //#include <gperftools/profiler.h> #include "src/monitor.h" #include "src/server.h" sails::Config config; bool isRun = true; sails::Server server; sails::Monitor* monitor; void sails_signal_handle(int signo, siginfo_t *, void *) { switch (signo) { case SIGINT: { server.Stop(); isRun = false; delete monitor; break; } } } void sails_init(int, char **) { // signal kill struct sigaction act; act.sa_sigaction = sails_signal_handle; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (sigaction(SIGINT, &act, NULL) == -1) { perror("sigaction error"); exit(EXIT_FAILURE); } // 初始化server server.Init(config.get_listen_port(), 3, 10, config.get_handle_thread(), true); monitor = new sails::Monitor(&server, config.get_monitor_port()); monitor->Run(); } int main(int argc, char *argv[]) { sails_init(argc, argv); // ProfilerStart("saf.prof"); while (isRun) { sleep(2); } // ProfilerStop(); char msg[100] = {'\0'}; snprintf(msg, sizeof(msg), "total send:%lld\n", server.send_data); perror(msg); sleep(2); return 0; } <commit_msg>update<commit_after>// Copyright (C) 2014 sails Authors. // All rights reserved. // // Filename: saf.cc // // Author: sailsxu <[email protected]> // Created: 2014-10-13 17:10:36 #include <sails/net/epoll_server.h> #include <sails/net/connector.h> #include <signal.h> //#include <gperftools/profiler.h> #include "src/monitor.h" #include "src/server.h" sails::Config config; bool isRun = true; sails::Server server; sails::Monitor* monitor; void sails_signal_handle(int signo, siginfo_t *, void *) { switch (signo) { case SIGINT: { server.Stop(); isRun = false; delete monitor; break; } } } void sails_init(int, char **) { // signal kill struct sigaction act; act.sa_sigaction = sails_signal_handle; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (sigaction(SIGINT, &act, NULL) == -1) { perror("sigaction error"); exit(EXIT_FAILURE); } // 初始化server server.Init(config.get_listen_port(), 3, 10, config.get_handle_thread(), true); monitor = new sails::Monitor(&server, config.get_monitor_port()); monitor->Run(); } int main(int argc, char *argv[]) { sails_init(argc, argv); // ProfilerStart("saf.prof"); while (isRun) { sleep(2); } // ProfilerStop(); return 0; } <|endoftext|>
<commit_before>#include "vogleditor_qsettingsdialog.h" #include "ui_vogleditor_qsettingsdialog.h" #include "vogleditor_qsettings.h" vogleditor_QSettingsDialog::vogleditor_QSettingsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::vogleditor_QSettingsDialog) { ui->setupUi(this); // tab parent ui->tabWidget->setCurrentIndex(g_settings.tab_page()); connect(ui->tabWidget, SIGNAL(currentChanged(int)), SLOT(tabCB(int))); connect(ui->buttonBox, SIGNAL(accepted()), SLOT(acceptCB())); connect(ui->buttonBox, SIGNAL(rejected()), SLOT(cancelCB())); connect(this, &vogleditor_QSettingsDialog::settingsChanged, &g_settings, &vogleditor_qsettings::update_group_active_lists); // Startup settings tab QString strSettings = g_settings.to_string(); ui->textEdit->setText(strSettings); // Group settings tab // State Render ui->checkboxStateRender->setText(g_settings.group_state_render_name()); ui->checkboxStateRender->setChecked(g_settings.group_state_render_stat()); ui->checkboxStateRender->setEnabled(g_settings.group_state_render_used()); connect(ui->checkboxStateRender, SIGNAL(stateChanged(int)), SLOT(checkboxStateRenderCB(int))); // Debug markers QVector<QCheckBox *> checkboxList; QStringList group_debug_marker_names = g_settings.group_debug_marker_names(); QVector<bool> debug_marker_stat = g_settings.group_debug_marker_stat(); QVector<bool> debug_marker_used = g_settings.group_debug_marker_used(); int debug_marker_cnt = group_debug_marker_names.size(); for (int i = 0; i < debug_marker_cnt; i++) { checkboxList << new QCheckBox(group_debug_marker_names[i], ui->groupboxDebugMarker); checkboxList[i]->setChecked(debug_marker_stat[i]); checkboxList[i]->setEnabled(debug_marker_used[i]); ui->vLayout_groupboxDebugMarker->insertWidget(i, checkboxList[i]); } for (int i = 0; i < debug_marker_cnt; i++) { connect(checkboxList[i], SIGNAL(stateChanged(int)), SLOT(checkboxCB(int))); } // Debug marker options ui->radiobuttonDebugMarkerNameOption->setText(g_settings.group_debug_marker_option_name_label()); ui->radiobuttonDebugMarkerNameOption->setChecked(g_settings.group_debug_marker_option_name_stat()); ui->radiobuttonDebugMarkerOmitOption->setText(g_settings.group_debug_marker_option_omit_label()); ui->radiobuttonDebugMarkerOmitOption->setChecked(g_settings.group_debug_marker_option_omit_stat()); setEnableDebugMarkerOptions(); connect(ui->radiobuttonDebugMarkerNameOption, SIGNAL(toggled(bool)), SLOT(radiobuttonNameCB(bool))); connect(ui->radiobuttonDebugMarkerOmitOption, SIGNAL(toggled(bool)), SLOT(radiobuttonOmitCB(bool))); // Nest options checkboxList.clear(); // Groupbox ui->groupboxNestOptions->setTitle(g_settings.groupbox_nest_options_name()); ui->groupboxNestOptions->setChecked(g_settings.groupbox_nest_options_stat()); ui->groupboxNestOptions->setEnabled(g_settings.groupbox_nest_options_used()); if (g_settings.groupbox_nest_options_stat()) { // For now, toggle State/Render groups and Nest options checkboxStateRenderCB(false); } // Checkboxes QStringList group_nest_options_names = g_settings.group_nest_options_names(); QVector<bool> nest_options_stat = g_settings.group_nest_options_stat(); QVector<bool> nest_options_used = g_settings.group_nest_options_used(); int nest_options_cnt = group_nest_options_names.size(); for (int i = 0; i < nest_options_cnt; i++) { checkboxList << new QCheckBox(group_nest_options_names[i], ui->groupboxNestOptions); checkboxList[i]->setChecked(nest_options_stat[i]); checkboxList[i]->setEnabled(nest_options_used[i]); ui->vLayout_groupboxNestOptionsScrollarea->addWidget(checkboxList[i]); } connect(ui->groupboxNestOptions, SIGNAL(toggled(bool)), // groupbox SLOT(groupboxNestOptionsCB(bool))); for (int i = 0; i < nest_options_cnt; i++) // checkboxes in groupbox { connect(checkboxList[i], SIGNAL(stateChanged(int)), SLOT(checkboxCB(int))); } // Save initial state m_bGroupInitialState = groupState(); } // constructor vogleditor_QSettingsDialog::~vogleditor_QSettingsDialog() { delete ui; clearLayout(ui->verticalLayout_tabGroups); } // destructor void vogleditor_QSettingsDialog::clearLayout(QLayout *layout) { // taken from // http://stackoverflow.com/questions/4272196/qt-remove-all-widgets-from-layout // ... didn't seem to make any difference using valgrind Memcheck... while (QLayoutItem *item = layout->takeAt(0)) { delete item->widget(); if (QLayout *childLayout = item->layout()) clearLayout(childLayout); delete item; } } // clearLayout void vogleditor_QSettingsDialog::tabCB(int page) { g_settings.set_tab_page(page); } void vogleditor_QSettingsDialog::checkboxStateRenderCB(int val) { bool bVal = bool(val); if (bVal) { ui->groupboxNestOptions->setChecked(!bVal); g_settings.set_groupbox_nest_options_stat(!bVal); } // Update g_settings.set_group_state_render_stat(bVal); updateTextTab(); } // checkboxStateRenderCB void vogleditor_QSettingsDialog::groupboxNestOptionsCB(bool bVal) { if (bVal) { ui->checkboxStateRender->setChecked(!bVal); g_settings.set_group_state_render_stat(!bVal); } // Update g_settings.set_groupbox_nest_options_stat(bVal); updateTextTab(); } // groupboxNestOptionsCB void vogleditor_QSettingsDialog::checkboxCB(int state) { g_settings.set_group_state_render_stat(ui->checkboxStateRender->isChecked()); g_settings.set_group_debug_marker_stat(checkboxValues(ui->groupboxDebugMarker)); g_settings.set_group_nest_options_stat(checkboxValues(ui->groupboxNestOptions)); setEnableDebugMarkerOptions(); updateTextTab(); } // checkboxCB void vogleditor_QSettingsDialog::setEnableDebugMarkerOptions() { // Disable options if no Debug marker groups are checked QVector<bool> bCurrentState = checkboxValues(ui->groupboxDebugMarker); bool bVal; foreach(bVal, bCurrentState) { if (bVal) break; } enableDebugMarkerOptions(bVal); } void vogleditor_QSettingsDialog::enableDebugMarkerOptions(bool bVal) { ui->radiobuttonDebugMarkerNameOption->setEnabled(bVal); ui->radiobuttonDebugMarkerOmitOption->setEnabled(bVal); // Notify g_settings g_settings.set_group_debug_marker_option_name_used(bVal); g_settings.set_group_debug_marker_option_omit_used(bVal); } void vogleditor_QSettingsDialog::radiobuttonNameCB(bool state) { g_settings.set_group_debug_marker_option_name_stat(state); updateTextTab(); } void vogleditor_QSettingsDialog::radiobuttonOmitCB(bool state) { g_settings.set_group_debug_marker_option_omit_stat(state); updateTextTab(); } void vogleditor_QSettingsDialog::updateTextTab() { //update json tab settings page QString strSettings = g_settings.to_string(); ui->textEdit->setText(strSettings); } QVector<bool> vogleditor_QSettingsDialog::checkboxValues(QObject *widget) { // Note: This function is intended to only return checkbox values of // API call names, so for the Debug marker API call list parent // radiobuttons were used for the options. QList<QCheckBox *> groupCheckBoxes = widget->findChildren<QCheckBox *>(); QVector<bool> bQVector; QList<QCheckBox *>::const_iterator iter = groupCheckBoxes.begin(); while (iter != groupCheckBoxes.end()) { bQVector << (*iter)->isChecked(); iter++; } return bQVector; } // checkboxValues() QVector<bool> vogleditor_QSettingsDialog::groupState() { QVector<bool> bCurrentState; bCurrentState << ui->checkboxStateRender->isChecked(); bCurrentState << ui->groupboxNestOptions->isChecked(); bCurrentState << checkboxValues(ui->groupboxDebugMarker); bCurrentState << checkboxValues(ui->groupboxNestOptions); bCurrentState << ui->radiobuttonDebugMarkerNameOption->isChecked(); bCurrentState << ui->radiobuttonDebugMarkerOmitOption->isChecked(); return bCurrentState; } // groupState void vogleditor_QSettingsDialog::reset() { if (groupOptionsChanged()) { // Set in same order as saved (from ::groupState()) // // TODO: QMap these, widget key to value, in constructor // so order won't matter int i = 0; ui->checkboxStateRender->setChecked(m_bGroupInitialState[i++]); ui->groupboxNestOptions->setChecked(m_bGroupInitialState[i++]); QList<QCheckBox *> checkboxes = ui->groupboxDebugMarker->findChildren<QCheckBox *>(); for (int indx = 0; indx < checkboxes.count(); indx++) { checkboxes[indx]->setChecked(m_bGroupInitialState[i++]); } checkboxes = ui->groupboxNestOptions->findChildren<QCheckBox *>(); for (int indx = 0; indx < checkboxes.count(); indx++) { checkboxes[indx]->setChecked(m_bGroupInitialState[i++]); } ui->radiobuttonDebugMarkerNameOption->setChecked(m_bGroupInitialState[i++]); ui->radiobuttonDebugMarkerOmitOption->setChecked(m_bGroupInitialState[i++]); } } // reset bool vogleditor_QSettingsDialog::groupOptionsChanged() { return m_bGroupInitialState != groupState(); } void vogleditor_QSettingsDialog::acceptCB() { save(); if (groupOptionsChanged()) { emit settingsChanged(); } } void vogleditor_QSettingsDialog::cancelCB() { reset(); } void vogleditor_QSettingsDialog::save() { g_settings.from_string(ui->textEdit->toPlainText().toStdString().c_str()); g_settings.save(); } <commit_msg>vogleditor: Fix crash when closing settings dialog due to accessing a deleted object.<commit_after>#include "vogleditor_qsettingsdialog.h" #include "ui_vogleditor_qsettingsdialog.h" #include "vogleditor_qsettings.h" vogleditor_QSettingsDialog::vogleditor_QSettingsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::vogleditor_QSettingsDialog) { ui->setupUi(this); // tab parent ui->tabWidget->setCurrentIndex(g_settings.tab_page()); connect(ui->tabWidget, SIGNAL(currentChanged(int)), SLOT(tabCB(int))); connect(ui->buttonBox, SIGNAL(accepted()), SLOT(acceptCB())); connect(ui->buttonBox, SIGNAL(rejected()), SLOT(cancelCB())); connect(this, &vogleditor_QSettingsDialog::settingsChanged, &g_settings, &vogleditor_qsettings::update_group_active_lists); // Startup settings tab QString strSettings = g_settings.to_string(); ui->textEdit->setText(strSettings); // Group settings tab // State Render ui->checkboxStateRender->setText(g_settings.group_state_render_name()); ui->checkboxStateRender->setChecked(g_settings.group_state_render_stat()); ui->checkboxStateRender->setEnabled(g_settings.group_state_render_used()); connect(ui->checkboxStateRender, SIGNAL(stateChanged(int)), SLOT(checkboxStateRenderCB(int))); // Debug markers QVector<QCheckBox *> checkboxList; QStringList group_debug_marker_names = g_settings.group_debug_marker_names(); QVector<bool> debug_marker_stat = g_settings.group_debug_marker_stat(); QVector<bool> debug_marker_used = g_settings.group_debug_marker_used(); int debug_marker_cnt = group_debug_marker_names.size(); for (int i = 0; i < debug_marker_cnt; i++) { checkboxList << new QCheckBox(group_debug_marker_names[i], ui->groupboxDebugMarker); checkboxList[i]->setChecked(debug_marker_stat[i]); checkboxList[i]->setEnabled(debug_marker_used[i]); ui->vLayout_groupboxDebugMarker->insertWidget(i, checkboxList[i]); } for (int i = 0; i < debug_marker_cnt; i++) { connect(checkboxList[i], SIGNAL(stateChanged(int)), SLOT(checkboxCB(int))); } // Debug marker options ui->radiobuttonDebugMarkerNameOption->setText(g_settings.group_debug_marker_option_name_label()); ui->radiobuttonDebugMarkerNameOption->setChecked(g_settings.group_debug_marker_option_name_stat()); ui->radiobuttonDebugMarkerOmitOption->setText(g_settings.group_debug_marker_option_omit_label()); ui->radiobuttonDebugMarkerOmitOption->setChecked(g_settings.group_debug_marker_option_omit_stat()); setEnableDebugMarkerOptions(); connect(ui->radiobuttonDebugMarkerNameOption, SIGNAL(toggled(bool)), SLOT(radiobuttonNameCB(bool))); connect(ui->radiobuttonDebugMarkerOmitOption, SIGNAL(toggled(bool)), SLOT(radiobuttonOmitCB(bool))); // Nest options checkboxList.clear(); // Groupbox ui->groupboxNestOptions->setTitle(g_settings.groupbox_nest_options_name()); ui->groupboxNestOptions->setChecked(g_settings.groupbox_nest_options_stat()); ui->groupboxNestOptions->setEnabled(g_settings.groupbox_nest_options_used()); if (g_settings.groupbox_nest_options_stat()) { // For now, toggle State/Render groups and Nest options checkboxStateRenderCB(false); } // Checkboxes QStringList group_nest_options_names = g_settings.group_nest_options_names(); QVector<bool> nest_options_stat = g_settings.group_nest_options_stat(); QVector<bool> nest_options_used = g_settings.group_nest_options_used(); int nest_options_cnt = group_nest_options_names.size(); for (int i = 0; i < nest_options_cnt; i++) { checkboxList << new QCheckBox(group_nest_options_names[i], ui->groupboxNestOptions); checkboxList[i]->setChecked(nest_options_stat[i]); checkboxList[i]->setEnabled(nest_options_used[i]); ui->vLayout_groupboxNestOptionsScrollarea->addWidget(checkboxList[i]); } connect(ui->groupboxNestOptions, SIGNAL(toggled(bool)), // groupbox SLOT(groupboxNestOptionsCB(bool))); for (int i = 0; i < nest_options_cnt; i++) // checkboxes in groupbox { connect(checkboxList[i], SIGNAL(stateChanged(int)), SLOT(checkboxCB(int))); } // Save initial state m_bGroupInitialState = groupState(); } // constructor vogleditor_QSettingsDialog::~vogleditor_QSettingsDialog() { clearLayout(ui->verticalLayout_tabGroups); delete ui; } // destructor void vogleditor_QSettingsDialog::clearLayout(QLayout *layout) { // taken from // http://stackoverflow.com/questions/4272196/qt-remove-all-widgets-from-layout // ... didn't seem to make any difference using valgrind Memcheck... while (QLayoutItem *item = layout->takeAt(0)) { delete item->widget(); if (QLayout *childLayout = item->layout()) clearLayout(childLayout); delete item; } } // clearLayout void vogleditor_QSettingsDialog::tabCB(int page) { g_settings.set_tab_page(page); } void vogleditor_QSettingsDialog::checkboxStateRenderCB(int val) { bool bVal = bool(val); if (bVal) { ui->groupboxNestOptions->setChecked(!bVal); g_settings.set_groupbox_nest_options_stat(!bVal); } // Update g_settings.set_group_state_render_stat(bVal); updateTextTab(); } // checkboxStateRenderCB void vogleditor_QSettingsDialog::groupboxNestOptionsCB(bool bVal) { if (bVal) { ui->checkboxStateRender->setChecked(!bVal); g_settings.set_group_state_render_stat(!bVal); } // Update g_settings.set_groupbox_nest_options_stat(bVal); updateTextTab(); } // groupboxNestOptionsCB void vogleditor_QSettingsDialog::checkboxCB(int state) { g_settings.set_group_state_render_stat(ui->checkboxStateRender->isChecked()); g_settings.set_group_debug_marker_stat(checkboxValues(ui->groupboxDebugMarker)); g_settings.set_group_nest_options_stat(checkboxValues(ui->groupboxNestOptions)); setEnableDebugMarkerOptions(); updateTextTab(); } // checkboxCB void vogleditor_QSettingsDialog::setEnableDebugMarkerOptions() { // Disable options if no Debug marker groups are checked QVector<bool> bCurrentState = checkboxValues(ui->groupboxDebugMarker); bool bVal; foreach(bVal, bCurrentState) { if (bVal) break; } enableDebugMarkerOptions(bVal); } void vogleditor_QSettingsDialog::enableDebugMarkerOptions(bool bVal) { ui->radiobuttonDebugMarkerNameOption->setEnabled(bVal); ui->radiobuttonDebugMarkerOmitOption->setEnabled(bVal); // Notify g_settings g_settings.set_group_debug_marker_option_name_used(bVal); g_settings.set_group_debug_marker_option_omit_used(bVal); } void vogleditor_QSettingsDialog::radiobuttonNameCB(bool state) { g_settings.set_group_debug_marker_option_name_stat(state); updateTextTab(); } void vogleditor_QSettingsDialog::radiobuttonOmitCB(bool state) { g_settings.set_group_debug_marker_option_omit_stat(state); updateTextTab(); } void vogleditor_QSettingsDialog::updateTextTab() { //update json tab settings page QString strSettings = g_settings.to_string(); ui->textEdit->setText(strSettings); } QVector<bool> vogleditor_QSettingsDialog::checkboxValues(QObject *widget) { // Note: This function is intended to only return checkbox values of // API call names, so for the Debug marker API call list parent // radiobuttons were used for the options. QList<QCheckBox *> groupCheckBoxes = widget->findChildren<QCheckBox *>(); QVector<bool> bQVector; QList<QCheckBox *>::const_iterator iter = groupCheckBoxes.begin(); while (iter != groupCheckBoxes.end()) { bQVector << (*iter)->isChecked(); iter++; } return bQVector; } // checkboxValues() QVector<bool> vogleditor_QSettingsDialog::groupState() { QVector<bool> bCurrentState; bCurrentState << ui->checkboxStateRender->isChecked(); bCurrentState << ui->groupboxNestOptions->isChecked(); bCurrentState << checkboxValues(ui->groupboxDebugMarker); bCurrentState << checkboxValues(ui->groupboxNestOptions); bCurrentState << ui->radiobuttonDebugMarkerNameOption->isChecked(); bCurrentState << ui->radiobuttonDebugMarkerOmitOption->isChecked(); return bCurrentState; } // groupState void vogleditor_QSettingsDialog::reset() { if (groupOptionsChanged()) { // Set in same order as saved (from ::groupState()) // // TODO: QMap these, widget key to value, in constructor // so order won't matter int i = 0; ui->checkboxStateRender->setChecked(m_bGroupInitialState[i++]); ui->groupboxNestOptions->setChecked(m_bGroupInitialState[i++]); QList<QCheckBox *> checkboxes = ui->groupboxDebugMarker->findChildren<QCheckBox *>(); for (int indx = 0; indx < checkboxes.count(); indx++) { checkboxes[indx]->setChecked(m_bGroupInitialState[i++]); } checkboxes = ui->groupboxNestOptions->findChildren<QCheckBox *>(); for (int indx = 0; indx < checkboxes.count(); indx++) { checkboxes[indx]->setChecked(m_bGroupInitialState[i++]); } ui->radiobuttonDebugMarkerNameOption->setChecked(m_bGroupInitialState[i++]); ui->radiobuttonDebugMarkerOmitOption->setChecked(m_bGroupInitialState[i++]); } } // reset bool vogleditor_QSettingsDialog::groupOptionsChanged() { return m_bGroupInitialState != groupState(); } void vogleditor_QSettingsDialog::acceptCB() { save(); if (groupOptionsChanged()) { emit settingsChanged(); } } void vogleditor_QSettingsDialog::cancelCB() { reset(); } void vogleditor_QSettingsDialog::save() { g_settings.from_string(ui->textEdit->toPlainText().toStdString().c_str()); g_settings.save(); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * 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 "gflags/gflags.h" #include "opencv2/opencv.hpp" #include "cyber/common/log.h" #include "modules/perception/inference/inference.h" #include "modules/perception/inference/inference_factory.h" #include "modules/perception/inference/tensorrt/batch_stream.h" #include "modules/perception/inference/tensorrt/entropy_calibrator.h" #include "modules/perception/inference/tensorrt/rt_net.h" #include "modules/perception/inference/utils/util.h" DEFINE_bool(int8, false, "use int8"); DEFINE_string(names_file, "./lane_parser/blob_names.txt", "path of output blob"); DEFINE_string(test_list, "image_list.txt", "path of image list"); DEFINE_string(image_root, "./images/", "path of image dir"); DEFINE_string(image_ext, ".jpg", "path of image ext"); DEFINE_string(res_dir, "./result.dat", "path of result"); int main(int argc, char **argv) { google::ParseCommandLineFlags(&argc, &argv, true); std::vector<float> output_data_vec1; std::vector<cv::Scalar> color_table; color_table.push_back(cv::Scalar(0, 97, 255)); // for other >0 mask values color_table.push_back(cv::Scalar(0, 0, 255)); // for mask value = 1 color_table.push_back(cv::Scalar(0, 255, 0)); // for mask value = 2 color_table.push_back(cv::Scalar(255, 0, 0)); // for mask value = 3 color_table.push_back(cv::Scalar(240, 32, 160)); // for mask value = 4 const std::string proto_file = "./lane_parser/caffe.pt"; const std::string weight_file = "./lane_parser/caffe.caffemodel"; const std::string model_root = "./lane_parser/"; cudaDeviceProp prop; cudaGetDeviceProperties(&prop, 0); AINFO << prop.name; apollo::perception::inference::Inference *rt_net; const std::string input_blob_name = "data"; std::vector<std::string> inputs{"data"}; std::vector<std::string> outputs{"loc_pred", "obj_pred", "cls_pred", "ori_pred", "dim_pred", "lof_pred", "lor_pred", "conv4_3"}; apollo::perception::inference::load_data<std::string>(FLAGS_names_file, &outputs); for (auto name : outputs) { ADEBUG << name; } if (FLAGS_int8) { apollo::perception::inference::BatchStream stream(2, 50, "./batches/"); nvinfer1::Int8EntropyCalibrator calibrator(stream, 0, true, "./"); std::cout << "int8" << std::endl; rt_net = apollo::perception::inference::CreateInferenceByName( "RTNetInt8", proto_file, weight_file, outputs, inputs, model_root); } else { std::cout << "fp32" << std::endl; rt_net = apollo::perception::inference::CreateInferenceByName( "RTNet", proto_file, weight_file, outputs, inputs); } const int height = 608; const int width = 1024; const int offset_y = 0; std::vector<int> shape = {1, 3, height, width}; std::map<std::string, std::vector<int>> shape_map{{input_blob_name, shape}}; rt_net->Init(shape_map); auto input_blob = rt_net->get_blob("data"); std::vector<std::string> image_lists; apollo::perception::inference::load_data<std::string>(FLAGS_test_list, &image_lists); std::vector<float> output_data_vec; for (auto image_file : image_lists) { cv::Mat img = cv::imread(FLAGS_image_root + image_file + FLAGS_image_ext, CV_8UC1); ADEBUG << img.channels(); cv::Rect roi(0, offset_y, img.cols, img.rows - offset_y); cv::Mat img_roi = img(roi); img_roi.copyTo(img); cv::resize(img, img, cv::Size(width, height)); const int count = 1 * width * height; std::vector<float> input(count); for (int i = 0; i < count; i++) { input[i] = static_cast<float>(img.data[i] - 128) * 0.0078125f; } cudaMemcpy(input_blob->mutable_gpu_data(), &input[0], count * sizeof(float), cudaMemcpyHostToDevice); cudaDeviceSynchronize(); rt_net->Infer(); cudaDeviceSynchronize(); for (auto output_name : outputs) { auto blob = rt_net->get_blob(output_name); std::vector<float> tmp_vec(blob->cpu_data(), blob->cpu_data() + blob->count()); if (output_name == "output") { const float *output_data = blob->cpu_data(); for (int h = 0; h < img.rows; h++) { for (int w = 0; w < img.cols; w++) { int offset = blob->offset(0, 0, h, w); if (output_data[offset] > 0) { img.at<cv::Vec3b>(h, w)[0] = static_cast<unsigned char>( img.at<cv::Vec3b>(w, h)[0] * 0.7 + color_table[0][0] * 0.3); } } } cv::imwrite("res.jpg", img); } output_data_vec.insert(output_data_vec.end(), tmp_vec.begin(), tmp_vec.end()); } } apollo::perception::inference::write_result(FLAGS_res_dir, output_data_vec); delete rt_net; return 0; } <commit_msg>Perception: consolidate lane_sample<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * 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 "gflags/gflags.h" #include "opencv2/opencv.hpp" #include "cyber/common/log.h" #include "modules/perception/inference/inference.h" #include "modules/perception/inference/inference_factory.h" #include "modules/perception/inference/tensorrt/batch_stream.h" #include "modules/perception/inference/tensorrt/entropy_calibrator.h" #include "modules/perception/inference/tensorrt/rt_net.h" #include "modules/perception/inference/utils/util.h" DEFINE_bool(int8, false, "use int8"); DEFINE_string(names_file, "./lane_parser/blob_names.txt", "path of output blob"); DEFINE_string(test_list, "image_list.txt", "path of image list"); DEFINE_string(image_root, "./images/", "path of image dir"); DEFINE_string(image_ext, ".jpg", "path of image ext"); DEFINE_string(res_dir, "./result.dat", "path of result"); int main(int argc, char **argv) { google::ParseCommandLineFlags(&argc, &argv, true); std::vector<cv::Scalar> color_table; color_table.push_back(cv::Scalar(0, 97, 255)); // for other >0 mask values color_table.push_back(cv::Scalar(0, 0, 255)); // for mask value = 1 color_table.push_back(cv::Scalar(0, 255, 0)); // for mask value = 2 color_table.push_back(cv::Scalar(255, 0, 0)); // for mask value = 3 color_table.push_back(cv::Scalar(240, 32, 160)); // for mask value = 4 const std::string proto_file = "./lane_parser/caffe.pt"; const std::string weight_file = "./lane_parser/caffe.caffemodel"; const std::string model_root = "./lane_parser/"; cudaDeviceProp prop; cudaGetDeviceProperties(&prop, 0); AINFO << prop.name; apollo::perception::inference::Inference *rt_net; const std::string input_blob_name = "data"; std::vector<std::string> inputs{"data"}; std::vector<std::string> outputs{"loc_pred", "obj_pred", "cls_pred", "ori_pred", "dim_pred", "lof_pred", "lor_pred", "conv4_3"}; apollo::perception::inference::load_data<std::string>(FLAGS_names_file, &outputs); for (auto &name : outputs) { ADEBUG << name; } if (FLAGS_int8) { apollo::perception::inference::BatchStream stream(2, 50, "./batches/"); nvinfer1::Int8EntropyCalibrator calibrator(stream, 0, true, "./"); std::cout << "int8" << std::endl; rt_net = apollo::perception::inference::CreateInferenceByName( "RTNetInt8", proto_file, weight_file, outputs, inputs, model_root); } else { std::cout << "fp32" << std::endl; rt_net = apollo::perception::inference::CreateInferenceByName( "RTNet", proto_file, weight_file, outputs, inputs); } const int height = 608; const int width = 1024; const int offset_y = 0; std::vector<int> shape = {1, 3, height, width}; std::map<std::string, std::vector<int>> shape_map{{input_blob_name, shape}}; rt_net->Init(shape_map); auto input_blob = rt_net->get_blob("data"); std::vector<std::string> image_lists; apollo::perception::inference::load_data<std::string>(FLAGS_test_list, &image_lists); std::vector<float> output_data_vec; const int count = width * height; for (auto &image_file : image_lists) { cv::Mat img = cv::imread(FLAGS_image_root + image_file + FLAGS_image_ext, CV_8UC1); ADEBUG << img.channels(); cv::Rect roi(0, offset_y, img.cols, img.rows - offset_y); cv::Mat img_roi = img(roi); img_roi.copyTo(img); cv::resize(img, img, cv::Size(width, height)); std::vector<float> input(count); for (int i = 0; i < count; ++i) { input[i] = static_cast<float>(img.data[i] - 128) * 0.0078125f; } cudaMemcpy(input_blob->mutable_gpu_data(), &input[0], count * sizeof(float), cudaMemcpyHostToDevice); cudaDeviceSynchronize(); rt_net->Infer(); cudaDeviceSynchronize(); for (auto &output_name : outputs) { auto blob = rt_net->get_blob(output_name); std::vector<float> tmp_vec(blob->cpu_data(), blob->cpu_data() + blob->count()); if (output_name == "output") { const float *output_data = blob->cpu_data(); for (int h = 0; h < img.rows; h++) { for (int w = 0; w < img.cols; w++) { int offset = blob->offset(0, 0, h, w); if (output_data[offset] > 0) { img.at<cv::Vec3b>(h, w)[0] = static_cast<unsigned char>( img.at<cv::Vec3b>(w, h)[0] * 0.7 + color_table[0][0] * 0.3); } } } cv::imwrite("res.jpg", img); } output_data_vec.insert(output_data_vec.end(), tmp_vec.begin(), tmp_vec.end()); } } apollo::perception::inference::write_result(FLAGS_res_dir, output_data_vec); delete rt_net; return 0; } <|endoftext|>
<commit_before>#include "dglcontroller.h" #include "dglgui.h" DGLResourceListener::DGLResourceListener(uint listenerId, uint objectId, DGLResource::ObjectType type, DGLResourceManager* manager): m_ListenerId(listenerId), m_ObjectId(objectId), m_ObjectType(type), m_Manager(manager), m_RefCount(0) { m_Manager->registerListener(this); } DGLResourceListener::~DGLResourceListener() { m_Manager->unregisterListener(this); } DGLResourceManager::DGLResourceManager(DglController* controller):m_MaxListenerId(0), m_Controller(controller) {} void DGLResourceManager::emitQueries() { dglnet::QueryResourceMessage queries; for (std::multimap<uint, DGLResourceListener*>::iterator i = m_Listeners.begin(); i != m_Listeners.end(); i++) { dglnet::QueryResourceMessage::ResourceQuery query; query.m_ListenerId = i->first; query.m_ObjectId = i->second->m_ObjectId; query.m_Type = i->second->m_ObjectType; queries.m_ResourceQueries.push_back(query); } if (queries.m_ResourceQueries.size()) m_Controller->sendMessage(&queries); } void DGLResourceManager::handleResourceMessage(const dglnet::ResourceMessage& msg) { int idx = 0; bool end = false; //this strange method of iteration is to allow modification of m_Listeners for (int idx = 0; !end; idx++) { std::pair<std::multimap<uint, DGLResourceListener*>::iterator, std::multimap<uint, DGLResourceListener*>::iterator> range = m_Listeners.equal_range(msg.m_ListenerId); std::multimap<uint, DGLResourceListener*>::iterator i = range.first; for (int j = 0; j < idx && i != range.second ; j++) { i++; } if (i == range.second) { end = true; } else { std::string errorMessage; if (msg.isOk(errorMessage)) { i->second->update(*msg.m_Resource); } else { i->second->error(errorMessage); } } } } DGLResourceListener* DGLResourceManager::createListener(uint objectId, DGLResource::ObjectType type) { for (std::multimap<uint, DGLResourceListener*>::iterator i = m_Listeners.begin(); i != m_Listeners.end(); i++) { if (i->second->m_ObjectId == objectId && i->second->m_ObjectType == type) { return new DGLResourceListener(i->second->m_ListenerId, objectId, type, this); } } return new DGLResourceListener(m_MaxListenerId++, objectId, type, this); } void DGLResourceManager::registerListener(DGLResourceListener* listener) { m_Listeners.insert(std::pair<uint, DGLResourceListener*>(listener->m_ListenerId, listener)); dglnet::QueryResourceMessage queries; dglnet::QueryResourceMessage::ResourceQuery query; query.m_ListenerId = listener->m_ListenerId; query.m_ObjectId = listener->m_ObjectId; query.m_Type = listener->m_ObjectType; queries.m_ResourceQueries.push_back(query); m_Controller->sendMessage(&queries); } void DGLResourceManager::unregisterListener(DGLResourceListener* listener) { std::pair<std::multimap<uint, DGLResourceListener*>::iterator, std::multimap<uint, DGLResourceListener*>::iterator> range = m_Listeners.equal_range(listener->m_ListenerId); for (std::multimap<uint, DGLResourceListener*>::iterator i = range.first; i != range.second; i++) { if (i->second == listener) { m_Listeners.erase(i); break; } } } void DGLViewRouter::show(uint name, DGLResource::ObjectType type, uint target) { switch (type) { case DGLResource::ObjectTypeBuffer: emit showBuffer(name); break; case DGLResource::ObjectTypeFramebuffer: emit showFramebuffer(name); break; case DGLResource::ObjectTypeFBO: emit showFBO(name); break; case DGLResource::ObjectTypeTexture: emit showTexture(name); break; case DGLResource::ObjectTypeShader: assert(target); emit showShader(name, target); break; case DGLResource::ObjectTypeProgram: emit showProgram(name); break; } } DglController::DglController():m_Disconnected(true), m_Connected(false), m_ConfiguredAndBkpointsSet(false), m_BreakPointController(this), m_ResourceManager(this) { m_Timer.setInterval(10); CONNASSERT(connect(&m_Timer, SIGNAL(timeout()), this, SLOT(poll()))); } void DglController::connectServer(const std::string& host, const std::string& port) { if (m_DglClient) { disconnectServer(); } //we are not disconnected, but not yet connected - so we do not set m_Connected m_Disconnected = false; m_DglClient = boost::make_shared<dglnet::Client>(this, this); m_DglClient->connectServer(host, port); m_Timer.start(); } void DglController::onSocket() { //m_Timer.stop(); m_NotifierRead = boost::make_shared<QSocketNotifier>(m_DglClient->getSocketFD(), QSocketNotifier::Read); m_NotifierWrite = boost::make_shared<QSocketNotifier>(m_DglClient->getSocketFD(), QSocketNotifier::Write); CONNASSERT(connect(&*m_NotifierRead, SIGNAL(activated(int)), this, SLOT(poll()))); CONNASSERT(connect(&*m_NotifierWrite, SIGNAL(activated(int)), this, SLOT(poll()))); } void DglController::disconnectServer() { if (m_DglClient) { m_DglClient->abort(); m_DglClient.reset(); m_ConfiguredAndBkpointsSet = false; setConnected(false); setDisconnected(true); debugeeInfo(""); } m_Connected = false; m_NotifierRead.reset(); m_NotifierWrite.reset(); } bool DglController::isConnected() { return m_Connected; } void DglController::poll() { if (m_DglClient) { m_DglClient->poll(); if (m_Disconnected) { //one of asio handlers requested disconnection disconnectServer(); error(tr("Connection error"), m_DglClientDeadInfo.c_str()); } } } void DglController::debugContinue() { setBreaked(false); setRunning(true); assert(isConnected()); dglnet::ContinueBreakMessage message(false); m_DglClient->sendMessage(&message); } void DglController::debugInterrupt() { assert(isConnected()); dglnet::ContinueBreakMessage message(true); m_DglClient->sendMessage(&message); } void DglController::debugStep() { setBreaked(false); setRunning(true); assert(isConnected()); dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_CALL); m_DglClient->sendMessage(&message); } void DglController::debugStepDrawCall() { setBreaked(false); setRunning(true); assert(isConnected()); dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_DRAW_CALL); m_DglClient->sendMessage(&message); } void DglController::debugStepFrame() { setBreaked(false); setRunning(true); assert(isConnected()); dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_FRAME); m_DglClient->sendMessage(&message); } void DglController::onSetStatus(std::string str) { newStatus(str.c_str()); } void DglController::queryCallTrace(uint startOffset, uint endOffset) { dglnet::QueryCallTraceMessage message(startOffset, endOffset); m_DglClient->sendMessage(&message); } void DglController::doHandle(const dglnet::HelloMessage & msg) { //we are connected now m_Connected = true; debugeeInfo(msg.m_ProcessName); setConnected(true); setDisconnected(false); } void DglController::doHandle(const dglnet::BreakedCallMessage & msg) { if (!m_ConfiguredAndBkpointsSet) { //this is the first time debugee was stopped, before any execution //we must upload some configuration to it m_ConfiguredAndBkpointsSet = true; sendConfig(); getBreakPoints()->sendCurrent(); } setBreaked(true); setRunning(false); breaked(msg.m_entryp, msg.m_TraceSize); breakedWithStateReports(msg.m_CurrentCtx, msg.m_CtxReports); m_ResourceManager.emitQueries(); } void DglController::doHandle(const dglnet::CallTraceMessage& msg) { gotCallTraceChunkChunk(msg.m_StartOffset, msg.m_Trace); } void DglController::doHandle(const dglnet::ResourceMessage& msg) { m_ResourceManager.handleResourceMessage(msg); } void DglController::doHandleDisconnect(const std::string& msg) { m_DglClientDeadInfo = msg; m_Disconnected = true; m_Connected = !m_Disconnected; } void DglController::sendMessage(dglnet::Message* msg) { assert(isConnected()); m_DglClient->sendMessage(msg); } DGLBreakPointController* DglController::getBreakPoints() { return &m_BreakPointController; } DGLResourceManager* DglController::getResourceManager() { return &m_ResourceManager; } DGLViewRouter* DglController::getViewRouter() { return &m_ViewRouter; } void DglController::configure(const DGLConfiguration& config) { m_Config = config; sendConfig(); } void DglController::sendConfig() { if (isConnected()) { dglnet::ConfigurationMessage message(m_Config); m_DglClient->sendMessage(&message); } } const DGLConfiguration& DglController::getConfig() { return m_Config; } DGLBreakPointController::DGLBreakPointController(DglController* controller):m_Controller(controller) {} std::set<Entrypoint> DGLBreakPointController::getCurrent() { return m_Current; } void DGLBreakPointController::setCurrent(const std::set<Entrypoint>& newCurrent) { if (m_Current != newCurrent) { m_Current = newCurrent; sendCurrent(); } } void DGLBreakPointController::sendCurrent() { if (m_Controller->isConnected()) { dglnet::SetBreakPointsMessage msg(m_Current); m_Controller->sendMessage(&msg); } }<commit_msg>More status-es in qstatusbar<commit_after>#include "dglcontroller.h" #include "dglgui.h" DGLResourceListener::DGLResourceListener(uint listenerId, uint objectId, DGLResource::ObjectType type, DGLResourceManager* manager): m_ListenerId(listenerId), m_ObjectId(objectId), m_ObjectType(type), m_Manager(manager), m_RefCount(0) { m_Manager->registerListener(this); } DGLResourceListener::~DGLResourceListener() { m_Manager->unregisterListener(this); } DGLResourceManager::DGLResourceManager(DglController* controller):m_MaxListenerId(0), m_Controller(controller) {} void DGLResourceManager::emitQueries() { dglnet::QueryResourceMessage queries; for (std::multimap<uint, DGLResourceListener*>::iterator i = m_Listeners.begin(); i != m_Listeners.end(); i++) { dglnet::QueryResourceMessage::ResourceQuery query; query.m_ListenerId = i->first; query.m_ObjectId = i->second->m_ObjectId; query.m_Type = i->second->m_ObjectType; queries.m_ResourceQueries.push_back(query); } if (queries.m_ResourceQueries.size()) m_Controller->sendMessage(&queries); } void DGLResourceManager::handleResourceMessage(const dglnet::ResourceMessage& msg) { int idx = 0; bool end = false; //this strange method of iteration is to allow modification of m_Listeners for (int idx = 0; !end; idx++) { std::pair<std::multimap<uint, DGLResourceListener*>::iterator, std::multimap<uint, DGLResourceListener*>::iterator> range = m_Listeners.equal_range(msg.m_ListenerId); std::multimap<uint, DGLResourceListener*>::iterator i = range.first; for (int j = 0; j < idx && i != range.second ; j++) { i++; } if (i == range.second) { end = true; } else { std::string errorMessage; if (msg.isOk(errorMessage)) { i->second->update(*msg.m_Resource); } else { i->second->error(errorMessage); } } } } DGLResourceListener* DGLResourceManager::createListener(uint objectId, DGLResource::ObjectType type) { for (std::multimap<uint, DGLResourceListener*>::iterator i = m_Listeners.begin(); i != m_Listeners.end(); i++) { if (i->second->m_ObjectId == objectId && i->second->m_ObjectType == type) { return new DGLResourceListener(i->second->m_ListenerId, objectId, type, this); } } return new DGLResourceListener(m_MaxListenerId++, objectId, type, this); } void DGLResourceManager::registerListener(DGLResourceListener* listener) { m_Listeners.insert(std::pair<uint, DGLResourceListener*>(listener->m_ListenerId, listener)); dglnet::QueryResourceMessage queries; dglnet::QueryResourceMessage::ResourceQuery query; query.m_ListenerId = listener->m_ListenerId; query.m_ObjectId = listener->m_ObjectId; query.m_Type = listener->m_ObjectType; queries.m_ResourceQueries.push_back(query); m_Controller->sendMessage(&queries); } void DGLResourceManager::unregisterListener(DGLResourceListener* listener) { std::pair<std::multimap<uint, DGLResourceListener*>::iterator, std::multimap<uint, DGLResourceListener*>::iterator> range = m_Listeners.equal_range(listener->m_ListenerId); for (std::multimap<uint, DGLResourceListener*>::iterator i = range.first; i != range.second; i++) { if (i->second == listener) { m_Listeners.erase(i); break; } } } void DGLViewRouter::show(uint name, DGLResource::ObjectType type, uint target) { switch (type) { case DGLResource::ObjectTypeBuffer: emit showBuffer(name); break; case DGLResource::ObjectTypeFramebuffer: emit showFramebuffer(name); break; case DGLResource::ObjectTypeFBO: emit showFBO(name); break; case DGLResource::ObjectTypeTexture: emit showTexture(name); break; case DGLResource::ObjectTypeShader: assert(target); emit showShader(name, target); break; case DGLResource::ObjectTypeProgram: emit showProgram(name); break; } } DglController::DglController():m_Disconnected(true), m_Connected(false), m_ConfiguredAndBkpointsSet(false), m_BreakPointController(this), m_ResourceManager(this) { m_Timer.setInterval(10); CONNASSERT(connect(&m_Timer, SIGNAL(timeout()), this, SLOT(poll()))); } void DglController::connectServer(const std::string& host, const std::string& port) { if (m_DglClient) { disconnectServer(); } //we are not disconnected, but not yet connected - so we do not set m_Connected m_Disconnected = false; m_DglClient = boost::make_shared<dglnet::Client>(this, this); m_DglClient->connectServer(host, port); m_Timer.start(); } void DglController::onSocket() { //m_Timer.stop(); m_NotifierRead = boost::make_shared<QSocketNotifier>(m_DglClient->getSocketFD(), QSocketNotifier::Read); m_NotifierWrite = boost::make_shared<QSocketNotifier>(m_DglClient->getSocketFD(), QSocketNotifier::Write); CONNASSERT(connect(&*m_NotifierRead, SIGNAL(activated(int)), this, SLOT(poll()))); CONNASSERT(connect(&*m_NotifierWrite, SIGNAL(activated(int)), this, SLOT(poll()))); } void DglController::disconnectServer() { if (m_DglClient) { m_DglClient->abort(); m_DglClient.reset(); m_ConfiguredAndBkpointsSet = false; setConnected(false); setDisconnected(true); debugeeInfo(""); } m_Connected = false; m_NotifierRead.reset(); m_NotifierWrite.reset(); newStatus("Disconnected."); } bool DglController::isConnected() { return m_Connected; } void DglController::poll() { if (m_DglClient) { m_DglClient->poll(); if (m_Disconnected) { //one of asio handlers requested disconnection disconnectServer(); error(tr("Connection error"), m_DglClientDeadInfo.c_str()); } } } void DglController::debugContinue() { setBreaked(false); setRunning(true); assert(isConnected()); dglnet::ContinueBreakMessage message(false); m_DglClient->sendMessage(&message); } void DglController::debugInterrupt() { assert(isConnected()); dglnet::ContinueBreakMessage message(true); m_DglClient->sendMessage(&message); newStatus("Interrupting..."); } void DglController::debugStep() { setBreaked(false); setRunning(true); assert(isConnected()); dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_CALL); m_DglClient->sendMessage(&message); newStatus("Running..."); } void DglController::debugStepDrawCall() { setBreaked(false); setRunning(true); assert(isConnected()); dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_DRAW_CALL); m_DglClient->sendMessage(&message); newStatus("Running..."); } void DglController::debugStepFrame() { setBreaked(false); setRunning(true); assert(isConnected()); dglnet::ContinueBreakMessage message(dglnet::ContinueBreakMessage::STEP_FRAME); m_DglClient->sendMessage(&message); newStatus("Running..."); } void DglController::onSetStatus(std::string str) { newStatus(str.c_str()); } void DglController::queryCallTrace(uint startOffset, uint endOffset) { dglnet::QueryCallTraceMessage message(startOffset, endOffset); m_DglClient->sendMessage(&message); } void DglController::doHandle(const dglnet::HelloMessage & msg) { //we are connected now m_Connected = true; debugeeInfo(msg.m_ProcessName); setConnected(true); setDisconnected(false); } void DglController::doHandle(const dglnet::BreakedCallMessage & msg) { if (!m_ConfiguredAndBkpointsSet) { //this is the first time debugee was stopped, before any execution //we must upload some configuration to it m_ConfiguredAndBkpointsSet = true; sendConfig(); getBreakPoints()->sendCurrent(); } setBreaked(true); setRunning(false); breaked(msg.m_entryp, msg.m_TraceSize); breakedWithStateReports(msg.m_CurrentCtx, msg.m_CtxReports); m_ResourceManager.emitQueries(); newStatus("Breaked execution."); } void DglController::doHandle(const dglnet::CallTraceMessage& msg) { gotCallTraceChunkChunk(msg.m_StartOffset, msg.m_Trace); } void DglController::doHandle(const dglnet::ResourceMessage& msg) { m_ResourceManager.handleResourceMessage(msg); } void DglController::doHandleDisconnect(const std::string& msg) { m_DglClientDeadInfo = msg; m_Disconnected = true; m_Connected = !m_Disconnected; } void DglController::sendMessage(dglnet::Message* msg) { assert(isConnected()); m_DglClient->sendMessage(msg); } DGLBreakPointController* DglController::getBreakPoints() { return &m_BreakPointController; } DGLResourceManager* DglController::getResourceManager() { return &m_ResourceManager; } DGLViewRouter* DglController::getViewRouter() { return &m_ViewRouter; } void DglController::configure(const DGLConfiguration& config) { m_Config = config; sendConfig(); } void DglController::sendConfig() { if (isConnected()) { dglnet::ConfigurationMessage message(m_Config); m_DglClient->sendMessage(&message); } } const DGLConfiguration& DglController::getConfig() { return m_Config; } DGLBreakPointController::DGLBreakPointController(DglController* controller):m_Controller(controller) {} std::set<Entrypoint> DGLBreakPointController::getCurrent() { return m_Current; } void DGLBreakPointController::setCurrent(const std::set<Entrypoint>& newCurrent) { if (m_Current != newCurrent) { m_Current = newCurrent; sendCurrent(); } } void DGLBreakPointController::sendCurrent() { if (m_Controller->isConnected()) { dglnet::SetBreakPointsMessage msg(m_Current); m_Controller->sendMessage(&msg); } }<|endoftext|>
<commit_before>/* * Part of tivars_lib_cpp * (C) 2015-2018 Adrien "Adriweb" Bertrand * https://github.com/adriweb/tivars_lib_cpp * License: MIT */ #include "TypeHandlers.h" #include "../utils.h" #include <unordered_map> #include <iostream> #include <iterator> #include <regex> #include <fstream> namespace tivars { namespace TH_Tokenized { std::unordered_map<uint, std::vector<std::string>> tokens_BytesToName; std::unordered_map<std::string, uint> tokens_NameToBytes; uchar lengthOfLongestTokenName; std::vector<uchar> firstByteOfTwoByteTokens; const uint16_t squishedASMTokens[] = { 0xBB6D, 0xEF69, 0xEF7B }; // 83+/84+, 84+CSE, CE } /* TODO: handle TI-Innovator Send( exception for in-strings tokenization (=> not shortest tokens) */ data_t TH_Tokenized::makeDataFromString(const std::string& str, const options_t& options) { (void)options; data_t data; // two bytes reserved for the size. Filled later data.push_back(0); data.push_back(0); const uchar maxTokSearchLen = std::min((uchar)str.length(), lengthOfLongestTokenName); bool isWithinString = false; for (uint strCursorPos = 0; strCursorPos < str.length(); strCursorPos++) { const std::string currChar = str.substr(strCursorPos, 1); if (currChar == "\"") { isWithinString = !isWithinString; } else if (currChar == "\n" || currChar == "→") { isWithinString = false; } /* isWithinString => minimum token length, otherwise maximal munch */ for (uint currentLength = isWithinString ? 1 : maxTokSearchLen; isWithinString ? (currentLength <= maxTokSearchLen) : (currentLength > 0); currentLength += (isWithinString ? 1 : -1)) { std::string currentSubString = str.substr(strCursorPos, currentLength); if (tokens_NameToBytes.count(currentSubString)) { uint tokenValue = tokens_NameToBytes[currentSubString]; if (tokenValue > 0xFF) { data.push_back((uchar)(tokenValue >> 8)); } data.push_back((uchar)(tokenValue & 0xFF)); strCursorPos += currentLength - 1; break; } } } uint actualDataLen = (uint) (data.size() - 2); data[0] = (uchar)(actualDataLen & 0xFF); data[1] = (uchar)((actualDataLen >> 8) & 0xFF); return data; } std::string TH_Tokenized::makeStringFromData(const data_t& data, const options_t& options) { if (data.size() < 2) { throw std::invalid_argument("Invalid data array. Needs to contain at least 2 bytes (size fields)"); } uint langIdx = (uint)((has_option(options, "lang") && options.at("lang") == LANG_FR) ? LANG_FR : LANG_EN); const int howManyBytes = (data[0] & 0xFF) + ((data[1] & 0xFF) << 8); if (howManyBytes != (int)data.size() - 2) { std::cerr << "[Warning] Byte count (" << (data.size() - 2) << ") and size field (" << howManyBytes << ") mismatch!"; } if (howManyBytes >= 2) { const uint16_t twoFirstBytes = (uint16_t) ((data[3] & 0xFF) + ((data[2] & 0xFF) << 8)); if (std::find(std::begin(squishedASMTokens), std::end(squishedASMTokens), twoFirstBytes) != std::end(squishedASMTokens)) { return "[Error] This is a squished ASM program - cannnot preview it!"; } } uint errCount = 0; std::string str; const size_t dataSize = data.size(); for (uint i = 2; i < (uint)howManyBytes + 2; i++) { uint currentToken = data[i]; uint nextToken = (i < dataSize-1) ? data[i+1] : (uint)-1; uint bytesKey = currentToken; if (is_in_vector(firstByteOfTwoByteTokens, (uchar)currentToken)) { if (nextToken == (uint)-1) { std::cerr << "[Warning] Encountered an unfinished two-byte token! Setting the second byte to 0x00"; nextToken = 0x00; } bytesKey = nextToken + (currentToken << 8); i++; } if (tokens_BytesToName.find(bytesKey) != tokens_BytesToName.end()) { str += tokens_BytesToName[bytesKey][langIdx]; } else { str += " [???] "; errCount++; } } if (errCount > 0) { std::cerr << "[Warning] " << errCount << " token(s) could not be detokenized (' [???] ' was used)!"; } if (has_option(options, "prettify") && options.at("prettify") == 1) { str = std::regex_replace(str, std::regex(R"(\[?\|?([a-z]+)\]?)"), "$1"); } if (has_option(options, "reindent") && options.at("reindent") == 1) { str = reindentCodeString(str); } return str; } std::string TH_Tokenized::reindentCodeString(const std::string& str_orig, const options_t& options) { int lang; if (has_option(options, "lang")) { lang = options.at("lang"); } else { lang = (str_orig.size() > 1 && str_orig[0] == '.' && (str_orig[1] == '.' || ::isalpha(str_orig[1]))) ? PRGMLANG_AXE : PRGMLANG_BASIC; } std::string str(str_orig); str = std::regex_replace(str, std::regex("([^\\s])(Del|Eff)Var "), "$1\n$2Var "); std::vector<std::string> lines_tmp = explode(str, '\n'); // Inplace-replace the appropriate ":" by new-line chars (ie, by inserting the split string in the lines_tmp array) for (uint16_t idx = 0; idx < (uint16_t)lines_tmp.size(); idx++) { const auto line = lines_tmp[idx]; bool isWithinString = false; for (uint16_t strIdx = 0; strIdx < (uint16_t)line.size(); strIdx++) { const auto currChar = line.substr(strIdx, 1); if (currChar == ":" && !isWithinString) { lines_tmp[idx] = line.substr(0, strIdx); // replace "old" line by lhs lines_tmp.insert(lines_tmp.begin() + idx + 1, line.substr(strIdx + 1)); // inserting rhs break; } else if (currChar == "\"") { isWithinString = !isWithinString; } else if (currChar == "\n" || currChar == "→") { isWithinString = false; } } } std::vector<std::pair<uint, std::string>> lines(lines_tmp.size()); // indent, text for (const auto& line : lines_tmp) { lines.emplace_back(0, line); } std::vector<std::string> increaseIndentAfter = { "If", "For", "While", "Repeat" }; std::vector<std::string> decreaseIndentOfToken = { "Then", "Else", "End", "ElseIf", "EndIf", "End!If" }; std::vector<std::string> closingTokens = { "End", "EndIf", "End!If" }; uint nextIndent = 0; std::string oldFirstCommand, firstCommand; for (auto& line : lines) { oldFirstCommand = firstCommand; std::string trimmedLine = trim(line.second); if (trimmedLine.length() > 0) { char* trimmedLine_c = (char*) trimmedLine.c_str(); firstCommand = strtok(trimmedLine_c, " "); firstCommand = trim(firstCommand); trimmedLine = std::string(trimmedLine_c); trimmedLine_c = (char*) trimmedLine.c_str(); if (firstCommand == trimmedLine) { firstCommand = strtok(trimmedLine_c, "("); firstCommand = trim(firstCommand); } } else { firstCommand = ""; } line.first = nextIndent; if (is_in_vector(increaseIndentAfter, firstCommand)) { nextIndent++; } if (line.first > 0 && is_in_vector(decreaseIndentOfToken, firstCommand)) { line.first--; } if (nextIndent > 0 && (is_in_vector(closingTokens, firstCommand) || (oldFirstCommand == "If" && firstCommand != "Then" && lang != PRGMLANG_AXE))) { nextIndent--; } } str = ""; for (const auto& line : lines) { str += str_repeat(" ", line.first * 3) + line.second + '\n'; } return ltrim(rtrim(str, "\t\n\r\f\v")); } void TH_Tokenized::initTokens() { std::ifstream t("programs_tokens.csv"); std::string csvFileStr((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); if (csvFileStr.length() > 0) { std::vector<std::vector<std::string>> lines; ParseCSV(csvFileStr, lines); for (const auto& tokenInfo : lines) { uint bytes; if (tokenInfo[6] == "2") // number of bytes for the token { if (!is_in_vector(firstByteOfTwoByteTokens, hexdec(tokenInfo[7]))) { firstByteOfTwoByteTokens.push_back(hexdec(tokenInfo[7])); } bytes = hexdec(tokenInfo[8]) + (hexdec(tokenInfo[7]) << 8); } else { bytes = hexdec(tokenInfo[7]); } tokens_BytesToName[bytes] = { tokenInfo[4], tokenInfo[5] }; // EN, FR tokens_NameToBytes[tokenInfo[4]] = bytes; // EN tokens_NameToBytes[tokenInfo[5]] = bytes; // FR uchar maxLenName = (uchar) std::max(tokenInfo[4].length(), tokenInfo[5].length()); if (maxLenName > lengthOfLongestTokenName) { lengthOfLongestTokenName = maxLenName; } } } else { throw std::runtime_error("Could not open the tokens csv file"); } } } <commit_msg>Detect ICE header, handle ICE-style If statements<commit_after>/* * Part of tivars_lib_cpp * (C) 2015-2018 Adrien "Adriweb" Bertrand * https://github.com/adriweb/tivars_lib_cpp * License: MIT */ #include "TypeHandlers.h" #include "../utils.h" #include <unordered_map> #include <iostream> #include <iterator> #include <regex> #include <fstream> namespace tivars { namespace TH_Tokenized { std::unordered_map<uint, std::vector<std::string>> tokens_BytesToName; std::unordered_map<std::string, uint> tokens_NameToBytes; uchar lengthOfLongestTokenName; std::vector<uchar> firstByteOfTwoByteTokens; const uint16_t squishedASMTokens[] = { 0xBB6D, 0xEF69, 0xEF7B }; // 83+/84+, 84+CSE, CE } /* TODO: handle TI-Innovator Send( exception for in-strings tokenization (=> not shortest tokens) */ data_t TH_Tokenized::makeDataFromString(const std::string& str, const options_t& options) { (void)options; data_t data; // two bytes reserved for the size. Filled later data.push_back(0); data.push_back(0); const uchar maxTokSearchLen = std::min((uchar)str.length(), lengthOfLongestTokenName); bool isWithinString = false; for (uint strCursorPos = 0; strCursorPos < str.length(); strCursorPos++) { const std::string currChar = str.substr(strCursorPos, 1); if (currChar == "\"") { isWithinString = !isWithinString; } else if (currChar == "\n" || currChar == "→") { isWithinString = false; } /* isWithinString => minimum token length, otherwise maximal munch */ for (uint currentLength = isWithinString ? 1 : maxTokSearchLen; isWithinString ? (currentLength <= maxTokSearchLen) : (currentLength > 0); currentLength += (isWithinString ? 1 : -1)) { std::string currentSubString = str.substr(strCursorPos, currentLength); if (tokens_NameToBytes.count(currentSubString)) { uint tokenValue = tokens_NameToBytes[currentSubString]; if (tokenValue > 0xFF) { data.push_back((uchar)(tokenValue >> 8)); } data.push_back((uchar)(tokenValue & 0xFF)); strCursorPos += currentLength - 1; break; } } } uint actualDataLen = (uint) (data.size() - 2); data[0] = (uchar)(actualDataLen & 0xFF); data[1] = (uchar)((actualDataLen >> 8) & 0xFF); return data; } std::string TH_Tokenized::makeStringFromData(const data_t& data, const options_t& options) { if (data.size() < 2) { throw std::invalid_argument("Invalid data array. Needs to contain at least 2 bytes (size fields)"); } uint langIdx = (uint)((has_option(options, "lang") && options.at("lang") == LANG_FR) ? LANG_FR : LANG_EN); const int howManyBytes = (data[0] & 0xFF) + ((data[1] & 0xFF) << 8); if (howManyBytes != (int)data.size() - 2) { std::cerr << "[Warning] Byte count (" << (data.size() - 2) << ") and size field (" << howManyBytes << ") mismatch!"; } if (howManyBytes >= 2) { const uint16_t twoFirstBytes = (uint16_t) ((data[3] & 0xFF) + ((data[2] & 0xFF) << 8)); if (std::find(std::begin(squishedASMTokens), std::end(squishedASMTokens), twoFirstBytes) != std::end(squishedASMTokens)) { return "[Error] This is a squished ASM program - cannnot preview it!"; } } uint errCount = 0; std::string str; const size_t dataSize = data.size(); for (uint i = 2; i < (uint)howManyBytes + 2; i++) { uint currentToken = data[i]; uint nextToken = (i < dataSize-1) ? data[i+1] : (uint)-1; uint bytesKey = currentToken; if (is_in_vector(firstByteOfTwoByteTokens, (uchar)currentToken)) { if (nextToken == (uint)-1) { std::cerr << "[Warning] Encountered an unfinished two-byte token! Setting the second byte to 0x00"; nextToken = 0x00; } bytesKey = nextToken + (currentToken << 8); i++; } if (tokens_BytesToName.find(bytesKey) != tokens_BytesToName.end()) { str += tokens_BytesToName[bytesKey][langIdx]; } else { str += " [???] "; errCount++; } } if (errCount > 0) { std::cerr << "[Warning] " << errCount << " token(s) could not be detokenized (' [???] ' was used)!"; } if (has_option(options, "prettify") && options.at("prettify") == 1) { str = std::regex_replace(str, std::regex(R"(\[?\|?([a-z]+)\]?)"), "$1"); } if (has_option(options, "reindent") && options.at("reindent") == 1) { str = reindentCodeString(str); } return str; } std::string TH_Tokenized::reindentCodeString(const std::string& str_orig, const options_t& options) { int lang; if (has_option(options, "lang")) { lang = options.at("lang"); } else if (str_orig.size() > 1 && str_orig[0] == '.' && (str_orig[1] == '.' || ::isalpha(str_orig[1]))) { lang = PRGMLANG_AXE; } else if (str_orig.size() > 0 && str_orig[0] == '\uf02f') { lang = PRGMLANG_ICE; } else { lang = PRGMLANG_BASIC; } std::string str(str_orig); str = std::regex_replace(str, std::regex("([^\\s])(Del|Eff)Var "), "$1\n$2Var "); std::vector<std::string> lines_tmp = explode(str, '\n'); // Inplace-replace the appropriate ":" by new-line chars (ie, by inserting the split string in the lines_tmp array) for (uint16_t idx = 0; idx < (uint16_t)lines_tmp.size(); idx++) { const auto line = lines_tmp[idx]; bool isWithinString = false; for (uint16_t strIdx = 0; strIdx < (uint16_t)line.size(); strIdx++) { const auto currChar = line.substr(strIdx, 1); if (currChar == ":" && !isWithinString) { lines_tmp[idx] = line.substr(0, strIdx); // replace "old" line by lhs lines_tmp.insert(lines_tmp.begin() + idx + 1, line.substr(strIdx + 1)); // inserting rhs break; } else if (currChar == "\"") { isWithinString = !isWithinString; } else if (currChar == "\n" || currChar == "→") { isWithinString = false; } } } std::vector<std::pair<uint, std::string>> lines(lines_tmp.size()); // indent, text for (const auto& line : lines_tmp) { lines.emplace_back(0, line); } std::vector<std::string> increaseIndentAfter = { "If", "For", "While", "Repeat" }; std::vector<std::string> decreaseIndentOfToken = { "Then", "Else", "End", "ElseIf", "EndIf", "End!If" }; std::vector<std::string> closingTokens = { "End", "EndIf", "End!If" }; uint nextIndent = 0; std::string oldFirstCommand, firstCommand; for (auto& line : lines) { oldFirstCommand = firstCommand; std::string trimmedLine = trim(line.second); if (trimmedLine.length() > 0) { char* trimmedLine_c = (char*) trimmedLine.c_str(); firstCommand = strtok(trimmedLine_c, " "); firstCommand = trim(firstCommand); trimmedLine = std::string(trimmedLine_c); trimmedLine_c = (char*) trimmedLine.c_str(); if (firstCommand == trimmedLine) { firstCommand = strtok(trimmedLine_c, "("); firstCommand = trim(firstCommand); } } else { firstCommand = ""; } line.first = nextIndent; if (is_in_vector(increaseIndentAfter, firstCommand)) { nextIndent++; } if (line.first > 0 && is_in_vector(decreaseIndentOfToken, firstCommand)) { line.first--; } if (nextIndent > 0 && (is_in_vector(closingTokens, firstCommand) || (oldFirstCommand == "If" && firstCommand != "Then" && lang != PRGMLANG_AXE && lang != PRGMLANG_ICE))) { nextIndent--; } } str = ""; for (const auto& line : lines) { str += str_repeat(" ", line.first * 3) + line.second + '\n'; } return ltrim(rtrim(str, "\t\n\r\f\v")); } void TH_Tokenized::initTokens() { std::ifstream t("programs_tokens.csv"); std::string csvFileStr((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); if (csvFileStr.length() > 0) { std::vector<std::vector<std::string>> lines; ParseCSV(csvFileStr, lines); for (const auto& tokenInfo : lines) { uint bytes; if (tokenInfo[6] == "2") // number of bytes for the token { if (!is_in_vector(firstByteOfTwoByteTokens, hexdec(tokenInfo[7]))) { firstByteOfTwoByteTokens.push_back(hexdec(tokenInfo[7])); } bytes = hexdec(tokenInfo[8]) + (hexdec(tokenInfo[7]) << 8); } else { bytes = hexdec(tokenInfo[7]); } tokens_BytesToName[bytes] = { tokenInfo[4], tokenInfo[5] }; // EN, FR tokens_NameToBytes[tokenInfo[4]] = bytes; // EN tokens_NameToBytes[tokenInfo[5]] = bytes; // FR uchar maxLenName = (uchar) std::max(tokenInfo[4].length(), tokenInfo[5].length()); if (maxLenName > lengthOfLongestTokenName) { lengthOfLongestTokenName = maxLenName; } } } else { throw std::runtime_error("Could not open the tokens csv file"); } } } <|endoftext|>
<commit_before>#include "ppk_modules.h" #include "tokenizer.h" #include "vparam.h" #include <sys/types.h> #include <dirent.h> #include <iostream> #include <cstring> //portability functions void* openLibrary(std::string lib_path); void* loadSymbol(void* dlhandle, const char* symbolName); const char* libraryError(); void PPK_Modules::debug(std::string msg) { #ifdef DEBUG_MSG std::cout << msg; #endif } #if defined(WIN32) || defined(WIN64) #include <windows.h> void* openLibrary(std::string lib_path){return LoadLibraryA(lib_path.c_str());} void* loadSymbol(void* dlhandle, const char* symbolName){return (void*)GetProcAddress((HINSTANCE__*)dlhandle, symbolName);} const char* libraryError(){return "";} static const char* baseKey="Software\\PPassKeeper\\"; size_t getRegistryValue(const char* key, char* ret, size_t max_size) { HKEY hk; char tmpBuf[512]; if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, KEY_QUERY_VALUE, &hk)) { DWORD size=sizeof(tmpBuf); RegQueryValueEx(hk, key, 0, 0, (BYTE*)tmpBuf, &size); RegCloseKey(hk); strncpy(ret, tmpBuf, max_size-1); return size; } else return 0; } void PPK_Modules::reload(void) { WIN32_FIND_DATA File; HANDLE hSearch; modules.clear(); //char dir_path[2048]; //unsigned int len=GetEnvironmentVariableA("ppasskeeperMods", dir_path, (DWORD)sizeof(dir_path)); char dir_path[512]; getRegistryValue("mods_path", tmpBuf, sizeof(tmpBuf)); std::string dirpath=dir_path; debug("--------------- <PPassKeeper> ---------------\nIf you don't want to see theses messages, recompile ppasskeeper with the cmake switch '-DPPK_DEBUG=OFF'\n") hSearch = FindFirstFile((dirpath+"\\*.dll").c_str(), &File); if (hSearch != INVALID_HANDLE_VALUE) { do { loadPlugin(dirpath, File.cFileName); }while (FindNextFile(hSearch, &File)); FindClose(hSearch); } else debug("Could not open plugins directory : "+dirpath); debug("--------------- </PPassKeeper> ---------------\n\n"); } #else #include <dlfcn.h> void* openLibrary(std::string lib_path){return dlopen(lib_path.c_str(), RTLD_LAZY);} void* loadSymbol(void* dlhandle, const char* symbolName){return dlsym(dlhandle, symbolName);} const char* libraryError(){return dlerror();} void PPK_Modules::reload(void) { DIR * plugindir; struct dirent * mydirent; modules.clear(); debug("--------------- <PPassKeeper> ---------------\nIf you don't want to see theses messages, recompile ppasskeeper with the cmake switch '-DPPK_DEBUG=OFF'\n"); //Open Plugin's directory plugindir = opendir(DIRECTORY_PATH); if(plugindir!=NULL) { while ((mydirent = readdir(plugindir))!=NULL) { int i = strlen(mydirent->d_name) - 3; //suffix check: don't load libtool (.la) files if (i >= 0 && strcmp(mydirent->d_name + i, ".la")!=0) loadPlugin(DIRECTORY_PATH, mydirent->d_name); } closedir(plugindir); } else debug("Could not open plugins directory : "DIRECTORY_PATH); debug("--------------- </PPassKeeper> ---------------\n\n"); } #endif //Private functions void PPK_Modules::loadPlugin(std::string dirpath, std::string filename) { //if the filename doesn't have the right prefix then try to load it as a shared object if(filename.size()>7 && filename.substr(0,7)=="libppk_") { //debug debug("Load the plugin '"+dirpath+"/"+filename+"': "); //Load the shared object void* dlhandle = openLibrary(dirpath+"/"+filename); if (dlhandle!=NULL) { _module tm; //Temporary module //Try to fill the module structure with the symbols tm.dlhandle=dlhandle; tm.getModuleID=(_getModuleID)loadSymbol(dlhandle, "getModuleID"); tm.getModuleName=(_getModuleName)loadSymbol(dlhandle, "getModuleName"); tm.getABIVersion=(_getABIVersion)loadSymbol(dlhandle, "getABIVersion"); tm.readFlagsAvailable=(_readFlagsAvailable)loadSymbol(dlhandle, "readFlagsAvailable"); tm.writeFlagsAvailable=(_writeFlagsAvailable)loadSymbol(dlhandle, "writeFlagsAvailable"); tm.listingFlagsAvailable=(_listingFlagsAvailable)loadSymbol(dlhandle, "listingFlagsAvailable"); // tm.entryExists=(_entryExists)loadSymbol(dlhandle, "entryExists"); tm.maxDataSize=(_maxDataSize)loadSymbol(dlhandle, "maxDataSize"); tm.getEntry=(_getEntry)loadSymbol(dlhandle, "getEntry"); tm.setEntry=(_setEntry)loadSymbol(dlhandle, "setEntry"); tm.removeEntry=(_removeEntry)loadSymbol(dlhandle, "removeEntry"); tm.isWritable=(_isWritable)loadSymbol(dlhandle, "isWritable"); tm.securityLevel=(_securityLevel)loadSymbol(dlhandle, "securityLevel"); tm.getEntryListCount=(_getEntryListCount)loadSymbol(dlhandle, "getEntryListCount"); tm.getEntryList=(_getEntryList)loadSymbol(dlhandle, "getEntryList"); //errors tm.getLastError=(_getLastError)loadSymbol(dlhandle, "getLastError"); //optionnal tm.setCustomPromptMessage=(_setCustomPromptMessage)loadSymbol(dlhandle, "setCustomPromptMessage"); tm.constructor=(_constructor)loadSymbol(dlhandle, "constructor"); tm.destructor=(_destructor)loadSymbol(dlhandle, "destructor"); tm.availableParameters=(_availableParameters)loadSymbol(dlhandle, "availableParameters"); tm.setParam=(_setParam)loadSymbol(dlhandle, "setParam"); #ifdef DEBUG_MSG if(tm.getModuleID==NULL)std::cerr << "missing : getModuleID();"; if(tm.getModuleName==NULL)std::cerr << "missing : getModuleName();"; if(tm.getABIVersion==NULL)std::cerr << "missing : getABIVersion();"; if(tm.readFlagsAvailable==NULL)std::cerr << "missing : readFlagsAvailable();"; if(tm.writeFlagsAvailable==NULL)std::cerr << "missing : writeFlagsAvailable();"; if(tm.listingFlagsAvailable==NULL)std::cerr << "missing : listingFlagsAvailable();"; if(tm.maxDataSize==NULL)std::cerr << "missing : maxDataSize();"; if(tm.entryExists==NULL)std::cerr << "missing : entryExists();"; if(tm.getEntry==NULL)std::cerr << "missing : getEntry();"; if(tm.setEntry==NULL)std::cerr << "missing : setEntry();"; if(tm.removeEntry==NULL)std::cerr << "missing : removeEntry();"; if(tm.isWritable==NULL)std::cerr << "missing : isWritable();"; if(tm.securityLevel==NULL)std::cerr << "missing : securityLevel();"; if(tm.getEntryListCount==NULL)std::cerr << "missing : getEntryListCount();"; if(tm.getEntryList==NULL)std::cerr << "missing : getEntryList();"; if(tm.getLastError==NULL)std::cerr << "missing : getLastError();"; #endif //if minimal functions are here, add the lib to available modules if(tm.getModuleID!=NULL && tm.getModuleName!=NULL && tm.getABIVersion!=NULL && tm.readFlagsAvailable!=NULL && tm.writeFlagsAvailable!=NULL && tm.listingFlagsAvailable!=NULL && tm.entryExists!=NULL && tm.maxDataSize!=NULL && tm.getEntry!=NULL && tm.setEntry!=NULL && tm.removeEntry!=NULL && tm.getLastError!=NULL && tm.isWritable!=NULL && tm.securityLevel!=NULL && tm.getEntryListCount!=NULL && tm.getEntryList!=NULL) { //Get the ID of the library tm.id=tm.getModuleID(); tm.display_name=tm.getModuleName(); //Call its constructor if(tm.constructor) tm.constructor(); //Send the parameters if(tm.setParam!=NULL) sendParameters(tm); //Copy it into the modules list if it doesn't already exist if(getModuleByID(tm.id)==NULL) { modules[tm.id]=tm; debug((std::string("OK (ID=")+tm.id)+")\n"); } else debug((std::string("FAILED (ID=") + tm.id) + " already exist in modules list)\n"); } else debug("FAILED (not all symbols are present, check version numbers)\n"); } else debug((std::string("FAILED (") + libraryError()) + ")\n"); } } void PPK_Modules::sendParameters(_module m) { VParam& param = VParam::instance(); if(m.setParam!=NULL) { std::vector<std::string> listParams = param.listParams(m.id); for(int i=0;i<listParams.size();i++) { cvariant cv = param.getParam(m.id, listParams[i].c_str()); m.setParam(listParams[i].c_str(), cv); } } } //Public functions PPK_Modules::PPK_Modules() { reload(); } PPK_Modules::~PPK_Modules() { //Call the destructor on every module std::map<std::string, _module>::iterator iter; for( iter = modules.begin(); iter != modules.end(); iter++ ) { if(iter->second.destructor) iter->second.destructor(); } } unsigned int PPK_Modules::size() { return modules.size()+1; } unsigned int PPK_Modules::getModulesList(ppk_module* pmodules, unsigned int ModulesCount) { if(modules.size()>0) { //Automatic module pmodules[0].id=LIBPPK_DEFAULT_MODULE; pmodules[0].display_name=LIBPPK_DEFAULT_MODULE_DESC; std::map<std::string,_module>::iterator iter; unsigned int i; for(i=1,iter=modules.begin(); i<ModulesCount && iter!=modules.end(); i++,iter++) { pmodules[i].id=iter->second.id; pmodules[i].display_name=iter->second.display_name; } return i; } else return false; } const _module* PPK_Modules::getModuleByID(const char* module_id) //return the corresponding module or NULL if the module is not referenced { //Get the real module name if(strcmp(module_id, LIBPPK_DEFAULT_MODULE)==0) module_id=autoModule(); //Does the module exist ? std::map<std::string,_module>::iterator fter = modules.find(module_id); if(fter!=modules.end()) return &(fter->second); else return NULL; } const char* PPK_Modules::autoModule() { if(getenv("GNOME_KEYRING_PID")!=NULL && \ getenv("GNOME_DESKTOP_SESSION_ID")!=NULL && \ ppk_module_is_available("GKeyring") ) { return "GKeyring"; } else if(getenv("KDE_FULL_SESSION")!=NULL && \ strcmp(getenv("KDE_SESSION_VERSION"), "4")==0 && \ ppk_module_is_available("KWallet4") ) { return "KWallet4"; } else if(ppk_module_is_available("SaveToFile_Enc")) return "SaveToFile_Enc"; else if(ppk_module_is_available("SaveToFile_PT")) return "SaveToFile_PT"; else if(ppk_module_count()>1) { ppk_module mods[2]; ppk_module_list(mods, sizeof(mods)); return mods[1].id; } else return ""; } <commit_msg>Windows: build fix<commit_after>#include "ppk_modules.h" #include "tokenizer.h" #include "vparam.h" #include <sys/types.h> #include <dirent.h> #include <iostream> #include <cstring> //portability functions void* openLibrary(std::string lib_path); void* loadSymbol(void* dlhandle, const char* symbolName); const char* libraryError(); void PPK_Modules::debug(std::string msg) { #ifdef DEBUG_MSG std::cout << msg; #endif } #if defined(WIN32) || defined(WIN64) #include <windows.h> void* openLibrary(std::string lib_path){return LoadLibraryA(lib_path.c_str());} void* loadSymbol(void* dlhandle, const char* symbolName){return (void*)GetProcAddress((HINSTANCE__*)dlhandle, symbolName);} const char* libraryError(){return "";} static const char* baseKey="Software\\PPassKeeper\\"; size_t getRegistryValue(const char* key, char* ret, size_t max_size) { HKEY hk; char tmpBuf[512]; if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, KEY_QUERY_VALUE, &hk)) { DWORD size=sizeof(tmpBuf); RegQueryValueEx(hk, key, 0, 0, (BYTE*)tmpBuf, &size); RegCloseKey(hk); strncpy(ret, tmpBuf, max_size-1); return size; } else return 0; } void PPK_Modules::reload(void) { WIN32_FIND_DATA File; HANDLE hSearch; modules.clear(); //char dir_path[2048]; //unsigned int len=GetEnvironmentVariableA("ppasskeeperMods", dir_path, (DWORD)sizeof(dir_path)); char dir_path[512]; getRegistryValue("mods_path", dir_path, sizeof(dir_path)); std::string dirpath=dir_path; debug("--------------- <PPassKeeper> ---------------\nIf you don't want to see theses messages, recompile ppasskeeper with the cmake switch '-DPPK_DEBUG=OFF'\n"); hSearch = FindFirstFile((dirpath+"\\*.dll").c_str(), &File); if (hSearch != INVALID_HANDLE_VALUE) { do { loadPlugin(dirpath, File.cFileName); }while (FindNextFile(hSearch, &File)); FindClose(hSearch); } else debug("Could not open plugins directory : "+dirpath); debug("--------------- </PPassKeeper> ---------------\n\n"); } #else #include <dlfcn.h> void* openLibrary(std::string lib_path){return dlopen(lib_path.c_str(), RTLD_LAZY);} void* loadSymbol(void* dlhandle, const char* symbolName){return dlsym(dlhandle, symbolName);} const char* libraryError(){return dlerror();} void PPK_Modules::reload(void) { DIR * plugindir; struct dirent * mydirent; modules.clear(); debug("--------------- <PPassKeeper> ---------------\nIf you don't want to see theses messages, recompile ppasskeeper with the cmake switch '-DPPK_DEBUG=OFF'\n"); //Open Plugin's directory plugindir = opendir(DIRECTORY_PATH); if(plugindir!=NULL) { while ((mydirent = readdir(plugindir))!=NULL) { int i = strlen(mydirent->d_name) - 3; //suffix check: don't load libtool (.la) files if (i >= 0 && strcmp(mydirent->d_name + i, ".la")!=0) loadPlugin(DIRECTORY_PATH, mydirent->d_name); } closedir(plugindir); } else debug("Could not open plugins directory : "DIRECTORY_PATH); debug("--------------- </PPassKeeper> ---------------\n\n"); } #endif //Private functions void PPK_Modules::loadPlugin(std::string dirpath, std::string filename) { //if the filename doesn't have the right prefix then try to load it as a shared object if(filename.size()>7 && filename.substr(0,7)=="libppk_") { //debug debug("Load the plugin '"+dirpath+"/"+filename+"': "); //Load the shared object void* dlhandle = openLibrary(dirpath+"/"+filename); if (dlhandle!=NULL) { _module tm; //Temporary module //Try to fill the module structure with the symbols tm.dlhandle=dlhandle; tm.getModuleID=(_getModuleID)loadSymbol(dlhandle, "getModuleID"); tm.getModuleName=(_getModuleName)loadSymbol(dlhandle, "getModuleName"); tm.getABIVersion=(_getABIVersion)loadSymbol(dlhandle, "getABIVersion"); tm.readFlagsAvailable=(_readFlagsAvailable)loadSymbol(dlhandle, "readFlagsAvailable"); tm.writeFlagsAvailable=(_writeFlagsAvailable)loadSymbol(dlhandle, "writeFlagsAvailable"); tm.listingFlagsAvailable=(_listingFlagsAvailable)loadSymbol(dlhandle, "listingFlagsAvailable"); // tm.entryExists=(_entryExists)loadSymbol(dlhandle, "entryExists"); tm.maxDataSize=(_maxDataSize)loadSymbol(dlhandle, "maxDataSize"); tm.getEntry=(_getEntry)loadSymbol(dlhandle, "getEntry"); tm.setEntry=(_setEntry)loadSymbol(dlhandle, "setEntry"); tm.removeEntry=(_removeEntry)loadSymbol(dlhandle, "removeEntry"); tm.isWritable=(_isWritable)loadSymbol(dlhandle, "isWritable"); tm.securityLevel=(_securityLevel)loadSymbol(dlhandle, "securityLevel"); tm.getEntryListCount=(_getEntryListCount)loadSymbol(dlhandle, "getEntryListCount"); tm.getEntryList=(_getEntryList)loadSymbol(dlhandle, "getEntryList"); //errors tm.getLastError=(_getLastError)loadSymbol(dlhandle, "getLastError"); //optionnal tm.setCustomPromptMessage=(_setCustomPromptMessage)loadSymbol(dlhandle, "setCustomPromptMessage"); tm.constructor=(_constructor)loadSymbol(dlhandle, "constructor"); tm.destructor=(_destructor)loadSymbol(dlhandle, "destructor"); tm.availableParameters=(_availableParameters)loadSymbol(dlhandle, "availableParameters"); tm.setParam=(_setParam)loadSymbol(dlhandle, "setParam"); #ifdef DEBUG_MSG if(tm.getModuleID==NULL)std::cerr << "missing : getModuleID();"; if(tm.getModuleName==NULL)std::cerr << "missing : getModuleName();"; if(tm.getABIVersion==NULL)std::cerr << "missing : getABIVersion();"; if(tm.readFlagsAvailable==NULL)std::cerr << "missing : readFlagsAvailable();"; if(tm.writeFlagsAvailable==NULL)std::cerr << "missing : writeFlagsAvailable();"; if(tm.listingFlagsAvailable==NULL)std::cerr << "missing : listingFlagsAvailable();"; if(tm.maxDataSize==NULL)std::cerr << "missing : maxDataSize();"; if(tm.entryExists==NULL)std::cerr << "missing : entryExists();"; if(tm.getEntry==NULL)std::cerr << "missing : getEntry();"; if(tm.setEntry==NULL)std::cerr << "missing : setEntry();"; if(tm.removeEntry==NULL)std::cerr << "missing : removeEntry();"; if(tm.isWritable==NULL)std::cerr << "missing : isWritable();"; if(tm.securityLevel==NULL)std::cerr << "missing : securityLevel();"; if(tm.getEntryListCount==NULL)std::cerr << "missing : getEntryListCount();"; if(tm.getEntryList==NULL)std::cerr << "missing : getEntryList();"; if(tm.getLastError==NULL)std::cerr << "missing : getLastError();"; #endif //if minimal functions are here, add the lib to available modules if(tm.getModuleID!=NULL && tm.getModuleName!=NULL && tm.getABIVersion!=NULL && tm.readFlagsAvailable!=NULL && tm.writeFlagsAvailable!=NULL && tm.listingFlagsAvailable!=NULL && tm.entryExists!=NULL && tm.maxDataSize!=NULL && tm.getEntry!=NULL && tm.setEntry!=NULL && tm.removeEntry!=NULL && tm.getLastError!=NULL && tm.isWritable!=NULL && tm.securityLevel!=NULL && tm.getEntryListCount!=NULL && tm.getEntryList!=NULL) { //Get the ID of the library tm.id=tm.getModuleID(); tm.display_name=tm.getModuleName(); //Call its constructor if(tm.constructor) tm.constructor(); //Send the parameters if(tm.setParam!=NULL) sendParameters(tm); //Copy it into the modules list if it doesn't already exist if(getModuleByID(tm.id)==NULL) { modules[tm.id]=tm; debug((std::string("OK (ID=")+tm.id)+")\n"); } else debug((std::string("FAILED (ID=") + tm.id) + " already exist in modules list)\n"); } else debug("FAILED (not all symbols are present, check version numbers)\n"); } else debug((std::string("FAILED (") + libraryError()) + ")\n"); } } void PPK_Modules::sendParameters(_module m) { VParam& param = VParam::instance(); if(m.setParam!=NULL) { std::vector<std::string> listParams = param.listParams(m.id); for(int i=0;i<listParams.size();i++) { cvariant cv = param.getParam(m.id, listParams[i].c_str()); m.setParam(listParams[i].c_str(), cv); } } } //Public functions PPK_Modules::PPK_Modules() { reload(); } PPK_Modules::~PPK_Modules() { //Call the destructor on every module std::map<std::string, _module>::iterator iter; for( iter = modules.begin(); iter != modules.end(); iter++ ) { if(iter->second.destructor) iter->second.destructor(); } } unsigned int PPK_Modules::size() { return modules.size()+1; } unsigned int PPK_Modules::getModulesList(ppk_module* pmodules, unsigned int ModulesCount) { if(modules.size()>0) { //Automatic module pmodules[0].id=LIBPPK_DEFAULT_MODULE; pmodules[0].display_name=LIBPPK_DEFAULT_MODULE_DESC; std::map<std::string,_module>::iterator iter; unsigned int i; for(i=1,iter=modules.begin(); i<ModulesCount && iter!=modules.end(); i++,iter++) { pmodules[i].id=iter->second.id; pmodules[i].display_name=iter->second.display_name; } return i; } else return false; } const _module* PPK_Modules::getModuleByID(const char* module_id) //return the corresponding module or NULL if the module is not referenced { //Get the real module name if(strcmp(module_id, LIBPPK_DEFAULT_MODULE)==0) module_id=autoModule(); //Does the module exist ? std::map<std::string,_module>::iterator fter = modules.find(module_id); if(fter!=modules.end()) return &(fter->second); else return NULL; } const char* PPK_Modules::autoModule() { if(getenv("GNOME_KEYRING_PID")!=NULL && \ getenv("GNOME_DESKTOP_SESSION_ID")!=NULL && \ ppk_module_is_available("GKeyring") ) { return "GKeyring"; } else if(getenv("KDE_FULL_SESSION")!=NULL && \ strcmp(getenv("KDE_SESSION_VERSION"), "4")==0 && \ ppk_module_is_available("KWallet4") ) { return "KWallet4"; } else if(ppk_module_is_available("SaveToFile_Enc")) return "SaveToFile_Enc"; else if(ppk_module_is_available("SaveToFile_PT")) return "SaveToFile_PT"; else if(ppk_module_count()>1) { ppk_module mods[2]; ppk_module_list(mods, sizeof(mods)); return mods[1].id; } else return ""; } <|endoftext|>
<commit_before>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass uses the top-down data structure graphs to implement a simple // context sensitive alias analysis. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" using namespace llvm; namespace { class DSAA : public ModulePass, public AliasAnalysis { TDDataStructures *TD; BUDataStructures *BU; public: DSAA() : TD(0) {} //------------------------------------------------ // Implement the Pass API // // run - Build up the result graph, representing the pointer graph for the // program. // bool runOnModule(Module &M) { InitializeAliasAnalysis(this); TD = &getAnalysis<TDDataStructures>(); BU = &getAnalysis<BUDataStructures>(); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AliasAnalysis::getAnalysisUsage(AU); AU.setPreservesAll(); // Does not transform code AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures } //------------------------------------------------ // Implement the AliasAnalysis API // AliasResult alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size); void getMustAliases(Value *P, std::vector<Value*> &RetVals); ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { return AliasAnalysis::getModRefInfo(CS1,CS2); } virtual void deleteValue(Value *V) { BU->deleteValue(V); TD->deleteValue(V); } virtual void copyValue(Value *From, Value *To) { if (From == To) return; BU->copyValue(From, To); TD->copyValue(From, To); } private: DSGraph *getGraphForValue(const Value *V); }; // Register the pass... RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis"); // Register as an implementation of AliasAnalysis RegisterAnalysisGroup<AliasAnalysis, DSAA> Y; } ModulePass *llvm::createDSAAPass() { return new DSAA(); } // getGraphForValue - Return the DSGraph to use for queries about the specified // value... // DSGraph *DSAA::getGraphForValue(const Value *V) { if (const Instruction *I = dyn_cast<Instruction>(V)) return &TD->getDSGraph(*I->getParent()->getParent()); else if (const Argument *A = dyn_cast<Argument>(V)) return &TD->getDSGraph(*A->getParent()); else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) return &TD->getDSGraph(*BB->getParent()); return 0; } // isSinglePhysicalObject - For now, the only case that we know that there is // only one memory object in the node is when there is a single global in the // node, and the only composition bit set is Global. // static bool isSinglePhysicalObject(DSNode *N) { assert(N->isComplete() && "Can only tell if this is a complete object!"); return N->isGlobalNode() && N->getGlobals().size() == 1 && !N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode(); } // alias - This is the only method here that does anything interesting... AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { if (V1 == V2) return MustAlias; DSGraph *G1 = getGraphForValue(V1); DSGraph *G2 = getGraphForValue(V2); assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?"); // Get the graph to use... DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph())); const DSGraph::ScalarMapTy &GSM = G.getScalarMap(); DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1); if (I == GSM.end()) return NoAlias; DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2); if (J == GSM.end()) return NoAlias; DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode(); unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset(); if (N1 == 0 || N2 == 0) return MayAlias; // Can't tell whether anything aliases null. // We can only make a judgment of one of the nodes is complete... if (N1->isComplete() || N2->isComplete()) { if (N1 != N2) return NoAlias; // Completely different nodes. #if 0 // This does not correctly handle arrays! // Both point to the same node and same offset, and there is only one // physical memory object represented in the node, return must alias. // // FIXME: This isn't correct because we do not handle array indexing // correctly. if (O1 == O2 && isSinglePhysicalObject(N1)) return MustAlias; // Exactly the same object & offset #endif // See if they point to different offsets... if so, we may be able to // determine that they do not alias... if (O1 != O2) { if (O2 < O1) { // Ensure that O1 <= O2 std::swap(V1, V2); std::swap(O1, O2); std::swap(V1Size, V2Size); } // FIXME: This is not correct because we do not handle array // indexing correctly with this check! //if (O1+V1Size <= O2) return NoAlias; } } // FIXME: we could improve on this by checking the globals graph for aliased // global queries... return AliasAnalysis::alias(V1, V1Size, V2, V2Size); } /// getModRefInfo - does a callsite modify or reference a value? /// AliasAnalysis::ModRefResult DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) { AliasAnalysis::ModRefResult Result =AliasAnalysis::getModRefInfo(CS, P, Size); Function *F = CS.getCalledFunction(); if (!F || F->isExternal() || Result == NoModRef) return Result; // Get the graphs for the callee and caller. Note that we want the BU graph // for the callee because we don't want all caller's effects incorporated! const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); DSGraph &CalleeBUGraph = BU->getDSGraph(*F); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P)) Result = NoModRef; // null is never modified :) else { assert(isa<GlobalVariable>(P) && cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() && "This isn't a global that DSA inconsiderately dropped " "from the graph?"); } return Result; } const DSNode *N = NI->second.getNode(); assert(N && "Null pointer in scalar map??"); // Compute the mapping from nodes in the callee graph to the nodes in the // caller graph for this call site. DSGraph::NodeMapTy CalleeCallerMap; DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS); CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph, CalleeCallerMap); // Loop over all of the nodes in the callee that correspond to "N", keeping // track of aggregate mod/ref info. bool NeverReads = true, NeverWrites = true; for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(), E = CalleeCallerMap.end(); I != E; ++I) if (I->second.getNode() == N) { if (I->first->isModified()) NeverWrites = false; if (I->first->isRead()) NeverReads = false; if (NeverReads == false && NeverWrites == false) return Result; } if (NeverWrites) // We proved it was not modified. Result = ModRefResult(Result & ~Mod); if (NeverReads) // We proved it was not read. Result = ModRefResult(Result & ~Ref); return Result; } /// getMustAliases - If there are any pointers known that must alias this /// pointer, return them now. This allows alias-set based alias analyses to /// perform a form a value numbering (which is exposed by load-vn). If an alias /// analysis supports this, it should ADD any must aliased pointers to the /// specified vector. /// void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) { #if 0 // This does not correctly handle arrays! // Currently the only must alias information we can provide is to say that // something is equal to a global value. If we already have a global value, // don't get worked up about it. if (!isa<GlobalValue>(P)) { DSGraph *G = getGraphForValue(P); if (!G) G = &TD->getGlobalsGraph(); // The only must alias information we can currently determine occurs when // the node for P is a global node with only one entry. DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P); if (I != G->getScalarMap().end()) { DSNode *N = I->second.getNode(); if (N->isComplete() && isSinglePhysicalObject(N)) RetVals.push_back(N->getGlobals()[0]); } } #endif return AliasAnalysis::getMustAliases(P, RetVals); } <commit_msg>#ifdef out a function only used by #ifdef'd code.<commit_after>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass uses the top-down data structure graphs to implement a simple // context sensitive alias analysis. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" using namespace llvm; namespace { class DSAA : public ModulePass, public AliasAnalysis { TDDataStructures *TD; BUDataStructures *BU; public: DSAA() : TD(0) {} //------------------------------------------------ // Implement the Pass API // // run - Build up the result graph, representing the pointer graph for the // program. // bool runOnModule(Module &M) { InitializeAliasAnalysis(this); TD = &getAnalysis<TDDataStructures>(); BU = &getAnalysis<BUDataStructures>(); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AliasAnalysis::getAnalysisUsage(AU); AU.setPreservesAll(); // Does not transform code AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures } //------------------------------------------------ // Implement the AliasAnalysis API // AliasResult alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size); void getMustAliases(Value *P, std::vector<Value*> &RetVals); ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { return AliasAnalysis::getModRefInfo(CS1,CS2); } virtual void deleteValue(Value *V) { BU->deleteValue(V); TD->deleteValue(V); } virtual void copyValue(Value *From, Value *To) { if (From == To) return; BU->copyValue(From, To); TD->copyValue(From, To); } private: DSGraph *getGraphForValue(const Value *V); }; // Register the pass... RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis"); // Register as an implementation of AliasAnalysis RegisterAnalysisGroup<AliasAnalysis, DSAA> Y; } ModulePass *llvm::createDSAAPass() { return new DSAA(); } // getGraphForValue - Return the DSGraph to use for queries about the specified // value... // DSGraph *DSAA::getGraphForValue(const Value *V) { if (const Instruction *I = dyn_cast<Instruction>(V)) return &TD->getDSGraph(*I->getParent()->getParent()); else if (const Argument *A = dyn_cast<Argument>(V)) return &TD->getDSGraph(*A->getParent()); else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) return &TD->getDSGraph(*BB->getParent()); return 0; } #if 0 // isSinglePhysicalObject - For now, the only case that we know that there is // only one memory object in the node is when there is a single global in the // node, and the only composition bit set is Global. // static bool isSinglePhysicalObject(DSNode *N) { assert(N->isComplete() && "Can only tell if this is a complete object!"); return N->isGlobalNode() && N->getGlobals().size() == 1 && !N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode(); } #endif // alias - This is the only method here that does anything interesting... AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { if (V1 == V2) return MustAlias; DSGraph *G1 = getGraphForValue(V1); DSGraph *G2 = getGraphForValue(V2); assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?"); // Get the graph to use... DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph())); const DSGraph::ScalarMapTy &GSM = G.getScalarMap(); DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1); if (I == GSM.end()) return NoAlias; DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2); if (J == GSM.end()) return NoAlias; DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode(); unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset(); if (N1 == 0 || N2 == 0) return MayAlias; // Can't tell whether anything aliases null. // We can only make a judgment of one of the nodes is complete... if (N1->isComplete() || N2->isComplete()) { if (N1 != N2) return NoAlias; // Completely different nodes. #if 0 // This does not correctly handle arrays! // Both point to the same node and same offset, and there is only one // physical memory object represented in the node, return must alias. // // FIXME: This isn't correct because we do not handle array indexing // correctly. if (O1 == O2 && isSinglePhysicalObject(N1)) return MustAlias; // Exactly the same object & offset #endif // See if they point to different offsets... if so, we may be able to // determine that they do not alias... if (O1 != O2) { if (O2 < O1) { // Ensure that O1 <= O2 std::swap(V1, V2); std::swap(O1, O2); std::swap(V1Size, V2Size); } // FIXME: This is not correct because we do not handle array // indexing correctly with this check! //if (O1+V1Size <= O2) return NoAlias; } } // FIXME: we could improve on this by checking the globals graph for aliased // global queries... return AliasAnalysis::alias(V1, V1Size, V2, V2Size); } /// getModRefInfo - does a callsite modify or reference a value? /// AliasAnalysis::ModRefResult DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) { AliasAnalysis::ModRefResult Result =AliasAnalysis::getModRefInfo(CS, P, Size); Function *F = CS.getCalledFunction(); if (!F || F->isExternal() || Result == NoModRef) return Result; // Get the graphs for the callee and caller. Note that we want the BU graph // for the callee because we don't want all caller's effects incorporated! const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); DSGraph &CalleeBUGraph = BU->getDSGraph(*F); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P)) Result = NoModRef; // null is never modified :) else { assert(isa<GlobalVariable>(P) && cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() && "This isn't a global that DSA inconsiderately dropped " "from the graph?"); } return Result; } const DSNode *N = NI->second.getNode(); assert(N && "Null pointer in scalar map??"); // Compute the mapping from nodes in the callee graph to the nodes in the // caller graph for this call site. DSGraph::NodeMapTy CalleeCallerMap; DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS); CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph, CalleeCallerMap); // Loop over all of the nodes in the callee that correspond to "N", keeping // track of aggregate mod/ref info. bool NeverReads = true, NeverWrites = true; for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(), E = CalleeCallerMap.end(); I != E; ++I) if (I->second.getNode() == N) { if (I->first->isModified()) NeverWrites = false; if (I->first->isRead()) NeverReads = false; if (NeverReads == false && NeverWrites == false) return Result; } if (NeverWrites) // We proved it was not modified. Result = ModRefResult(Result & ~Mod); if (NeverReads) // We proved it was not read. Result = ModRefResult(Result & ~Ref); return Result; } /// getMustAliases - If there are any pointers known that must alias this /// pointer, return them now. This allows alias-set based alias analyses to /// perform a form a value numbering (which is exposed by load-vn). If an alias /// analysis supports this, it should ADD any must aliased pointers to the /// specified vector. /// void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) { #if 0 // This does not correctly handle arrays! // Currently the only must alias information we can provide is to say that // something is equal to a global value. If we already have a global value, // don't get worked up about it. if (!isa<GlobalValue>(P)) { DSGraph *G = getGraphForValue(P); if (!G) G = &TD->getGlobalsGraph(); // The only must alias information we can currently determine occurs when // the node for P is a global node with only one entry. DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P); if (I != G->getScalarMap().end()) { DSNode *N = I->second.getNode(); if (N->isComplete() && isSinglePhysicalObject(N)) RetVals.push_back(N->getGlobals()[0]); } } #endif return AliasAnalysis::getMustAliases(P, RetVals); } <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vprConfig.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #include <sys/time.h> #include <errno.h> #include <md/POSIX/SelectorImpBSD.h> #include <Utils/Assert.h> namespace vpr { //: Add the given handle to the selector //! PRE: handle is a valid handle //! POST: handle is added to the handle set, and initialized to a mask of //+ no-events bool SelectorImpBSD::addHandle (IOSys::Handle handle) { bool status; if ( getHandle(handle) == mPollDescs.end() ) { BSDPollDesc new_desc; new_desc.fd = handle; new_desc.in_flags = 0; new_desc.out_flags = 0; mPollDescs.push_back(new_desc); status = true; } else { status = false; } return status; } //: Remove a handle from the selector //! PRE: handle is in the selector //! POST: handle is removed from the set of valid handles bool SelectorImpBSD::removeHandle (IOSys::Handle handle) { bool status; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { status = false; } else { mPollDescs.erase(i); status = true; } return status; } //: Set the event flags going in to the select to mask bool SelectorImpBSD::setIn (IOSys::Handle handle, vpr::Uint16 mask) { bool status; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { status = false; } else { (*i).in_flags = mask; status = true; } return status; } //: Get the current in flag mask vpr::Uint16 SelectorImpBSD::getIn (IOSys::Handle handle) { vpr::Uint16 flags; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { // XXX: This is VERY bad thing to do. Need to have an error code instead flags = 0; } else { flags = (*i).in_flags; } return flags; } //: Get the current out flag mask vpr::Uint16 SelectorImpBSD::getOut (IOSys::Handle handle) { vpr::Uint16 flags; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { // XXX: This is VERY bad thing to do. Need to have an error code instead flags = 0; } else { flags = (*i).out_flags; } return flags; } //: Select //! ARGS: numWithEvents - Upon completion, this holds the number of items that //+ have events //! ARGS: timeout - The number of msecs to select for (0 - don't wait) Status SelectorImpBSD::select (vpr::Uint16& numWithEvents, vpr::Uint16 timeout) { vpr::Status ret_val; int result; fd_set read_set, write_set, exception_set; std::vector<BSDPollDesc>::iterator i; struct timeval timeout_obj; // Zero everything out before doing anything else. FD_ZERO(&read_set); FD_ZERO(&write_set); FD_ZERO(&exception_set); for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) { if ( (*i).in_flags & SelectorBase::VPR_READ ) { FD_SET((*i).fd, &read_set); } if ( (*i).in_flags & SelectorBase::VPR_WRITE ) { FD_SET((*i).fd, &write_set); } if ( (*i).in_flags & SelectorBase::VPR_EXCEPT ) { FD_SET((*i).fd, &exception_set); } } // Apparently select(2) doesn't like if the microsecond member has a time // larger than 1 second, so if timeout (given in milliseconds) is larger // than 1000, we have to split it up between the seconds and microseconds // members. if ( timeout >= 1000 ) { timeout_obj.tv_sec = timeout / 1000; timeout_obj.tv_usec = (timeout % 1000) * 1000000; } else { timeout_obj.tv_sec = 0; timeout_obj.tv_usec = timeout * 1000; } // If timeout is 0, this will be the same as polling the descriptors. To // get no timeout, NULL must be passed to select(2). result = ::select(mPollDescs.size(), &read_set, &write_set, &exception_set, (timeout > 0) ? &timeout_obj : NULL); // D'oh! if ( -1 == result ) { fprintf(stderr, "SelectorImpBSD::select: Error selecting: %s\n", strerror(errno)); numWithEvents = 0; ret_val.setCode(Status::Failure); } // Timeout. else if ( 0 == result ) { numWithEvents = 0; ret_val.setCode(Status::Timeout); } // We got one! else { for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) { if ( FD_ISSET((*i).fd, &read_set) ) { (*i).out_flags |= SelectorBase::VPR_READ; } if ( FD_ISSET((*i).fd, &write_set) ) { (*i).out_flags |= SelectorBase::VPR_WRITE; } if ( FD_ISSET((*i).fd, &exception_set) ) { (*i).out_flags |= SelectorBase::VPR_EXCEPT; } } } numWithEvents = result; return ret_val; } // Get the index of the handle given //! RETURNS: .end() - Not found, else the index to the handle in mPollDescs std::vector<SelectorImpBSD::BSDPollDesc>::iterator SelectorImpBSD::getHandle (int handle) { // XXX: Should probably be replaced by a map in the future for speed for(std::vector<BSDPollDesc>::iterator i=mPollDescs.begin(); i != mPollDescs.end();i++) { if((*i).fd == handle) return i; } return mPollDescs.end(); } } // namespace vpr <commit_msg>In select(), 'numWithEvents' was being set to the value of 'result' even when select(2) failed. This assginment should only be made when one or more of the file descriptors is ready.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vprConfig.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #include <sys/time.h> #include <errno.h> #include <md/POSIX/SelectorImpBSD.h> #include <Utils/Assert.h> namespace vpr { //: Add the given handle to the selector //! PRE: handle is a valid handle //! POST: handle is added to the handle set, and initialized to a mask of //+ no-events bool SelectorImpBSD::addHandle (IOSys::Handle handle) { bool status; if ( getHandle(handle) == mPollDescs.end() ) { BSDPollDesc new_desc; new_desc.fd = handle; new_desc.in_flags = 0; new_desc.out_flags = 0; mPollDescs.push_back(new_desc); status = true; } else { status = false; } return status; } //: Remove a handle from the selector //! PRE: handle is in the selector //! POST: handle is removed from the set of valid handles bool SelectorImpBSD::removeHandle (IOSys::Handle handle) { bool status; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { status = false; } else { mPollDescs.erase(i); status = true; } return status; } //: Set the event flags going in to the select to mask bool SelectorImpBSD::setIn (IOSys::Handle handle, vpr::Uint16 mask) { bool status; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { status = false; } else { (*i).in_flags = mask; status = true; } return status; } //: Get the current in flag mask vpr::Uint16 SelectorImpBSD::getIn (IOSys::Handle handle) { vpr::Uint16 flags; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { // XXX: This is VERY bad thing to do. Need to have an error code instead flags = 0; } else { flags = (*i).in_flags; } return flags; } //: Get the current out flag mask vpr::Uint16 SelectorImpBSD::getOut (IOSys::Handle handle) { vpr::Uint16 flags; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { // XXX: This is VERY bad thing to do. Need to have an error code instead flags = 0; } else { flags = (*i).out_flags; } return flags; } //: Select //! ARGS: numWithEvents - Upon completion, this holds the number of items that //+ have events //! ARGS: timeout - The number of msecs to select for (0 - don't wait) Status SelectorImpBSD::select (vpr::Uint16& numWithEvents, vpr::Uint16 timeout) { vpr::Status ret_val; int result; fd_set read_set, write_set, exception_set; std::vector<BSDPollDesc>::iterator i; struct timeval timeout_obj; // Zero everything out before doing anything else. FD_ZERO(&read_set); FD_ZERO(&write_set); FD_ZERO(&exception_set); for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) { if ( (*i).in_flags & SelectorBase::VPR_READ ) { FD_SET((*i).fd, &read_set); } if ( (*i).in_flags & SelectorBase::VPR_WRITE ) { FD_SET((*i).fd, &write_set); } if ( (*i).in_flags & SelectorBase::VPR_EXCEPT ) { FD_SET((*i).fd, &exception_set); } } // Apparently select(2) doesn't like if the microsecond member has a time // larger than 1 second, so if timeout (given in milliseconds) is larger // than 1000, we have to split it up between the seconds and microseconds // members. if ( timeout >= 1000 ) { timeout_obj.tv_sec = timeout / 1000; timeout_obj.tv_usec = (timeout % 1000) * 1000000; } else { timeout_obj.tv_sec = 0; timeout_obj.tv_usec = timeout * 1000; } // If timeout is 0, this will be the same as polling the descriptors. To // get no timeout, NULL must be passed to select(2). result = ::select(mPollDescs.size(), &read_set, &write_set, &exception_set, (timeout > 0) ? &timeout_obj : NULL); // D'oh! if ( -1 == result ) { fprintf(stderr, "SelectorImpBSD::select: Error selecting: %s\n", strerror(errno)); numWithEvents = 0; ret_val.setCode(Status::Failure); } // Timeout. else if ( 0 == result ) { numWithEvents = 0; ret_val.setCode(Status::Timeout); } // We got one! else { for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) { if ( FD_ISSET((*i).fd, &read_set) ) { (*i).out_flags |= SelectorBase::VPR_READ; } if ( FD_ISSET((*i).fd, &write_set) ) { (*i).out_flags |= SelectorBase::VPR_WRITE; } if ( FD_ISSET((*i).fd, &exception_set) ) { (*i).out_flags |= SelectorBase::VPR_EXCEPT; } } numWithEvents = result; } return ret_val; } // Get the index of the handle given //! RETURNS: .end() - Not found, else the index to the handle in mPollDescs std::vector<SelectorImpBSD::BSDPollDesc>::iterator SelectorImpBSD::getHandle (int handle) { // XXX: Should probably be replaced by a map in the future for speed for(std::vector<BSDPollDesc>::iterator i=mPollDescs.begin(); i != mPollDescs.end();i++) { if((*i).fd == handle) return i; } return mPollDescs.end(); } } // namespace vpr <|endoftext|>
<commit_before>/* Algorithm Factory (C) 2008 Jack Lloyd */ #include <botan/algo_factory.h> #include <botan/stl_util.h> #include <botan/engine.h> #include <botan/exceptn.h> #include <botan/block_cipher.h> #include <botan/stream_cipher.h> #include <botan/hash.h> #include <botan/mac.h> #include <algorithm> namespace Botan { namespace { /** * Template functions for the factory prototype/search algorithm */ template<typename T> T* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return 0; } template<> BlockCipher* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_block_cipher(request, af); } template<> StreamCipher* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_stream_cipher(request, af); } template<> HashFunction* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_hash(request, af); } template<> MessageAuthenticationCode* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_mac(request, af); } template<typename T> const T* factory_prototype(const std::string& algo_spec, const std::string& provider, const std::vector<Engine*>& engines, Algorithm_Factory& af, Algorithm_Cache<T>& cache) { if(const T* cache_hit = cache.get(algo_spec, provider)) return cache_hit; SCAN_Name scan_name(algo_spec); for(u32bit i = 0; i != engines.size(); ++i) { T* impl = engine_get_algo<T>(engines[i], scan_name, af); if(impl) cache.add(impl, algo_spec, engines[i]->provider_name()); } return cache.get(algo_spec, provider); } } /** * Setup caches */ Algorithm_Factory::Algorithm_Factory(const std::vector<Engine*>& engines_in, Mutex_Factory& mf) : engines(engines_in), block_cipher_cache(mf.make()), stream_cipher_cache(mf.make()), hash_cache(mf.make()), mac_cache(mf.make()) { } /** * Delete all engines */ Algorithm_Factory::~Algorithm_Factory() { std::for_each(engines.begin(), engines.end(), del_fun<Engine>()); engines.clear(); } /** * Set the preferred provider for an algorithm */ void Algorithm_Factory::set_preferred_provider(const std::string& algo_spec, const std::string& provider) { if(prototype_block_cipher(algo_spec)) block_cipher_cache.set_preferred_provider(algo_spec, provider); else if(prototype_stream_cipher(algo_spec)) stream_cipher_cache.set_preferred_provider(algo_spec, provider); else if(prototype_hash_function(algo_spec)) hash_cache.set_preferred_provider(algo_spec, provider); else if(prototype_mac(algo_spec)) mac_cache.set_preferred_provider(algo_spec, provider); } /** * Get an engine out of the list */ Engine* Algorithm_Factory::get_engine_n(u32bit n) const { if(n >= engines.size()) return 0; return engines[n]; } /** * Return the possible providers of a request * Note: assumes you don't have different types by the same name */ std::vector<std::string> Algorithm_Factory::providers_of(const std::string& algo_spec) { if(prototype_block_cipher(algo_spec)) return block_cipher_cache.providers_of(algo_spec); else if(prototype_stream_cipher(algo_spec)) return stream_cipher_cache.providers_of(algo_spec); else if(prototype_hash_function(algo_spec)) return hash_cache.providers_of(algo_spec); else if(prototype_mac(algo_spec)) return mac_cache.providers_of(algo_spec); else return std::vector<std::string>(); } /** * Return the prototypical block cipher cooresponding to this request */ const BlockCipher* Algorithm_Factory::prototype_block_cipher(const std::string& algo_spec, const std::string& provider) { return factory_prototype<BlockCipher>(algo_spec, provider, engines, *this, block_cipher_cache); } /** * Return the prototypical stream cipher cooresponding to this request */ const StreamCipher* Algorithm_Factory::prototype_stream_cipher(const std::string& algo_spec, const std::string& provider) { return factory_prototype<StreamCipher>(algo_spec, provider, engines, *this, stream_cipher_cache); } /** * Return the prototypical object cooresponding to this request (if found) */ const HashFunction* Algorithm_Factory::prototype_hash_function(const std::string& algo_spec, const std::string& provider) { return factory_prototype<HashFunction>(algo_spec, provider, engines, *this, hash_cache); } /** * Return the prototypical object cooresponding to this request */ const MessageAuthenticationCode* Algorithm_Factory::prototype_mac(const std::string& algo_spec, const std::string& provider) { return factory_prototype<MessageAuthenticationCode>(algo_spec, provider, engines, *this, mac_cache); } /** * Return a new block cipher cooresponding to this request */ BlockCipher* Algorithm_Factory::make_block_cipher(const std::string& algo_spec, const std::string& provider) { if(const BlockCipher* proto = prototype_block_cipher(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /** * Return a new stream cipher cooresponding to this request */ StreamCipher* Algorithm_Factory::make_stream_cipher(const std::string& algo_spec, const std::string& provider) { if(const StreamCipher* proto = prototype_stream_cipher(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /** * Return a new object cooresponding to this request */ HashFunction* Algorithm_Factory::make_hash_function(const std::string& algo_spec, const std::string& provider) { if(const HashFunction* proto = prototype_hash_function(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /** * Return a new object cooresponding to this request */ MessageAuthenticationCode* Algorithm_Factory::make_mac(const std::string& algo_spec, const std::string& provider) { if(const MessageAuthenticationCode* proto = prototype_mac(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /** * Add a new block cipher */ void Algorithm_Factory::add_block_cipher(BlockCipher* block_cipher, const std::string& provider) { block_cipher_cache.add(block_cipher, block_cipher->name(), provider); } /** * Add a new stream cipher */ void Algorithm_Factory::add_stream_cipher(StreamCipher* stream_cipher, const std::string& provider) { stream_cipher_cache.add(stream_cipher, stream_cipher->name(), provider); } /** * Add a new hash */ void Algorithm_Factory::add_hash_function(HashFunction* hash, const std::string& provider) { hash_cache.add(hash, hash->name(), provider); } /** * Add a new mac */ void Algorithm_Factory::add_mac(MessageAuthenticationCode* mac, const std::string& provider) { mac_cache.add(mac, mac->name(), provider); } } <commit_msg>Add comment about non-obvious but vital side effect<commit_after>/* Algorithm Factory (C) 2008 Jack Lloyd */ #include <botan/algo_factory.h> #include <botan/stl_util.h> #include <botan/engine.h> #include <botan/exceptn.h> #include <botan/block_cipher.h> #include <botan/stream_cipher.h> #include <botan/hash.h> #include <botan/mac.h> #include <algorithm> namespace Botan { namespace { /** * Template functions for the factory prototype/search algorithm */ template<typename T> T* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return 0; } template<> BlockCipher* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_block_cipher(request, af); } template<> StreamCipher* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_stream_cipher(request, af); } template<> HashFunction* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_hash(request, af); } template<> MessageAuthenticationCode* engine_get_algo(Engine* engine, const SCAN_Name& request, Algorithm_Factory& af) { return engine->find_mac(request, af); } template<typename T> const T* factory_prototype(const std::string& algo_spec, const std::string& provider, const std::vector<Engine*>& engines, Algorithm_Factory& af, Algorithm_Cache<T>& cache) { if(const T* cache_hit = cache.get(algo_spec, provider)) return cache_hit; SCAN_Name scan_name(algo_spec); for(u32bit i = 0; i != engines.size(); ++i) { T* impl = engine_get_algo<T>(engines[i], scan_name, af); if(impl) cache.add(impl, algo_spec, engines[i]->provider_name()); } return cache.get(algo_spec, provider); } } /** * Setup caches */ Algorithm_Factory::Algorithm_Factory(const std::vector<Engine*>& engines_in, Mutex_Factory& mf) : engines(engines_in), block_cipher_cache(mf.make()), stream_cipher_cache(mf.make()), hash_cache(mf.make()), mac_cache(mf.make()) { } /** * Delete all engines */ Algorithm_Factory::~Algorithm_Factory() { std::for_each(engines.begin(), engines.end(), del_fun<Engine>()); engines.clear(); } /** * Set the preferred provider for an algorithm */ void Algorithm_Factory::set_preferred_provider(const std::string& algo_spec, const std::string& provider) { if(prototype_block_cipher(algo_spec)) block_cipher_cache.set_preferred_provider(algo_spec, provider); else if(prototype_stream_cipher(algo_spec)) stream_cipher_cache.set_preferred_provider(algo_spec, provider); else if(prototype_hash_function(algo_spec)) hash_cache.set_preferred_provider(algo_spec, provider); else if(prototype_mac(algo_spec)) mac_cache.set_preferred_provider(algo_spec, provider); } /** * Get an engine out of the list */ Engine* Algorithm_Factory::get_engine_n(u32bit n) const { if(n >= engines.size()) return 0; return engines[n]; } /** * Return the possible providers of a request * Note: assumes you don't have different types by the same name */ std::vector<std::string> Algorithm_Factory::providers_of(const std::string& algo_spec) { /* The checks with if(prototype_X(algo_spec)) have the effect of forcing a full search, since otherwise there might not be any providers at all in the cache. */ if(prototype_block_cipher(algo_spec)) return block_cipher_cache.providers_of(algo_spec); else if(prototype_stream_cipher(algo_spec)) return stream_cipher_cache.providers_of(algo_spec); else if(prototype_hash_function(algo_spec)) return hash_cache.providers_of(algo_spec); else if(prototype_mac(algo_spec)) return mac_cache.providers_of(algo_spec); else return std::vector<std::string>(); } /** * Return the prototypical block cipher cooresponding to this request */ const BlockCipher* Algorithm_Factory::prototype_block_cipher(const std::string& algo_spec, const std::string& provider) { return factory_prototype<BlockCipher>(algo_spec, provider, engines, *this, block_cipher_cache); } /** * Return the prototypical stream cipher cooresponding to this request */ const StreamCipher* Algorithm_Factory::prototype_stream_cipher(const std::string& algo_spec, const std::string& provider) { return factory_prototype<StreamCipher>(algo_spec, provider, engines, *this, stream_cipher_cache); } /** * Return the prototypical object cooresponding to this request (if found) */ const HashFunction* Algorithm_Factory::prototype_hash_function(const std::string& algo_spec, const std::string& provider) { return factory_prototype<HashFunction>(algo_spec, provider, engines, *this, hash_cache); } /** * Return the prototypical object cooresponding to this request */ const MessageAuthenticationCode* Algorithm_Factory::prototype_mac(const std::string& algo_spec, const std::string& provider) { return factory_prototype<MessageAuthenticationCode>(algo_spec, provider, engines, *this, mac_cache); } /** * Return a new block cipher cooresponding to this request */ BlockCipher* Algorithm_Factory::make_block_cipher(const std::string& algo_spec, const std::string& provider) { if(const BlockCipher* proto = prototype_block_cipher(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /** * Return a new stream cipher cooresponding to this request */ StreamCipher* Algorithm_Factory::make_stream_cipher(const std::string& algo_spec, const std::string& provider) { if(const StreamCipher* proto = prototype_stream_cipher(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /** * Return a new object cooresponding to this request */ HashFunction* Algorithm_Factory::make_hash_function(const std::string& algo_spec, const std::string& provider) { if(const HashFunction* proto = prototype_hash_function(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /** * Return a new object cooresponding to this request */ MessageAuthenticationCode* Algorithm_Factory::make_mac(const std::string& algo_spec, const std::string& provider) { if(const MessageAuthenticationCode* proto = prototype_mac(algo_spec, provider)) return proto->clone(); throw Algorithm_Not_Found(algo_spec); } /** * Add a new block cipher */ void Algorithm_Factory::add_block_cipher(BlockCipher* block_cipher, const std::string& provider) { block_cipher_cache.add(block_cipher, block_cipher->name(), provider); } /** * Add a new stream cipher */ void Algorithm_Factory::add_stream_cipher(StreamCipher* stream_cipher, const std::string& provider) { stream_cipher_cache.add(stream_cipher, stream_cipher->name(), provider); } /** * Add a new hash */ void Algorithm_Factory::add_hash_function(HashFunction* hash, const std::string& provider) { hash_cache.add(hash, hash->name(), provider); } /** * Add a new mac */ void Algorithm_Factory::add_mac(MessageAuthenticationCode* mac, const std::string& provider) { mac_cache.add(mac, mac->name(), provider); } } <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2002 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vrj/vrjConfig.h> #include <vrj/Display/SurfaceViewport.h> #include <vrj/Display/WallProjection.h> #include <vrj/Display/TrackedWallProjection.h> #include <gmtl/Math.h> //#include <vrj/Math/Coord.h> #include <gmtl/Vec.h> #include <jccl/Config/ConfigChunk.h> #include <vrj/Kernel/User.h> #include <gadget/Type/Position/PositionUnitConversion.h> #include <gmtl/Matrix.h> #include <gmtl/MatrixOps.h> #include <gmtl/Generate.h> #include <gmtl/Xforms.h> namespace vrj { void SurfaceViewport::config(jccl::ConfigChunkPtr chunk) { vprASSERT(chunk.get() != NULL); vprASSERT(chunk->getDescToken() == std::string("surfaceViewport")); Viewport::config(chunk); // Call base class config mType = SURFACE; // Read in the corners jccl::ConfigChunkPtr ll_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",0); jccl::ConfigChunkPtr lr_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",1); jccl::ConfigChunkPtr ur_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",2); jccl::ConfigChunkPtr ul_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",3); mLLCorner.set(ll_corner_chunk->getProperty<float>("x"), ll_corner_chunk->getProperty<float>("y"), ll_corner_chunk->getProperty<float>("z")); mLRCorner.set(lr_corner_chunk->getProperty<float>("x"), lr_corner_chunk->getProperty<float>("y"), lr_corner_chunk->getProperty<float>("z")); mURCorner.set(ur_corner_chunk->getProperty<float>("x"), ur_corner_chunk->getProperty<float>("y"), ur_corner_chunk->getProperty<float>("z")); mULCorner.set(ul_corner_chunk->getProperty<float>("x"), ul_corner_chunk->getProperty<float>("y"), ul_corner_chunk->getProperty<float>("z")); // Calculate the rotation and the pts calculateSurfaceRotation(); calculateCornersInBaseFrame(); // Get info about being tracked mTracked = chunk->getProperty<bool>("tracked"); if(mTracked) { mTrackerProxyName = chunk->getProperty<std::string>("trackerproxy"); } // Create Projection objects // NOTE: The -'s are because we are measuring distance to // the left(bottom) which is opposite the normal axis direction //vjMatrix rot_inv; //rot_inv.invert(mSurfaceRotation); if(!mTracked) { mLeftProj = new WallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt], mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt]); mRightProj = new WallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt], mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt]); } else { mLeftProj = new TrackedWallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt], mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt], mTrackerProxyName); mRightProj = new TrackedWallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt], mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt], mTrackerProxyName); } // Configure the projections mLeftProj->config(chunk); mLeftProj->setEye(Projection::LEFT); mLeftProj->setViewport(this); mRightProj->config(chunk); mRightProj->setEye(Projection::RIGHT); mRightProj->setViewport(this); } void SurfaceViewport::updateProjections(const float positionScale) { gmtl::Matrix44f left_eye_pos, right_eye_pos; // NOTE: Eye coord system is -z forward, x-right, y-up // -- Calculate Eye Positions -- // gmtl::Matrix44f cur_head_pos = mUser->getHeadPosProxy()->getData(positionScale); /* Coord head_coord(cur_head_pos); // Create a user readable version vprDEBUG(vprDBG_ALL,5) << "vjDisplay::updateProjections: Getting head position" << std::endl << vprDEBUG_FLUSH; vprDEBUG(vprDBG_ALL,5) << "\tHeadPos:" << head_coord.pos << "\tHeadOr:" << head_coord.orient << std::endl << vprDEBUG_FLUSH; */ // Compute location of left and right eyes //float interocularDist = 2.75f/12.0f; float interocular_dist = mUser->getInterocularDistance(); interocular_dist *= positionScale; // Scale eye separation float eye_offset = interocular_dist/2.0f; // Distance to move eye left_eye_pos = cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f( -eye_offset, 0, 0)); right_eye_pos = cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f(eye_offset, 0, 0)); mLeftProj->calcViewMatrix(left_eye_pos, positionScale); mRightProj->calcViewMatrix(right_eye_pos, positionScale); } void SurfaceViewport::calculateSurfaceRotation() { assertPtsLegal(); // Find the base vectors for the surface axiis (in terms of the base coord system) // With z out, x to the right, and y up gmtl::Vec3f x_base, y_base, z_base; x_base = (mLRCorner-mLLCorner); y_base = (mURCorner-mLRCorner); gmtl::cross( z_base, x_base, y_base); // They must be normalized gmtl::normalize(x_base); gmtl::normalize(y_base); gmtl::normalize(z_base); // Calculate the surfaceRotMat using law of cosines mSurfaceRotation = gmtl::makeDirCos<gmtl::Matrix44f>(x_base, y_base, z_base ); //mSurfaceRotation.makeDirCos(x_base,y_base,z_base); // surfMbase //mSurfaceRotation.invert(mSurfRotInv); // baseMsurf } void SurfaceViewport::calculateCornersInBaseFrame() { mxLLCorner = mSurfaceRotation * mLLCorner; mxLRCorner = mSurfaceRotation * mLRCorner; mxURCorner = mSurfaceRotation * mURCorner; mxULCorner = mSurfaceRotation * mULCorner; // Verify that they are all in the same x,y plane vprDEBUG(vprDBG_ALL, vprDBG_HVERB_LVL) << std::setprecision(10) << mxLLCorner[gmtl::Zelt] << " " << mxLRCorner[gmtl::Zelt] << " " << mxURCorner[gmtl::Zelt] << " " << mxULCorner[gmtl::Zelt] << "\n" << vprDEBUG_FLUSH; #ifdef VJ_DEBUG const float epsilon = 1e-6; #endif vprASSERT(gmtl::Math::isEqual(mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Zelt], epsilon) && gmtl::Math::isEqual(mxURCorner[gmtl::Zelt], mxULCorner[gmtl::Zelt], epsilon) && gmtl::Math::isEqual(mxLLCorner[gmtl::Zelt], mxULCorner[gmtl::Zelt], epsilon)); } }; <commit_msg>Updated for bug fix in GMTL.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2002 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vrj/vrjConfig.h> #include <vrj/Display/SurfaceViewport.h> #include <vrj/Display/WallProjection.h> #include <vrj/Display/TrackedWallProjection.h> #include <gmtl/Math.h> //#include <vrj/Math/Coord.h> #include <gmtl/Vec.h> #include <jccl/Config/ConfigChunk.h> #include <vrj/Kernel/User.h> #include <gadget/Type/Position/PositionUnitConversion.h> #include <gmtl/Matrix.h> #include <gmtl/MatrixOps.h> #include <gmtl/Generate.h> #include <gmtl/Xforms.h> namespace vrj { void SurfaceViewport::config(jccl::ConfigChunkPtr chunk) { vprASSERT(chunk.get() != NULL); vprASSERT(chunk->getDescToken() == std::string("surfaceViewport")); Viewport::config(chunk); // Call base class config mType = SURFACE; // Read in the corners jccl::ConfigChunkPtr ll_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",0); jccl::ConfigChunkPtr lr_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",1); jccl::ConfigChunkPtr ur_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",2); jccl::ConfigChunkPtr ul_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",3); mLLCorner.set(ll_corner_chunk->getProperty<float>("x"), ll_corner_chunk->getProperty<float>("y"), ll_corner_chunk->getProperty<float>("z")); mLRCorner.set(lr_corner_chunk->getProperty<float>("x"), lr_corner_chunk->getProperty<float>("y"), lr_corner_chunk->getProperty<float>("z")); mURCorner.set(ur_corner_chunk->getProperty<float>("x"), ur_corner_chunk->getProperty<float>("y"), ur_corner_chunk->getProperty<float>("z")); mULCorner.set(ul_corner_chunk->getProperty<float>("x"), ul_corner_chunk->getProperty<float>("y"), ul_corner_chunk->getProperty<float>("z")); // Calculate the rotation and the pts calculateSurfaceRotation(); calculateCornersInBaseFrame(); // Get info about being tracked mTracked = chunk->getProperty<bool>("tracked"); if(mTracked) { mTrackerProxyName = chunk->getProperty<std::string>("trackerproxy"); } // Create Projection objects // NOTE: The -'s are because we are measuring distance to // the left(bottom) which is opposite the normal axis direction //vjMatrix rot_inv; //rot_inv.invert(mSurfaceRotation); if(!mTracked) { mLeftProj = new WallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt], mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt]); mRightProj = new WallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt], mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt]); } else { mLeftProj = new TrackedWallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt], mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt], mTrackerProxyName); mRightProj = new TrackedWallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt], mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt], mTrackerProxyName); } // Configure the projections mLeftProj->config(chunk); mLeftProj->setEye(Projection::LEFT); mLeftProj->setViewport(this); mRightProj->config(chunk); mRightProj->setEye(Projection::RIGHT); mRightProj->setViewport(this); } void SurfaceViewport::updateProjections(const float positionScale) { gmtl::Matrix44f left_eye_pos, right_eye_pos; // NOTE: Eye coord system is -z forward, x-right, y-up // -- Calculate Eye Positions -- // gmtl::Matrix44f cur_head_pos = mUser->getHeadPosProxy()->getData(positionScale); /* Coord head_coord(cur_head_pos); // Create a user readable version vprDEBUG(vprDBG_ALL,5) << "vjDisplay::updateProjections: Getting head position" << std::endl << vprDEBUG_FLUSH; vprDEBUG(vprDBG_ALL,5) << "\tHeadPos:" << head_coord.pos << "\tHeadOr:" << head_coord.orient << std::endl << vprDEBUG_FLUSH; */ // Compute location of left and right eyes //float interocularDist = 2.75f/12.0f; float interocular_dist = mUser->getInterocularDistance(); interocular_dist *= positionScale; // Scale eye separation float eye_offset = interocular_dist/2.0f; // Distance to move eye left_eye_pos = cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f( -eye_offset, 0, 0)); right_eye_pos = cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f(eye_offset, 0, 0)); mLeftProj->calcViewMatrix(left_eye_pos, positionScale); mRightProj->calcViewMatrix(right_eye_pos, positionScale); } void SurfaceViewport::calculateSurfaceRotation() { assertPtsLegal(); // Find the base vectors for the surface axiis (in terms of the base coord system) // With z out, x to the right, and y up gmtl::Vec3f x_base, y_base, z_base; x_base = (mLRCorner-mLLCorner); y_base = (mURCorner-mLRCorner); gmtl::cross( z_base, x_base, y_base); // They must be normalized gmtl::normalize(x_base); gmtl::normalize(y_base); gmtl::normalize(z_base); // Calculate the surfaceRotMat using law of cosines mSurfaceRotation = gmtl::makeDirCos<gmtl::Matrix44f>(x_base, y_base, z_base ); gmtl::invert(mSurfaceRotation); //mSurfaceRotation.makeDirCos(x_base,y_base,z_base); // surfMbase //mSurfaceRotation.invert(mSurfRotInv); // baseMsurf } void SurfaceViewport::calculateCornersInBaseFrame() { mxLLCorner = mSurfaceRotation * mLLCorner; mxLRCorner = mSurfaceRotation * mLRCorner; mxURCorner = mSurfaceRotation * mURCorner; mxULCorner = mSurfaceRotation * mULCorner; // Verify that they are all in the same x,y plane vprDEBUG(vprDBG_ALL, vprDBG_HVERB_LVL) << std::setprecision(10) << mxLLCorner[gmtl::Zelt] << " " << mxLRCorner[gmtl::Zelt] << " " << mxURCorner[gmtl::Zelt] << " " << mxULCorner[gmtl::Zelt] << "\n" << vprDEBUG_FLUSH; #ifdef VJ_DEBUG const float epsilon = 1e-6; #endif vprASSERT(gmtl::Math::isEqual(mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Zelt], epsilon) && gmtl::Math::isEqual(mxURCorner[gmtl::Zelt], mxULCorner[gmtl::Zelt], epsilon) && gmtl::Math::isEqual(mxLLCorner[gmtl::Zelt], mxULCorner[gmtl::Zelt], epsilon)); } }; <|endoftext|>
<commit_before>#include "main.h" #include "im.h" using namespace eigengo::akka; Main::Main(const std::string queue, const std::string exchange, const std::string routingKey) : RabbitRpcServer::RabbitRpcServer(queue, exchange, routingKey) { } std::string Main::handleMessage(const AmqpClient::BasicMessage::ptr_t message, const AmqpClient::Channel::ptr_t channel) { ImageMessage imageMessage(message); auto image = imageMessage.headImage(); return "foo"; } int main(int argc, char** argv) { Main main("recog", "amq.direct", "recog.key"); main.runAndJoin(8); return 0; }<commit_msg>Native processing<commit_after>#include "main.h" #include "im.h" using namespace eigengo::akka; Main::Main(const std::string queue, const std::string exchange, const std::string routingKey) : RabbitRpcServer::RabbitRpcServer(queue, exchange, routingKey) { } std::string Main::handleMessage(const AmqpClient::BasicMessage::ptr_t message, const AmqpClient::Channel::ptr_t channel) { ImageMessage imageMessage(message); auto image = imageMessage.headImage(); Jzon::Object root; root.add("accepted", true); Jzon::Writer writer(root, Jzon::NoFormat); writer.Write(); return writer.GetResult(); } int main(int argc, char** argv) { Main main("recog", "amq.direct", "recog.key"); main.runAndJoin(8); return 0; }<|endoftext|>
<commit_before>/******************************************************************************* * tests/core/post_hash_table_test.cpp * * Part of Project c7a. * * Copyright (C) 2015 Matthias Stumpp <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <c7a/core/reduce_post_table.hpp> #include <gtest/gtest.h> #include <string> #include <utility> #include <vector> #include <c7a/net/manager.hpp> using namespace c7a::data; using namespace c7a::net; struct PostTable : public::testing::Test {}; std::pair<int, int> pair(int ele) { return std::make_pair(ele, ele); } template <typename Key, typename HashFunction = std::hash<Key> > class CustomKeyHashFunction : public c7a::core::PostReduceByHashKey<int> { public: CustomKeyHashFunction(const HashFunction& hash_function = HashFunction()) : hash_function_(hash_function) { } template <typename ReducePostTable> typename ReducePostTable::index_result operator () (Key v, ReducePostTable* ht) const { using index_result = typename ReducePostTable::index_result; size_t global_index = v / 2; return index_result(global_index); } private: HashFunction hash_function_; }; TEST_F(PostTable, CustomHashFunction) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); CustomKeyHashFunction<int> cust_hash; c7a::core::PostReduceFlushToDefault flush_func; c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn), false, c7a::core::PostReduceFlushToDefault, CustomKeyHashFunction<int>> table(key_ex, red_fn, emitters, cust_hash, flush_func); ASSERT_EQ(0u, writer1.size()); ASSERT_EQ(0u, table.NumItems()); for (int i = 0; i < 16; i++) { table.Insert(std::move(pair(i))); } ASSERT_EQ(0u, writer1.size()); ASSERT_EQ(16u, table.NumItems()); table.Flush(); ASSERT_EQ(16u, writer1.size()); ASSERT_EQ(0u, table.NumItems()); } TEST_F(PostTable, AddIntegers) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(pair(1)); table.Insert(pair(2)); table.Insert(pair(3)); ASSERT_EQ(3u, table.NumItems()); table.Insert(pair(2)); ASSERT_EQ(3u, table.NumItems()); } TEST_F(PostTable, CreateEmptyTable) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); ASSERT_EQ(0u, table.NumItems()); } TEST_F(PostTable, FlushIntegers) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(pair(1)); table.Insert(pair(2)); table.Insert(pair(3)); ASSERT_EQ(3u, table.NumItems()); table.Flush(); ASSERT_EQ(3u, writer1.size()); ASSERT_EQ(0u, table.NumItems()); table.Insert(pair(1)); ASSERT_EQ(1u, table.NumItems()); } TEST_F(PostTable, FlushIntegersInSequence) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(pair(1)); table.Insert(pair(2)); table.Insert(pair(3)); ASSERT_EQ(3u, table.NumItems()); table.Flush(); ASSERT_EQ(3u, writer1.size()); ASSERT_EQ(0u, table.NumItems()); table.Insert(pair(1)); ASSERT_EQ(1u, table.NumItems()); } TEST_F(PostTable, DISABLED_MultipleEmitters) { std::vector<int> vec1; auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; std::vector<int> writer2; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); emitters.push_back([&writer2](const int value) { writer2.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(pair(1)); table.Insert(pair(2)); table.Insert(pair(3)); ASSERT_EQ(3u, table.NumItems()); table.Flush(); ASSERT_EQ(0u, table.NumItems()); ASSERT_EQ(3u, writer1.size()); ASSERT_EQ(3u, writer2.size()); table.Insert(pair(1)); ASSERT_EQ(1u, table.NumItems()); } TEST_F(PostTable, ComplexType) { using StringPair = std::pair<std::string, int>; auto key_ex = [](StringPair in) { return in.first; }; auto red_fn = [](StringPair in1, StringPair in2) { return std::make_pair(in1.first, in1.second + in2.second); }; typedef std::function<void (const StringPair&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<StringPair> writer1; emitters.push_back([&writer1](const StringPair value) { writer1.push_back(value); }); c7a::core::ReducePostTable<StringPair, std::string, StringPair, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(std::make_pair("hallo", std::make_pair("hallo", 1))); table.Insert(std::make_pair("hello", std::make_pair("hello", 2))); table.Insert(std::make_pair("bonjour", std::make_pair("bonjour", 3))); ASSERT_EQ(3u, table.NumItems()); table.Insert(std::make_pair("hello", std::make_pair("hello", 5))); ASSERT_EQ(3u, table.NumItems()); table.Insert(std::make_pair("baguette", std::make_pair("baguette", 42))); ASSERT_EQ(4u, table.NumItems()); } // TODO(ms): add one test with a for loop inserting 10000 items. -> trigger /******************************************************************************/ <commit_msg>enabled test<commit_after>/******************************************************************************* * tests/core/post_hash_table_test.cpp * * Part of Project c7a. * * Copyright (C) 2015 Matthias Stumpp <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <c7a/core/reduce_post_table.hpp> #include <gtest/gtest.h> #include <string> #include <utility> #include <vector> #include <c7a/net/manager.hpp> using namespace c7a::data; using namespace c7a::net; struct PostTable : public::testing::Test {}; std::pair<int, int> pair(int ele) { return std::make_pair(ele, ele); } template <typename Key, typename HashFunction = std::hash<Key> > class CustomKeyHashFunction : public c7a::core::PostReduceByHashKey<int> { public: CustomKeyHashFunction(const HashFunction& hash_function = HashFunction()) : hash_function_(hash_function) { } template <typename ReducePostTable> typename ReducePostTable::index_result operator () (Key v, ReducePostTable* ht) const { using index_result = typename ReducePostTable::index_result; size_t global_index = v / 2; return index_result(global_index); } private: HashFunction hash_function_; }; TEST_F(PostTable, CustomHashFunction) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); CustomKeyHashFunction<int> cust_hash; c7a::core::PostReduceFlushToDefault flush_func; c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn), false, c7a::core::PostReduceFlushToDefault, CustomKeyHashFunction<int>> table(key_ex, red_fn, emitters, cust_hash, flush_func); ASSERT_EQ(0u, writer1.size()); ASSERT_EQ(0u, table.NumItems()); for (int i = 0; i < 16; i++) { table.Insert(std::move(pair(i))); } ASSERT_EQ(0u, writer1.size()); ASSERT_EQ(16u, table.NumItems()); table.Flush(); ASSERT_EQ(16u, writer1.size()); ASSERT_EQ(0u, table.NumItems()); } TEST_F(PostTable, AddIntegers) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(pair(1)); table.Insert(pair(2)); table.Insert(pair(3)); ASSERT_EQ(3u, table.NumItems()); table.Insert(pair(2)); ASSERT_EQ(3u, table.NumItems()); } TEST_F(PostTable, CreateEmptyTable) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); ASSERT_EQ(0u, table.NumItems()); } TEST_F(PostTable, FlushIntegers) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(pair(1)); table.Insert(pair(2)); table.Insert(pair(3)); ASSERT_EQ(3u, table.NumItems()); table.Flush(); ASSERT_EQ(3u, writer1.size()); ASSERT_EQ(0u, table.NumItems()); table.Insert(pair(1)); ASSERT_EQ(1u, table.NumItems()); } TEST_F(PostTable, FlushIntegersInSequence) { auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(pair(1)); table.Insert(pair(2)); table.Insert(pair(3)); ASSERT_EQ(3u, table.NumItems()); table.Flush(); ASSERT_EQ(3u, writer1.size()); ASSERT_EQ(0u, table.NumItems()); table.Insert(pair(1)); ASSERT_EQ(1u, table.NumItems()); } TEST_F(PostTable, MultipleEmitters) { std::vector<int> vec1; auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; typedef std::function<void (const int&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<int> writer1; std::vector<int> writer2; emitters.push_back([&writer1](const int value) { writer1.push_back(value); }); emitters.push_back([&writer2](const int value) { writer2.push_back(value); }); c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(pair(1)); table.Insert(pair(2)); table.Insert(pair(3)); ASSERT_EQ(3u, table.NumItems()); table.Flush(); ASSERT_EQ(0u, table.NumItems()); ASSERT_EQ(3u, writer1.size()); ASSERT_EQ(3u, writer2.size()); table.Insert(pair(1)); ASSERT_EQ(1u, table.NumItems()); } TEST_F(PostTable, ComplexType) { using StringPair = std::pair<std::string, int>; auto key_ex = [](StringPair in) { return in.first; }; auto red_fn = [](StringPair in1, StringPair in2) { return std::make_pair(in1.first, in1.second + in2.second); }; typedef std::function<void (const StringPair&)> EmitterFunction; std::vector<EmitterFunction> emitters; std::vector<StringPair> writer1; emitters.push_back([&writer1](const StringPair value) { writer1.push_back(value); }); c7a::core::ReducePostTable<StringPair, std::string, StringPair, decltype(key_ex), decltype(red_fn)> table(key_ex, red_fn, emitters); table.Insert(std::make_pair("hallo", std::make_pair("hallo", 1))); table.Insert(std::make_pair("hello", std::make_pair("hello", 2))); table.Insert(std::make_pair("bonjour", std::make_pair("bonjour", 3))); ASSERT_EQ(3u, table.NumItems()); table.Insert(std::make_pair("hello", std::make_pair("hello", 5))); ASSERT_EQ(3u, table.NumItems()); table.Insert(std::make_pair("baguette", std::make_pair("baguette", 42))); ASSERT_EQ(4u, table.NumItems()); } // TODO(ms): add one test with a for loop inserting 10000 items. -> trigger /******************************************************************************/ <|endoftext|>
<commit_before>#include <iostream> #include "Cluster.h" #include "utils.h" #include "numerics.h" #include "RandomNumberGenerator.h" #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> using namespace std; bool is_almost(double val1, double val2, double precision) { return abs(val1-val2) < precision; } int main(int argc, char** argv) { cout << "Begin:: test_cluster" << endl; RandomNumberGenerator rng; double sum_sum_score_deltas; boost::numeric::ublas::matrix<double> Data; LoadData("SynData2.csv", Data); // std::cout << Data << std::endl; Cluster<double> cd(5); //hard code # columns std::cout << std::endl << "Init cluster" << std::endl; std::cout << cd << std::endl; sum_sum_score_deltas = 0; for(int i=0; i < 4; i++) { std::vector<double> V; for(int j=0;j < Data.size2(); j++) { V.push_back(Data(i,j)); } sum_sum_score_deltas += cd.insert_row(V, i); } std::cout << std::endl << "modified cluster" << std::endl; std::cout << cd << std::endl; std::cout << "sum_sum_score_deltas: " << sum_sum_score_deltas << std::endl; std::cout << std::endl << "logps" << std::endl; std::cout << cd.calc_logps() << std::endl;; std::cout << std::endl << "sum logp" << std::endl; std::cout << cd.calc_sum_logp() << std::endl;; // sum_sum_score_deltas = 0; for(int i=4; i < 8; i++) { std::vector<double> V; for(int j=0;j < Data.size2(); j++) { V.push_back(Data(i,j)); } sum_sum_score_deltas += cd.insert_row(V, i); } std::cout << std::endl << "modified cluster" << std::endl; std::cout << cd << std::endl; std::cout << "sum_sum_score_deltas: " << sum_sum_score_deltas << std::endl; std::cout << std::endl << "logps" << std::endl; std::cout << cd.calc_logps() << std::endl;; std::cout << std::endl << "sum logp" << std::endl; std::cout << cd.calc_sum_logp() << std::endl;; // int i = 8; std::vector<double> V; for(int j=0;j<Data.size2(); j++) { V.push_back(Data(i,j)); } double vector_logp = cd.get_vector_logp(V); std::cout << "add vector with vector_logp" << std::endl; std::cout << vector_logp << std::endl; std::cout << "calc_data_logp() is result" << std::endl; std::cout << cd.calc_data_logp(V) << std::endl; cd.insert_row(V, i); std::cout << std::endl << "modified cluster" << std::endl; std::cout << cd << std::endl; std::cout << "remove vector" << std::endl; cd.remove_row(V, i); std::cout << std::endl << "modified cluster" << std::endl; std::cout << cd << std::endl; // std::cout << "calculate logps from scratch" << std::endl; std::cout << std::endl << "logps" << std::endl; std::cout << cd.calc_logps() << std::endl;; std::cout << std::endl << "sum logp" << std::endl; std::cout << cd.calc_sum_logp() << std::endl;; print_defaults(); std::cout << "show use of underlying numerics functions" << std::endl; std::cout << "calc_continuous_logp(0, 1, 2, 2, 0)" << std::endl; std::cout << numerics::calc_continuous_logp(0, 1, 2, 2, 0) << std::endl; std::cout << "calc_cluster_crp_logp(10, 100, 10)" << std::endl; std::cout << numerics::calc_cluster_crp_logp(10, 100, 10) << std::endl; // std::cout << "numerics::calc_cluster_vector_joint_logp(cd, V)" << std::endl; // std::cout << numerics::calc_cluster_vector_joint_logp(cd, V) << std::endl; cout << "Stop:: test_cluster" << endl; } <commit_msg>add test of equivalence of a cluster with separate suffstats<commit_after>#include <iostream> #include "Cluster.h" #include "utils.h" #include "numerics.h" #include "RandomNumberGenerator.h" #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> using namespace std; bool is_almost(double val1, double val2, double precision) { return abs(val1-val2) < precision; } int main(int argc, char** argv) { cout << "Begin:: test_cluster" << endl; RandomNumberGenerator rng; int max_value = 20; int num_rows = 3; int num_cols = 3; Cluster<double> cd(num_cols); vector<Suffstats<double> > sd_v; for(int row_idx=0; row_idx<num_rows; row_idx++) { Suffstats<double> sd; sd_v.push_back(sd); } for(int row_idx=0; row_idx<num_rows; row_idx++) { vector<double> row_data; for(int col_idx=0; col_idx<num_cols; col_idx++) { double new_value = (rng.nexti(max_value) + 1) * rng.next(); sd_v[col_idx].insert_el(new_value); row_data.push_back(new_value); } cd.insert_row(row_data, row_idx); } vector<double> score_v; double sum_scores = 0; for(int col_idx=0; col_idx<num_cols; col_idx++) { double suff_score = sd_v[col_idx].get_score(); score_v.push_back(suff_score); sum_scores += suff_score; } cout << "vector off separate suffstats scores: " << score_v << endl; cout << "sum separate scores: " << sum_scores << endl; cout << "Cluster score with same data: " << cd.get_score() << endl; cout << endl; // assert(is_almost(sum_scores, cd.get_score(), 1E-10)); double sum_sum_score_deltas; boost::numeric::ublas::matrix<double> Data; LoadData("SynData2.csv", Data); // std::cout << Data << std::endl; cd = Cluster<double>(5); //hard code # columns std::cout << std::endl << "Init cluster" << std::endl; std::cout << cd << std::endl; sum_sum_score_deltas = 0; for(int i=0; i < 4; i++) { std::vector<double> V; for(int j=0;j < Data.size2(); j++) { V.push_back(Data(i,j)); } sum_sum_score_deltas += cd.insert_row(V, i); } std::cout << std::endl << "modified cluster" << std::endl; std::cout << cd << std::endl; std::cout << "sum_sum_score_deltas: " << sum_sum_score_deltas << std::endl; std::cout << std::endl << "logps" << std::endl; std::cout << cd.calc_logps() << std::endl;; std::cout << std::endl << "sum logp" << std::endl; std::cout << cd.calc_sum_logp() << std::endl;; // sum_sum_score_deltas = 0; for(int i=4; i < 8; i++) { std::vector<double> V; for(int j=0;j < Data.size2(); j++) { V.push_back(Data(i,j)); } sum_sum_score_deltas += cd.insert_row(V, i); } std::cout << std::endl << "modified cluster" << std::endl; std::cout << cd << std::endl; std::cout << "sum_sum_score_deltas: " << sum_sum_score_deltas << std::endl; std::cout << std::endl << "logps" << std::endl; std::cout << cd.calc_logps() << std::endl;; std::cout << std::endl << "sum logp" << std::endl; std::cout << cd.calc_sum_logp() << std::endl;; // int i = 8; std::vector<double> V; for(int j=0;j<Data.size2(); j++) { V.push_back(Data(i,j)); } double vector_logp = cd.get_vector_logp(V); std::cout << "add vector with vector_logp" << std::endl; std::cout << vector_logp << std::endl; std::cout << "calc_data_logp() is result" << std::endl; std::cout << cd.calc_data_logp(V) << std::endl; cd.insert_row(V, i); std::cout << std::endl << "modified cluster" << std::endl; std::cout << cd << std::endl; std::cout << "remove vector" << std::endl; cd.remove_row(V, i); std::cout << std::endl << "modified cluster" << std::endl; std::cout << cd << std::endl; // std::cout << "calculate logps from scratch" << std::endl; std::cout << std::endl << "logps" << std::endl; std::cout << cd.calc_logps() << std::endl;; std::cout << std::endl << "sum logp" << std::endl; std::cout << cd.calc_sum_logp() << std::endl;; print_defaults(); std::cout << "show use of underlying numerics functions" << std::endl; std::cout << "calc_continuous_logp(0, 1, 2, 2, 0)" << std::endl; std::cout << numerics::calc_continuous_logp(0, 1, 2, 2, 0) << std::endl; std::cout << "calc_cluster_crp_logp(10, 100, 10)" << std::endl; std::cout << numerics::calc_cluster_crp_logp(10, 100, 10) << std::endl; // std::cout << "numerics::calc_cluster_vector_joint_logp(cd, V)" << std::endl; // std::cout << numerics::calc_cluster_vector_joint_logp(cd, V) << std::endl; cout << "Stop:: test_cluster" << endl; } <|endoftext|>
<commit_before>// Copyright (c) 2012-2013 The PPCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "kernel.h" #include "txdb.h" using namespace std; typedef std::map<int, unsigned int> MapModifierCheckpoints; // Hard checkpoints of stake modifiers to ensure they are deterministic static std::map<int, unsigned int> mapStakeModifierCheckpoints = boost::assign::map_list_of ( 0, 0x0e00670bu ) ; // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet) static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet = boost::assign::map_list_of ( 0, 0x0e00670bu ) ; // Get time weight int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd) { // Kernel hash weight starts from 0 at the min age // this change increases active coins participating the hash and helps // to secure the network when proof-of-stake difficulty is low return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64_t)nStakeMaxAge); } // Get the last stake modifier and its generation time from a given block static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime) { if (!pindex) return error("GetLastStakeModifier: null pindex"); while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier()) pindex = pindex->pprev; if (!pindex->GeneratedStakeModifier()) return error("GetLastStakeModifier: no generation at genesis block"); nStakeModifier = pindex->nStakeModifier; nModifierTime = pindex->GetBlockTime(); return true; } // Get selection interval section (in seconds) static int64_t GetStakeModifierSelectionIntervalSection(int nSection) { assert (nSection >= 0 && nSection < 64); return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)))); } // Get stake modifier selection interval (in seconds) static int64_t GetStakeModifierSelectionInterval() { int64_t nSelectionInterval = 0; for (int nSection=0; nSection<64; nSection++) nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection); return nSelectionInterval; } // select a block from the candidate blocks in vSortedByTimestamp, excluding // already selected blocks in vSelectedBlocks, and with timestamp up to // nSelectionIntervalStop. static bool SelectBlockFromCandidates(vector<pair<int64_t, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks, int64_t nSelectionIntervalStop, uint64_t nStakeModifierPrev, const CBlockIndex** pindexSelected) { bool fSelected = false; uint256 hashBest = 0; *pindexSelected = (const CBlockIndex*) 0; BOOST_FOREACH(const PAIRTYPE(int64_t, uint256)& item, vSortedByTimestamp) { if (!mapBlockIndex.count(item.second)) return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str()); const CBlockIndex* pindex = mapBlockIndex[item.second]; if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop) break; if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0) continue; // compute the selection hash by hashing its proof-hash and the // previous proof-of-stake modifier CDataStream ss(SER_GETHASH, 0); ss << pindex->hashProof << nStakeModifierPrev; uint256 hashSelection = Hash(ss.begin(), ss.end()); // the selection hash is divided by 2**32 so that proof-of-stake block // is always favored over proof-of-work block. this is to preserve // the energy efficiency property if (pindex->IsProofOfStake()) hashSelection >>= 32; if (fSelected && hashSelection < hashBest) { hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } else if (!fSelected) { fSelected = true; hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } } if (fDebug && GetBoolArg("-printstakemodifier")) printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str()); return fSelected; } // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. // Stake modifier consists of bits each of which is contributed from a // selected block of a given block group in the past. // The selection of a block is based on a hash of the block's proof-hash and // the previous stake modifier. // Stake modifier is recomputed at a fixed time interval instead of every // block. This is to make it difficult for an attacker to gain control of // additional bits in the stake modifier, even after generating a chain of // blocks. bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier) { nStakeModifier = 0; fGeneratedStakeModifier = false; if (!pindexPrev) { fGeneratedStakeModifier = true; return true; // genesis block's modifier is 0 } // First find current stake modifier and its generation block time // if it's not old enough, return the same stake modifier int64_t nModifierTime = 0; if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime)) return error("ComputeNextStakeModifier: unable to get last modifier"); if (fDebug) { printf("ComputeNextStakeModifier: prev modifier=0x%016"PRIx64" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str()); } if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval) return true; // Sort candidate blocks by timestamp vector<pair<int64_t, uint256> > vSortedByTimestamp; vSortedByTimestamp.reserve(64 * nModifierInterval / nTargetSpacing); int64_t nSelectionInterval = GetStakeModifierSelectionInterval(); int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval; const CBlockIndex* pindex = pindexPrev; while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) { vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash())); pindex = pindex->pprev; } int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0; reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); // Select 64 blocks from candidate blocks to generate stake modifier uint64_t nStakeModifierNew = 0; int64_t nSelectionIntervalStop = nSelectionIntervalStart; map<uint256, const CBlockIndex*> mapSelectedBlocks; for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++) { // add an interval section to the current selection round nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound); // select a block from the candidates of current round if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex)) return error("ComputeNextStakeModifier: unable to select block at round %d", nRound); // write the entropy bit of the selected block nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound); // add the selected block from candidates to selected list mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex)); if (fDebug && GetBoolArg("-printstakemodifier")) printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit()); } // Print selection map for visualization of the selected blocks if (fDebug && GetBoolArg("-printstakemodifier")) { string strSelectionMap = ""; // '-' indicates proof-of-work blocks not selected strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-'); pindex = pindexPrev; while (pindex && pindex->nHeight >= nHeightFirstCandidate) { // '=' indicates proof-of-stake blocks not selected if (pindex->IsProofOfStake()) strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "="); pindex = pindex->pprev; } BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks) { // 'S' indicates selected proof-of-stake blocks // 'W' indicates selected proof-of-work blocks strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W"); } printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str()); } if (fDebug) { printf("ComputeNextStakeModifier: new modifier=0x%016"PRIx64" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str()); } nStakeModifier = nStakeModifierNew; fGeneratedStakeModifier = true; return true; } // The stake modifier used to hash for a stake kernel is chosen as the stake // modifier about a selection interval later than the coin generating the kernel static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake) { nStakeModifier = 0; if (!mapBlockIndex.count(hashBlockFrom)) return error("GetKernelStakeModifier() : block not indexed"); const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom]; nStakeModifierHeight = pindexFrom->nHeight; nStakeModifierTime = pindexFrom->GetBlockTime(); int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval(); const CBlockIndex* pindex = pindexFrom; // loop to find the stake modifier later by a selection interval while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) { if (!pindex->pnext) { // reached best block; may happen if node is behind on block chain if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime())) return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s", pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str()); else return false; } pindex = pindex->pnext; if (pindex->GeneratedStakeModifier()) { nStakeModifierHeight = pindex->nHeight; nStakeModifierTime = pindex->GetBlockTime(); } } nStakeModifier = pindex->nStakeModifier; return true; } // ppcoin kernel protocol // coinstake must meet hash target according to the protocol: // kernel (input 0) must meet the formula // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight // this ensures that the chance of getting a coinstake is proportional to the // amount of coin age one owns. // The reason this hash is chosen is the following: // nStakeModifier: scrambles computation to make it very difficult to precompute // future proof-of-stake at the time of the coin's confirmation // txPrev.block.nTime: prevent nodes from guessing a good timestamp to // generate transaction for future advantage // txPrev.offset: offset of txPrev inside block, to reduce the chance of // nodes generating coinstake at the same time // txPrev.nTime: reduce the chance of nodes generating coinstake at the same // time // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes // generating coinstake at the same time // block/tx hash should not be used here as they can be generated in vast // quantities so as to generate blocks faster, degrading the system back into // a proof-of-work situation. // bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake) { if (nTimeTx < txPrev.nTime) // Transaction timestamp violation return error("CheckStakeKernelHash() : nTime violation"); unsigned int nTimeBlockFrom = blockFrom.GetBlockTime(); if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement return error("CheckStakeKernelHash() : min age violation"); CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); int64_t nValueIn = txPrev.vout[prevout.n].nValue; uint256 hashBlockFrom = blockFrom.GetHash(); CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)txPrev.nTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60); targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256(); // Calculate hash CDataStream ss(SER_GETHASH, 0); uint64_t nStakeModifier = 0; int nStakeModifierHeight = 0; int64_t nStakeModifierTime = 0; if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake)) return false; ss << nStakeModifier; ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx; hashProofOfStake = Hash(ss.begin(), ss.end()); if (fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRIx64" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : check modifier=0x%016"PRIx64" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } // Now check if proof-of-stake hash meets target protocol if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay) return false; if (fDebug && !fPrintProofOfStake) { printf("CheckStakeKernelHash() : using modifier 0x%016"PRIx64" at height=%d timestamp=%s for block from height=%d timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime).c_str(), mapBlockIndex[hashBlockFrom]->nHeight, DateTimeStrFormat(blockFrom.GetBlockTime()).c_str()); printf("CheckStakeKernelHash() : pass modifier=0x%016"PRIx64" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString().c_str()); } return true; } // Check kernel hash target and coinstake signature bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake) { if (!tx.IsCoinStake()) return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str()); // Kernel (input 0) must match the stake hash target per coin age (nBits) const CTxIn& txin = tx.vin[0]; // First try finding the previous transaction in database CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download // Verify signature if (!VerifySignature(txPrev, tx, 0, 0)) return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str())); // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug)) return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync return true; } // Check whether the coinstake timestamp meets protocol bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx) { // v0.3 protocol return (nTimeBlock == nTimeTx); } // Get stake modifier checksum unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex) { assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); // Hash previous checksum with flags, hashProofOfStake and nStakeModifier CDataStream ss(SER_GETHASH, 0); if (pindex->pprev) ss << pindex->pprev->nStakeModifierChecksum; ss << pindex->nFlags << (pindex->IsProofOfStake() ? pindex->hashProof : 0) << pindex->nStakeModifier; uint256 hashChecksum = Hash(ss.begin(), ss.end()); hashChecksum >>= (256 - 32); return hashChecksum.Get64(); } // Check stake modifier hard checkpoints bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum) { MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints); if (checkpoints.count(nHeight)) return nStakeModifierChecksum == checkpoints[nHeight]; return true; } <commit_msg>Delete kernel.cpp<commit_after><|endoftext|>
<commit_before>#include "private/qhttpclient_private.hpp" #include <QTimerEvent> /////////////////////////////////////////////////////////////////////////////// namespace qhttp { namespace client { /////////////////////////////////////////////////////////////////////////////// QHttpClient::QHttpClient(QObject *parent) : QTcpSocket(parent), d_ptr(new QHttpClientPrivate(this)) { d_ptr->initialize(); QHTTP_LINE_LOG } QHttpClient::QHttpClient(QHttpClientPrivate &dd, QObject *parent) : QTcpSocket(parent), d_ptr(&dd) { d_ptr->initialize(); QHTTP_LINE_LOG } QHttpClient::~QHttpClient() { QHTTP_LINE_LOG } quint32 QHttpClient::timeOut() const { return d_func()->itimeOut; } void QHttpClient::setTimeOut(quint32 t) { d_func()->itimeOut = t; } bool QHttpClient::isOpen() const { return QTcpSocket::isOpen() && state() == QTcpSocket::ConnectedState; } bool QHttpClient::request(THttpMethod method, QUrl url, const TRequstHandler &reqHandler, const TResponseHandler &resHandler) { Q_D(QHttpClient); d->ireqHandler = nullptr; d->irespHandler = nullptr; if ( !url.isValid() || url.isEmpty() || url.host().isEmpty() ) return false; d->ilastMethod = method; d->ilastUrl = url; connectToHost(url.host(), url.port(80)); // process handlers if ( resHandler ) { d->irespHandler = resHandler; if ( reqHandler ) d->ireqHandler = reqHandler; else d->ireqHandler = [](QHttpRequest* req) ->void { req->end(); }; } return true; } void QHttpClient::timerEvent(QTimerEvent *e) { Q_D(QHttpClient); if ( e->timerId() == d->itimer.timerId() ) { close(); } } void QHttpClient::onRequestReady(QHttpRequest *req) { emit httpConnected(req); } void QHttpClient::onResponseReady(QHttpResponse *res) { emit newResponse(res); } /////////////////////////////////////////////////////////////////////////////// void QHttpClientPrivate::onConnected() { QHttpRequest *request = new QHttpRequest(isocket); request->d_func()->imethod = ilastMethod; request->d_func()->iurl = ilastUrl; if ( itimeOut > 0 ) itimer.start(itimeOut, Qt::CoarseTimer, q_func()); # if QHTTP_MESSAGES_LOG > 0 iinputBuffer.clear(); # endif if ( ireqHandler ) ireqHandler(request); else q_func()->onRequestReady(request); } void QHttpClientPrivate::onReadyRead() { while ( isocket->bytesAvailable() > 0 ) { char buffer[4097] = {0}; size_t readLength = isocket->read(buffer, 4096); parse(buffer, readLength); # if QHTTP_MESSAGES_LOG > 0 iinputBuffer.append(buffer); # endif } } /////////////////////////////////////////////////////////////////////////////// int QHttpClientPrivate::messageBegin(http_parser*) { itempHeaderField.clear(); itempHeaderValue.clear(); return 0; } int QHttpClientPrivate::status(http_parser* parser, const char* at, size_t length) { ilastResponse = new QHttpResponse(isocket); ilastResponse->d_func()->istatus = static_cast<TStatusCode>(parser->status_code); ilastResponse->d_func()->iversion = QString("%1.%2") .arg(parser->http_major) .arg(parser->http_minor); ilastResponse->d_func()->icustomeStatusMessage = QString::fromUtf8(at, length); return 0; } int QHttpClientPrivate::headerField(http_parser*, const char* at, size_t length) { Q_ASSERT(ilastResponse); // insert the header we parsed previously // into the header map if ( !itempHeaderField.isEmpty() && !itempHeaderValue.isEmpty() ) { // header names are always lower-cased ilastResponse->d_func()->iheaders.insert( itempHeaderField.toLower(), itempHeaderValue.toLower() ); // clear header value. this sets up a nice // feedback loop where the next time // HeaderValue is called, it can simply append itempHeaderField.clear(); itempHeaderValue.clear(); } itempHeaderField.append(at, length); return 0; } int QHttpClientPrivate::headerValue(http_parser*, const char* at, size_t length) { Q_ASSERT(ilastResponse); itempHeaderValue.append(at, length); return 0; } int QHttpClientPrivate::headersComplete(http_parser*) { Q_ASSERT(ilastResponse); // Insert last remaining header ilastResponse->d_func()->iheaders.insert( itempHeaderField.toLower(), itempHeaderValue.toLower() ); if ( irespHandler ) irespHandler(ilastResponse); else q_func()->onResponseReady(ilastResponse); return 0; } int QHttpClientPrivate::body(http_parser*, const char* at, size_t length) { Q_ASSERT(ilastResponse); if ( ilastResponse->idataHandler ) ilastResponse->idataHandler(QByteArray(at, length)); else emit ilastResponse->data(QByteArray(at, length)); return 0; } int QHttpClientPrivate::messageComplete(http_parser*) { Q_ASSERT(ilastResponse); ilastResponse->d_func()->isuccessful = true; if ( ilastResponse->iendHandler ) ilastResponse->iendHandler(); else emit ilastResponse->end(); return 0; } /////////////////////////////////////////////////////////////////////////////// } // namespace client } // namespace qhttp /////////////////////////////////////////////////////////////////////////////// <commit_msg>fix a bug in qhttpclient.<commit_after>#include "private/qhttpclient_private.hpp" #include <QTimerEvent> /////////////////////////////////////////////////////////////////////////////// namespace qhttp { namespace client { /////////////////////////////////////////////////////////////////////////////// QHttpClient::QHttpClient(QObject *parent) : QTcpSocket(parent), d_ptr(new QHttpClientPrivate(this)) { d_ptr->initialize(); QHTTP_LINE_LOG } QHttpClient::QHttpClient(QHttpClientPrivate &dd, QObject *parent) : QTcpSocket(parent), d_ptr(&dd) { d_ptr->initialize(); QHTTP_LINE_LOG } QHttpClient::~QHttpClient() { QHTTP_LINE_LOG } quint32 QHttpClient::timeOut() const { return d_func()->itimeOut; } void QHttpClient::setTimeOut(quint32 t) { d_func()->itimeOut = t; } bool QHttpClient::isOpen() const { return QTcpSocket::isOpen() && state() == QTcpSocket::ConnectedState; } bool QHttpClient::request(THttpMethod method, QUrl url, const TRequstHandler &reqHandler, const TResponseHandler &resHandler) { Q_D(QHttpClient); d->ireqHandler = nullptr; d->irespHandler = nullptr; if ( !url.isValid() || url.isEmpty() || url.host().isEmpty() ) return false; d->ilastMethod = method; d->ilastUrl = url; connectToHost(url.host(), url.port(80)); // process handlers if ( resHandler ) { d->irespHandler = resHandler; if ( reqHandler ) d->ireqHandler = reqHandler; else d->ireqHandler = [](QHttpRequest* req) ->void { req->end(); }; } return true; } void QHttpClient::timerEvent(QTimerEvent *e) { Q_D(QHttpClient); if ( e->timerId() == d->itimer.timerId() ) { close(); } } void QHttpClient::onRequestReady(QHttpRequest *req) { emit httpConnected(req); } void QHttpClient::onResponseReady(QHttpResponse *res) { emit newResponse(res); } /////////////////////////////////////////////////////////////////////////////// void QHttpClientPrivate::onConnected() { QHttpRequest *request = new QHttpRequest(isocket); request->d_func()->imethod = ilastMethod; request->d_func()->iurl = ilastUrl; if ( itimeOut > 0 ) itimer.start(itimeOut, Qt::CoarseTimer, q_func()); # if QHTTP_MESSAGES_LOG > 0 iinputBuffer.clear(); # endif if ( ireqHandler ) ireqHandler(request); else q_func()->onRequestReady(request); } void QHttpClientPrivate::onReadyRead() { while ( isocket->bytesAvailable() > 0 ) { char buffer[4097] = {0}; size_t readLength = isocket->read(buffer, 4096); parse(buffer, readLength); # if QHTTP_MESSAGES_LOG > 0 iinputBuffer.append(buffer); # endif } } /////////////////////////////////////////////////////////////////////////////// // if user closes the connection, ends the response or by any other reason // the socket be disconnected, then the iresponse instance may has been deleted. // In these situations reading more http body or emitting end() for incoming response // is not possible. #define CHECK_FOR_DISCONNECTED if ( ilastResponse == nullptr ) \ return 0; int QHttpClientPrivate::messageBegin(http_parser*) { itempHeaderField.clear(); itempHeaderValue.clear(); return 0; } int QHttpClientPrivate::status(http_parser* parser, const char* at, size_t length) { CHECK_FOR_DISCONNECTED ilastResponse = new QHttpResponse(isocket); ilastResponse->d_func()->istatus = static_cast<TStatusCode>(parser->status_code); ilastResponse->d_func()->iversion = QString("%1.%2") .arg(parser->http_major) .arg(parser->http_minor); ilastResponse->d_func()->icustomeStatusMessage = QString::fromUtf8(at, length); return 0; } int QHttpClientPrivate::headerField(http_parser*, const char* at, size_t length) { CHECK_FOR_DISCONNECTED // insert the header we parsed previously // into the header map if ( !itempHeaderField.isEmpty() && !itempHeaderValue.isEmpty() ) { // header names are always lower-cased ilastResponse->d_func()->iheaders.insert( itempHeaderField.toLower(), itempHeaderValue.toLower() ); // clear header value. this sets up a nice // feedback loop where the next time // HeaderValue is called, it can simply append itempHeaderField.clear(); itempHeaderValue.clear(); } itempHeaderField.append(at, length); return 0; } int QHttpClientPrivate::headerValue(http_parser*, const char* at, size_t length) { itempHeaderValue.append(at, length); return 0; } int QHttpClientPrivate::headersComplete(http_parser*) { CHECK_FOR_DISCONNECTED // Insert last remaining header ilastResponse->d_func()->iheaders.insert( itempHeaderField.toLower(), itempHeaderValue.toLower() ); if ( irespHandler ) irespHandler(ilastResponse); else q_func()->onResponseReady(ilastResponse); return 0; } int QHttpClientPrivate::body(http_parser*, const char* at, size_t length) { CHECK_FOR_DISCONNECTED if ( ilastResponse->idataHandler ) ilastResponse->idataHandler(QByteArray(at, length)); else emit ilastResponse->data(QByteArray(at, length)); return 0; } int QHttpClientPrivate::messageComplete(http_parser*) { CHECK_FOR_DISCONNECTED ilastResponse->d_func()->isuccessful = true; if ( ilastResponse->iendHandler ) ilastResponse->iendHandler(); else emit ilastResponse->end(); return 0; } /////////////////////////////////////////////////////////////////////////////// } // namespace client } // namespace qhttp /////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> using namespace std; #include "libsqasm/assembler.hpp" #include "libsqrun/runner.hpp" static void assemble(const string &fileName, const bool debug = false) { auto compilationData(Assembler::assemble(fileName)); Runner::run(compilationData->ops()); if (debug) { if (!compilationData->symbolTable().empty()) { cout << "Symbol table" << endl; for (auto &pair : compilationData->symbolTable()) { cout << " symbol: " << pair.first << " = " << pair.second << endl; } } if (!compilationData->cells().empty()) { cout << "Cells" << endl; for (auto &cell : compilationData->cells()) { cout << " cell: " << cell->toString() << endl; } } } } int main(int argc, char *argv[]) { try { for (auto i = 1; i < argc; ++i) { assemble(argv[i]); } return EXIT_SUCCESS; } catch (const exception &ex) { cout << "Message: " << ex.what() << endl; return EXIT_FAILURE; } } <commit_msg>Parse --debug switch from command line<commit_after>#include <iostream> #include <string> #include <vector> using namespace std; #include "libsqasm/assembler.hpp" #include "libsqrun/runner.hpp" static void assemble(const string &fileName, const bool debug) { auto compilationData(Assembler::assemble(fileName)); Runner::run(compilationData->ops(), debug); } int main(int argc, char *argv[]) { try { bool debug = false; for (auto i = 1; i < argc; ++i) { string arg(argv[i]); if (i == 1 && arg.compare("--debug") == 0) { debug = true; continue; } assemble(arg, debug); } return EXIT_SUCCESS; } catch (const exception &ex) { cout << "Message: " << ex.what() << endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>/* Copyright (C) 2000 MySQL 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) any later version. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* UNION of select's UNION's were introduced by Monty and Sinisa <[email protected]> */ #include "mysql_priv.h" #include "sql_select.h" int mysql_union(THD *thd, LEX *lex,select_result *result) { SELECT_LEX *sl; SELECT_LEX_UNIT *unit= &(lex->unit); List<Item> item_list; TABLE *table; int describe=(lex->select_lex.options & SELECT_DESCRIBE) ? 1 : 0; int res; bool found_rows_for_union=false; TABLE_LIST result_table_list; TABLE_LIST *first_table=(TABLE_LIST *)lex->select_lex.table_list.first; TMP_TABLE_PARAM tmp_table_param; select_union *union_result; DBUG_ENTER("mysql_union"); st_select_lex_node * global; /* Fix tables 'to-be-unioned-from' list to point at opened tables */ for (sl= &lex->select_lex; sl; sl= (SELECT_LEX *) sl->next) { for (TABLE_LIST *cursor= (TABLE_LIST *)sl->table_list.first; cursor; cursor=cursor->next) cursor->table= ((TABLE_LIST*) cursor->table)->table; } /* Global option */ if (((void*)(global= unit->global_parameters)) == ((void*)unit)) { found_rows_for_union = lex->select_lex.options & OPTION_FOUND_ROWS && !describe && global->select_limit; if (found_rows_for_union) lex->select_lex.options ^= OPTION_FOUND_ROWS; } if (describe) { Item *item; item_list.push_back(new Item_empty_string("table",NAME_LEN)); item_list.push_back(new Item_empty_string("type",10)); item_list.push_back(item=new Item_empty_string("possible_keys", NAME_LEN*MAX_KEY)); item->maybe_null=1; item_list.push_back(item=new Item_empty_string("key",NAME_LEN)); item->maybe_null=1; item_list.push_back(item=new Item_int("key_len",0,3)); item->maybe_null=1; item_list.push_back(item=new Item_empty_string("ref", NAME_LEN*MAX_REF_PARTS)); item->maybe_null=1; item_list.push_back(new Item_real("rows",0.0,0,10)); item_list.push_back(new Item_empty_string("Extra",255)); } else { Item *item; List_iterator<Item> it(lex->select_lex.item_list); TABLE_LIST *first_table= (TABLE_LIST*) lex->select_lex.table_list.first; /* Create a list of items that will be in the result set */ while ((item= it++)) if (item_list.push_back(item)) DBUG_RETURN(-1); if (setup_fields(thd,first_table,item_list,0,0,1)) DBUG_RETURN(-1); } bzero((char*) &tmp_table_param,sizeof(tmp_table_param)); tmp_table_param.field_count=item_list.elements; if (!(table= create_tmp_table(thd, &tmp_table_param, item_list, (ORDER*) 0, !describe & !lex->union_option, 1, 0, (lex->select_lex.options | thd->options | TMP_TABLE_ALL_COLUMNS), unit))) DBUG_RETURN(-1); table->file->extra(HA_EXTRA_WRITE_CACHE); table->file->extra(HA_EXTRA_IGNORE_DUP_KEY); bzero((char*) &result_table_list,sizeof(result_table_list)); result_table_list.db= (char*) ""; result_table_list.real_name=result_table_list.name=(char*) "union"; result_table_list.table=table; if (!(union_result=new select_union(table))) { res= -1; goto exit; } union_result->save_time_stamp=!describe; for (sl= &lex->select_lex; sl; sl= (SELECT_LEX*) sl->next) { lex->select=sl; unit->offset_limit_cnt= sl->offset_limit; unit->select_limit_cnt= sl->select_limit+sl->offset_limit; if (unit->select_limit_cnt < sl->select_limit) unit->select_limit_cnt= HA_POS_ERROR; // no limit if (unit->select_limit_cnt == HA_POS_ERROR) sl->options&= ~OPTION_FOUND_ROWS; res= mysql_select(thd, (describe && sl->linkage==GLOBAL_OPTIONS_TYPE) ? first_table : (TABLE_LIST*) sl->table_list.first, sl->item_list, sl->where, (sl->braces) ? (ORDER *)sl->order_list.first : (ORDER *) 0, (ORDER*) sl->group_list.first, sl->having, (ORDER*) NULL, sl->options | thd->options | SELECT_NO_UNLOCK | ((describe) ? SELECT_DESCRIBE : 0), union_result, unit); if (res) goto exit; } if (union_result->flush()) { res= 1; // Error is already sent goto exit; } delete union_result; /* Send result to 'result' */ lex->select = &lex->select_lex; res =-1; { /* Create a list of fields in the temporary table */ List_iterator<Item> it(item_list); Field **field; #if 0 List<Item_func_match> ftfunc_list; ftfunc_list.empty(); #else thd->lex.select_lex.ftfunc_list.empty(); #endif for (field=table->field ; *field ; field++) { (void) it++; (void) it.replace(new Item_field(*field)); } if (!thd->fatal_error) // Check if EOM { st_select_lex_node * global= unit->global_parameters; unit->offset_limit_cnt= global->offset_limit; unit->select_limit_cnt= global->select_limit+global->offset_limit; if (unit->select_limit_cnt < global->select_limit) unit->select_limit_cnt= HA_POS_ERROR; // no limit if (unit->select_limit_cnt == HA_POS_ERROR) thd->options&= ~OPTION_FOUND_ROWS; if (describe) unit->select_limit_cnt= HA_POS_ERROR; // no limit res= mysql_select(thd,&result_table_list, item_list, NULL, (describe) ? 0 : (ORDER*)global->order_list.first, (ORDER*) NULL, NULL, (ORDER*) NULL, thd->options, result, unit); if (found_rows_for_union && !res) thd->limit_found_rows = (ulonglong)table->file->records; } } exit: free_tmp_table(thd,table); DBUG_RETURN(res); } /*************************************************************************** ** store records in temporary table for UNION ***************************************************************************/ select_union::select_union(TABLE *table_par) :table(table_par) { bzero((char*) &info,sizeof(info)); /* We can always use DUP_IGNORE because the temporary table will only contain a unique key if we are using not using UNION ALL */ info.handle_duplicates= DUP_IGNORE; } select_union::~select_union() { } int select_union::prepare(List<Item> &list, SELECT_LEX_UNIT *u) { unit= u; if (save_time_stamp && list.elements != table->fields) { my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT, ER(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT),MYF(0)); return -1; } return 0; } bool select_union::send_data(List<Item> &values) { if (unit->offset_limit_cnt) { // using limit offset,count unit->offset_limit_cnt--; return 0; } fill_record(table->field,values); return write_record(table,&info) ? 1 : 0; } bool select_union::send_eof() { return 0; } bool select_union::flush() { int error; if ((error=table->file->extra(HA_EXTRA_NO_CACHE))) { table->file->print_error(error,MYF(0)); ::send_error(&thd->net); return 1; } return 0; } <commit_msg>removed fake description (EXPLAIN) of first table for last SELECT_LEX with global parameters, because now it is absent<commit_after>/* Copyright (C) 2000 MySQL 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) any later version. 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* UNION of select's UNION's were introduced by Monty and Sinisa <[email protected]> */ #include "mysql_priv.h" #include "sql_select.h" int mysql_union(THD *thd, LEX *lex,select_result *result) { SELECT_LEX *sl; SELECT_LEX_UNIT *unit= &(lex->unit); List<Item> item_list; TABLE *table; int describe=(lex->select_lex.options & SELECT_DESCRIBE) ? 1 : 0; int res; bool found_rows_for_union=false; TABLE_LIST result_table_list; TMP_TABLE_PARAM tmp_table_param; select_union *union_result; DBUG_ENTER("mysql_union"); st_select_lex_node * global; /* Fix tables 'to-be-unioned-from' list to point at opened tables */ for (sl= &lex->select_lex; sl; sl= (SELECT_LEX *) sl->next) { for (TABLE_LIST *cursor= (TABLE_LIST *)sl->table_list.first; cursor; cursor=cursor->next) cursor->table= ((TABLE_LIST*) cursor->table)->table; } /* Global option */ if (((void*)(global= unit->global_parameters)) == ((void*)unit)) { found_rows_for_union = lex->select_lex.options & OPTION_FOUND_ROWS && !describe && global->select_limit; if (found_rows_for_union) lex->select_lex.options ^= OPTION_FOUND_ROWS; } if (describe) { Item *item; item_list.push_back(new Item_empty_string("table",NAME_LEN)); item_list.push_back(new Item_empty_string("type",10)); item_list.push_back(item=new Item_empty_string("possible_keys", NAME_LEN*MAX_KEY)); item->maybe_null=1; item_list.push_back(item=new Item_empty_string("key",NAME_LEN)); item->maybe_null=1; item_list.push_back(item=new Item_int("key_len",0,3)); item->maybe_null=1; item_list.push_back(item=new Item_empty_string("ref", NAME_LEN*MAX_REF_PARTS)); item->maybe_null=1; item_list.push_back(new Item_real("rows",0.0,0,10)); item_list.push_back(new Item_empty_string("Extra",255)); } else { Item *item; List_iterator<Item> it(lex->select_lex.item_list); TABLE_LIST *first_table= (TABLE_LIST*) lex->select_lex.table_list.first; /* Create a list of items that will be in the result set */ while ((item= it++)) if (item_list.push_back(item)) DBUG_RETURN(-1); if (setup_fields(thd,first_table,item_list,0,0,1)) DBUG_RETURN(-1); } bzero((char*) &tmp_table_param,sizeof(tmp_table_param)); tmp_table_param.field_count=item_list.elements; if (!(table= create_tmp_table(thd, &tmp_table_param, item_list, (ORDER*) 0, !describe & !lex->union_option, 1, 0, (lex->select_lex.options | thd->options | TMP_TABLE_ALL_COLUMNS), unit))) DBUG_RETURN(-1); table->file->extra(HA_EXTRA_WRITE_CACHE); table->file->extra(HA_EXTRA_IGNORE_DUP_KEY); bzero((char*) &result_table_list,sizeof(result_table_list)); result_table_list.db= (char*) ""; result_table_list.real_name=result_table_list.name=(char*) "union"; result_table_list.table=table; if (!(union_result=new select_union(table))) { res= -1; goto exit; } union_result->save_time_stamp=!describe; for (sl= &lex->select_lex; sl; sl= (SELECT_LEX*) sl->next) { lex->select=sl; unit->offset_limit_cnt= sl->offset_limit; unit->select_limit_cnt= sl->select_limit+sl->offset_limit; if (unit->select_limit_cnt < sl->select_limit) unit->select_limit_cnt= HA_POS_ERROR; // no limit if (unit->select_limit_cnt == HA_POS_ERROR) sl->options&= ~OPTION_FOUND_ROWS; res= mysql_select(thd, (TABLE_LIST*) sl->table_list.first, sl->item_list, sl->where, (sl->braces) ? (ORDER *)sl->order_list.first : (ORDER *) 0, (ORDER*) sl->group_list.first, sl->having, (ORDER*) NULL, sl->options | thd->options | SELECT_NO_UNLOCK | ((describe) ? SELECT_DESCRIBE : 0), union_result, unit); if (res) goto exit; } if (union_result->flush()) { res= 1; // Error is already sent goto exit; } delete union_result; /* Send result to 'result' */ lex->select = &lex->select_lex; res =-1; { /* Create a list of fields in the temporary table */ List_iterator<Item> it(item_list); Field **field; #if 0 List<Item_func_match> ftfunc_list; ftfunc_list.empty(); #else thd->lex.select_lex.ftfunc_list.empty(); #endif for (field=table->field ; *field ; field++) { (void) it++; (void) it.replace(new Item_field(*field)); } if (!thd->fatal_error) // Check if EOM { st_select_lex_node * global= unit->global_parameters; unit->offset_limit_cnt= global->offset_limit; unit->select_limit_cnt= global->select_limit+global->offset_limit; if (unit->select_limit_cnt < global->select_limit) unit->select_limit_cnt= HA_POS_ERROR; // no limit if (unit->select_limit_cnt == HA_POS_ERROR) thd->options&= ~OPTION_FOUND_ROWS; if (describe) unit->select_limit_cnt= HA_POS_ERROR; // no limit res= mysql_select(thd,&result_table_list, item_list, NULL, (describe) ? 0 : (ORDER*)global->order_list.first, (ORDER*) NULL, NULL, (ORDER*) NULL, thd->options, result, unit); if (found_rows_for_union && !res) thd->limit_found_rows = (ulonglong)table->file->records; } } exit: free_tmp_table(thd,table); DBUG_RETURN(res); } /*************************************************************************** ** store records in temporary table for UNION ***************************************************************************/ select_union::select_union(TABLE *table_par) :table(table_par) { bzero((char*) &info,sizeof(info)); /* We can always use DUP_IGNORE because the temporary table will only contain a unique key if we are using not using UNION ALL */ info.handle_duplicates= DUP_IGNORE; } select_union::~select_union() { } int select_union::prepare(List<Item> &list, SELECT_LEX_UNIT *u) { unit= u; if (save_time_stamp && list.elements != table->fields) { my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT, ER(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT),MYF(0)); return -1; } return 0; } bool select_union::send_data(List<Item> &values) { if (unit->offset_limit_cnt) { // using limit offset,count unit->offset_limit_cnt--; return 0; } fill_record(table->field,values); return write_record(table,&info) ? 1 : 0; } bool select_union::send_eof() { return 0; } bool select_union::flush() { int error; if ((error=table->file->extra(HA_EXTRA_NO_CACHE))) { table->file->print_error(error,MYF(0)); ::send_error(&thd->net); return 1; } return 0; } <|endoftext|>
<commit_before> #include "IntegrateOverRadius.h" #include "GslWrappers.h" #include "RadialFunction.h" #include <cmath> #include <gsl/gsl_spline.h> namespace { RadialFunction weighByVolumeElement(const RadialFunction& f) { std::vector<double> weighted(f.data); for (size_t r=0; r<weighted.size(); ++r) { weighted[r] *= 4.0*M_PI * f.radii[r] * f.radii[r]; } return RadialFunction(f.radii, weighted); } class RadialInterpFunction : public GSL::FunctionObject { private: gsl_interp_accel* acc; gsl_spline* spline; public: RadialInterpFunction(const RadialFunction& f) { acc = gsl_interp_accel_alloc(); spline = gsl_spline_alloc(gsl_interp_cspline, f.radii.size()); gsl_spline_init(spline, f.radii.data(), f.data.data(), f.radii.size()); } ~RadialInterpFunction() { gsl_spline_free(spline); gsl_interp_accel_free(acc); } double operator()(double x) const { return gsl_spline_eval(spline, x, acc); } }; } // helper namespace double integrateOverRadius(const RadialFunction& input) { // multiply data values by volume element (4 pi r^2) before integration const RadialFunction integrand = weighByVolumeElement(input); // construct a GSL cubic spline approximation to the data // TODO: see if GSL interfacing can be cleaned up RadialInterpFunction interp_integrand(integrand); // perform integration with GSL calls // TODO: // consider other algorithm possibilities: // 1- use the spline's exact integral // 2- use a spectral type approach // 3- ? const double r_min = integrand.radii.front(); const double r_max = integrand.radii.back(); const double eps_abs = 1.0e-6; const double eps_rel = eps_abs; return GSL::integrate(interp_integrand, r_min, r_max, eps_abs, eps_rel); } <commit_msg>IntegrateOverRadius: Use new spline wrapper<commit_after> #include "IntegrateOverRadius.h" #include "GslWrappers.h" #include "RadialFunction.h" #include <cmath> namespace { RadialFunction weighByVolumeElement(const RadialFunction& f) { std::vector<double> weighted(f.data); for (size_t r=0; r<weighted.size(); ++r) { weighted[r] *= 4.0*M_PI * f.radii[r] * f.radii[r]; } return RadialFunction(f.radii, weighted); } class RadialInterpFunction : public GSL::FunctionObject { private: GSL::Spline spline; public: RadialInterpFunction(const RadialFunction& f) : spline(f) {} double operator()(double x) const { return spline.eval(x); } }; } // helper namespace double integrateOverRadius(const RadialFunction& input) { // multiply data values by volume element (4 pi r^2) before integration const RadialFunction integrand = weighByVolumeElement(input); // construct a GSL cubic spline approximation to the data // TODO: see if GSL interfacing can be cleaned up RadialInterpFunction interp_integrand(integrand); // perform integration with GSL calls // TODO: // consider other algorithm possibilities: // 1- use the spline's exact integral // 2- use a spectral type approach // 3- ? const double r_min = integrand.radii.front(); const double r_max = integrand.radii.back(); const double eps_abs = 1.0e-6; const double eps_rel = eps_abs; return GSL::integrate(interp_integrand, r_min, r_max, eps_abs, eps_rel); } <|endoftext|>
<commit_before>// ffmpeg player output (portaudio) // part of MusicPlayer, https://github.com/albertz/music-player // Copyright (c) 2012, Albert Zeyer, www.az2000.de // All rights reserved. // This code is under the 2-clause BSD license, see License.txt in the root directory of this project. #include "ffmpeg.h" #include "PyUtils.h" #include <portaudio.h> #include <boost/bind.hpp> #include <boost/atomic.hpp> #ifdef __APPLE__ // PortAudio specific Mac stuff #include "pa_mac_core.h" #endif // For setting the thread priority to realtime on MacOSX. #ifdef __APPLE__ #include <mach/mach_init.h> #include <mach/thread_policy.h> #include <mach/thread_act.h> // the doc says mach/sched.h but that seems outdated... #include <pthread.h> #include <mach/mach_error.h> #include <mach/mach_time.h> #endif static void setRealtime(); /* The implementation with the PortAudio callback was there first. For testing, I implemented also the blocking PortAudio interface. I had some issues which small hiccups in the audio output - maybe the blocking PortAudio implementation can avoid them better. For the callback, we need to minimize the locks - or better, avoid them fully. I'm not sure it is good to depend on thread context switches in case it is locked. This however needs some heavy redesign. */ #define USE_PORTAUDIO_CALLBACK 1 int initPlayerOutput() { PaError ret = Pa_Initialize(); if(ret != paNoError) Py_FatalError("PortAudio init failed"); return 0; } void reinitPlayerOutput() { if(Pa_Terminate() != paNoError) printf("Warning: Pa_Terminate() failed\n"); initPlayerOutput(); } template<typename T> struct OutPaSampleFormat{}; template<> struct OutPaSampleFormat<int16_t> { static const PaSampleFormat format = paInt16; }; template<> struct OutPaSampleFormat<float32_t> { static const PaSampleFormat format = paFloat32; }; #define LATENCY_IN_MS 100 struct PlayerObject::OutStream { PlayerObject* const player; PaStream* stream; boost::atomic<bool> needRealtimeReset; // PortAudio callback thread must set itself to realtime boost::atomic<bool> setThreadName; OutStream(PlayerObject* p) : player(p), stream(NULL), needRealtimeReset(false) { mlock(this, sizeof(*this)); } ~OutStream() { close(); } #if USE_PORTAUDIO_CALLBACK static int paStreamCallback( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { OutStream* outStream = (OutStream*) userData; if(outStream->needRealtimeReset.exchange(false)) setRealtime(); if(outStream->setThreadName.exchange(false)) setCurThreadName("audio callback"); if(statusFlags & paOutputUnderflow) printf("audio: paOutputUnderflow\n"); if(statusFlags & paOutputOverflow) printf("audio: paOutputOverflow\n"); // We must not hold the PyGIL here! // Also no need to hold the player lock, all is safe! outStream->player->readOutStream((OUTSAMPLE_t*) output, frameCount * outStream->player->outNumChannels, NULL); return paContinue; } #else PyThread audioThread; void audioThreadProc(PyMutex& threadLock, bool& stopSignal) { while(true) { { PyScopedLock l(threadLock); if(stopSignal) return; } if(needRealtimeReset) { needRealtimeReset = false; setRealtime(); } OUTSAMPLE_t buffer[48 * 2 * 10]; // 10ms stereo in 48khz size_t frameCount = 0; { PyScopedLock lock(player->lock); if(stopSignal) return; player->readOutStream(buffer, sizeof(buffer)/sizeof(OUTSAMPLE_t), NULL); frameCount = sizeof(buffer)/sizeof(OUTSAMPLE_t) / player->outNumChannels; } PaError ret = Pa_WriteStream(stream, buffer, frameCount); if(ret == paOutputUnderflowed) printf("warning: paOutputUnderflowed\n"); else if(ret != paNoError) { printf("Pa_WriteStream error %i (%s)\n", ret, Pa_GetErrorText(ret)); // sleep half a second to avoid spamming for(int i = 0; i < 50; ++i) { usleep(10 * 1000); PyScopedLock l(threadLock); if(stopSignal) return; } } } } #endif bool open() { if(stream) close(); assert(stream == NULL); // For reference: // Mixxx code: http://bazaar.launchpad.net/~mixxxdevelopers/mixxx/trunk/view/head:/mixxx/src/sounddeviceportaudio.cpp PaStreamParameters outputParameters; #if defined(__APPLE__) PaMacCoreStreamInfo macInfo; PaMacCore_SetupStreamInfo( &macInfo, paMacCorePlayNice | paMacCorePro ); outputParameters.hostApiSpecificStreamInfo = &macInfo; #elif defined(__LINUX__) // TODO: if we have PaAlsa_EnableRealtimeScheduling in portaudio, // we can call that to enable RT priority with ALSA. // We could check dynamically via dsym. outputParameters.hostApiSpecificStreamInfo = NULL; #else outputParameters.hostApiSpecificStreamInfo = NULL; #endif outputParameters.device = Pa_GetDefaultOutputDevice(); if (outputParameters.device == paNoDevice) { PyScopedGIL gil; PyErr_SetString(PyExc_RuntimeError, "Pa_GetDefaultOutputDevice didn't returned a device"); return false; } outputParameters.channelCount = player->outNumChannels; outputParameters.sampleFormat = OutPaSampleFormat<OUTSAMPLE_t>::format; //unsigned long bufferSize = (player->outSamplerate * player->outNumChannels / 1000) * LATENCY_IN_MS / 4; unsigned long bufferSize = paFramesPerBufferUnspecified; // support any buffer size if(bufferSize == paFramesPerBufferUnspecified) outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency; else outputParameters.suggestedLatency = LATENCY_IN_MS / 1000.0; // Note about framesPerBuffer: // Earlier, we used (2048 * 5 * OUTSAMPLEBYTELEN) which caused // some random more or less rare cracking noises. // See here: https://github.com/albertz/music-player/issues/35 // This doesn't seem to happen with paFramesPerBufferUnspecified. PaError ret = Pa_OpenStream( &stream, NULL, // no input &outputParameters, player->outSamplerate, // sampleRate bufferSize, paClipOff | paDitherOff, #if USE_PORTAUDIO_CALLBACK &paStreamCallback, #else NULL, #endif this //void *userData ); if(ret != paNoError) { { PyScopedGIL gil; PyErr_Format(PyExc_RuntimeError, "Pa_OpenStream failed: (err %i) %s", ret, Pa_GetErrorText(ret)); } if(stream) close(); return false; } needRealtimeReset = true; setThreadName = true; Pa_StartStream(stream); #if !USE_PORTAUDIO_CALLBACK audioThread.func = boost::bind(&OutStream::audioThreadProc, this, _1, _2); audioThread.start(); #endif return true; } void close() { if(this->stream == NULL) return; // we expect that we have the player lock here. // reset fader. player->fader.change(0,0); // we must release the player lock so that any thread-join can be done. PaStream* stream = NULL; std::swap(stream, this->stream); PyScopedUnlock unlock(player->lock); #if !USE_PORTAUDIO_CALLBACK audioThread.stop(); #endif Pa_CloseStream(stream); } bool isOpen() const { return stream != NULL; } }; int PlayerObject::setPlaying(bool playing) { PlayerObject* player = this; bool oldplayingstate = player->playing; if(oldplayingstate != playing) outOfSync = true; PyScopedGIL gil; { PyScopedGIUnlock gunlock; player->workerThread.start(); // if not running yet, start if(!player->outStream.get()) player->outStream.reset(new OutStream(this)); assert(player->outStream.get() != NULL); if(soundcardOutputEnabled) { if(playing && !player->outStream->isOpen()) { if(!player->outStream->open()) playing = false; } } if(soundcardOutputEnabled && player->outStream.get() && player->outStream->isOpen() && oldplayingstate != playing) fader.change(playing ? 1 : -1, outSamplerate); player->playing = playing; } if(!PyErr_Occurred() && player->dict) { Py_INCREF(player->dict); PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange"); if(onPlayingStateChange && onPlayingStateChange != Py_None) { Py_INCREF(onPlayingStateChange); PyObject* kwargs = PyDict_New(); assert(kwargs); PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate)); PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing)); PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs); Py_XDECREF(retObj); // errors are not fatal from the callback, so handle it now and go on if(PyErr_Occurred()) PyErr_Print(); Py_DECREF(kwargs); Py_DECREF(onPlayingStateChange); } Py_DECREF(player->dict); } return PyErr_Occurred() ? -1 : 0; } void PlayerObject::resetPlaying() { if(this->playing) this->setPlaying(false); if(this->outStream.get() != NULL) this->outStream.reset(); reinitPlayerOutput(); } #ifdef __APPLE__ // https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html // Also, from Google Native Client, osx/nacl_thread_nice.c has some related code. // Or, from Google Chrome, platform_thread_mac.mm. http://src.chromium.org/svn/trunk/src/base/threading/platform_thread_mac.mm void setRealtime() { kern_return_t ret; thread_port_t threadport = pthread_mach_thread_np(pthread_self()); thread_extended_policy_data_t policy; policy.timeshare = 0; ret = thread_policy_set(threadport, THREAD_EXTENDED_POLICY, (thread_policy_t)&policy, THREAD_EXTENDED_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } thread_precedence_policy_data_t precedence; precedence.importance = 63; ret = thread_policy_set(threadport, THREAD_PRECEDENCE_POLICY, (thread_policy_t)&precedence, THREAD_PRECEDENCE_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } // Get the conversion factor from milliseconds to absolute time // which is what the time-constraints call needs. mach_timebase_info_data_t tb_info; mach_timebase_info(&tb_info); double timeFact = ((double)tb_info.denom / (double)tb_info.numer) * 1000000; thread_time_constraint_policy_data_t ttcpolicy; ttcpolicy.period = 2.9 * timeFact; // in Chrome: 2.9ms ~= 128 frames @44.1KHz ttcpolicy.computation = 0.75 * ttcpolicy.period; ttcpolicy.constraint = 0.85 * ttcpolicy.period; ttcpolicy.preemptible = 0; ret = thread_policy_set(threadport, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } } #else void setRealtime() {} // not implemented yet #endif <commit_msg>more on realtime param<commit_after>// ffmpeg player output (portaudio) // part of MusicPlayer, https://github.com/albertz/music-player // Copyright (c) 2012, Albert Zeyer, www.az2000.de // All rights reserved. // This code is under the 2-clause BSD license, see License.txt in the root directory of this project. #include "ffmpeg.h" #include "PyUtils.h" #include <portaudio.h> #include <boost/bind.hpp> #include <boost/atomic.hpp> #ifdef __APPLE__ // PortAudio specific Mac stuff #include "pa_mac_core.h" #endif // For setting the thread priority to realtime on MacOSX. #ifdef __APPLE__ #include <mach/mach_init.h> #include <mach/thread_policy.h> #include <mach/thread_act.h> // the doc says mach/sched.h but that seems outdated... #include <pthread.h> #include <mach/mach_error.h> #include <mach/mach_time.h> #endif static void setRealtime(double dutyCicleMs); /* The implementation with the PortAudio callback was there first. For testing, I implemented also the blocking PortAudio interface. I had some issues which small hiccups in the audio output - maybe the blocking PortAudio implementation can avoid them better. For the callback, we need to minimize the locks - or better, avoid them fully. I'm not sure it is good to depend on thread context switches in case it is locked. This however needs some heavy redesign. */ #define USE_PORTAUDIO_CALLBACK 1 int initPlayerOutput() { PaError ret = Pa_Initialize(); if(ret != paNoError) Py_FatalError("PortAudio init failed"); return 0; } void reinitPlayerOutput() { if(Pa_Terminate() != paNoError) printf("Warning: Pa_Terminate() failed\n"); initPlayerOutput(); } template<typename T> struct OutPaSampleFormat{}; template<> struct OutPaSampleFormat<int16_t> { static const PaSampleFormat format = paInt16; }; template<> struct OutPaSampleFormat<float32_t> { static const PaSampleFormat format = paFloat32; }; #define LATENCY_IN_MS 100 struct PlayerObject::OutStream { PlayerObject* const player; PaStream* stream; boost::atomic<bool> needRealtimeReset; // PortAudio callback thread must set itself to realtime boost::atomic<bool> setThreadName; OutStream(PlayerObject* p) : player(p), stream(NULL), needRealtimeReset(false) { mlock(this, sizeof(*this)); } ~OutStream() { close(); } #if USE_PORTAUDIO_CALLBACK static int paStreamCallback( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { OutStream* outStream = (OutStream*) userData; PlayerObject* player = outStream->player; if(outStream->needRealtimeReset.exchange(false)) setRealtime(1000.0 * frameCount / player->outSamplerate); if(outStream->setThreadName.exchange(false)) setCurThreadName("audio callback"); if(statusFlags & paOutputUnderflow) printf("audio: paOutputUnderflow\n"); if(statusFlags & paOutputOverflow) printf("audio: paOutputOverflow\n"); // We must not hold the PyGIL here! // Also no need to hold the player lock, all is safe! player->readOutStream((OUTSAMPLE_t*) output, frameCount * outStream->player->outNumChannels, NULL); return paContinue; } #else PyThread audioThread; void audioThreadProc(PyMutex& threadLock, bool& stopSignal) { while(true) { { PyScopedLock l(threadLock); if(stopSignal) return; } if(needRealtimeReset) { needRealtimeReset = false; setRealtime(); } OUTSAMPLE_t buffer[48 * 2 * 10]; // 10ms stereo in 48khz size_t frameCount = 0; { PyScopedLock lock(player->lock); if(stopSignal) return; player->readOutStream(buffer, sizeof(buffer)/sizeof(OUTSAMPLE_t), NULL); frameCount = sizeof(buffer)/sizeof(OUTSAMPLE_t) / player->outNumChannels; } PaError ret = Pa_WriteStream(stream, buffer, frameCount); if(ret == paOutputUnderflowed) printf("warning: paOutputUnderflowed\n"); else if(ret != paNoError) { printf("Pa_WriteStream error %i (%s)\n", ret, Pa_GetErrorText(ret)); // sleep half a second to avoid spamming for(int i = 0; i < 50; ++i) { usleep(10 * 1000); PyScopedLock l(threadLock); if(stopSignal) return; } } } } #endif bool open() { if(stream) close(); assert(stream == NULL); // For reference: // Mixxx code: http://bazaar.launchpad.net/~mixxxdevelopers/mixxx/trunk/view/head:/mixxx/src/sounddeviceportaudio.cpp PaStreamParameters outputParameters; #if defined(__APPLE__) PaMacCoreStreamInfo macInfo; PaMacCore_SetupStreamInfo( &macInfo, paMacCorePlayNice | paMacCorePro ); outputParameters.hostApiSpecificStreamInfo = &macInfo; #elif defined(__LINUX__) // TODO: if we have PaAlsa_EnableRealtimeScheduling in portaudio, // we can call that to enable RT priority with ALSA. // We could check dynamically via dsym. outputParameters.hostApiSpecificStreamInfo = NULL; #else outputParameters.hostApiSpecificStreamInfo = NULL; #endif outputParameters.device = Pa_GetDefaultOutputDevice(); if (outputParameters.device == paNoDevice) { PyScopedGIL gil; PyErr_SetString(PyExc_RuntimeError, "Pa_GetDefaultOutputDevice didn't returned a device"); return false; } outputParameters.channelCount = player->outNumChannels; outputParameters.sampleFormat = OutPaSampleFormat<OUTSAMPLE_t>::format; //unsigned long bufferSize = (player->outSamplerate * player->outNumChannels / 1000) * LATENCY_IN_MS / 4; unsigned long bufferSize = paFramesPerBufferUnspecified; // support any buffer size if(bufferSize == paFramesPerBufferUnspecified) outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency; else outputParameters.suggestedLatency = LATENCY_IN_MS / 1000.0; // Note about framesPerBuffer: // Earlier, we used (2048 * 5 * OUTSAMPLEBYTELEN) which caused // some random more or less rare cracking noises. // See here: https://github.com/albertz/music-player/issues/35 // This doesn't seem to happen with paFramesPerBufferUnspecified. PaError ret = Pa_OpenStream( &stream, NULL, // no input &outputParameters, player->outSamplerate, // sampleRate bufferSize, paClipOff | paDitherOff, #if USE_PORTAUDIO_CALLBACK &paStreamCallback, #else NULL, #endif this //void *userData ); if(ret != paNoError) { { PyScopedGIL gil; PyErr_Format(PyExc_RuntimeError, "Pa_OpenStream failed: (err %i) %s", ret, Pa_GetErrorText(ret)); } if(stream) close(); return false; } needRealtimeReset = true; setThreadName = true; Pa_StartStream(stream); #if !USE_PORTAUDIO_CALLBACK audioThread.func = boost::bind(&OutStream::audioThreadProc, this, _1, _2); audioThread.start(); #endif return true; } void close() { if(this->stream == NULL) return; // we expect that we have the player lock here. // reset fader. player->fader.change(0,0); // we must release the player lock so that any thread-join can be done. PaStream* stream = NULL; std::swap(stream, this->stream); PyScopedUnlock unlock(player->lock); #if !USE_PORTAUDIO_CALLBACK audioThread.stop(); #endif Pa_CloseStream(stream); } bool isOpen() const { return stream != NULL; } }; int PlayerObject::setPlaying(bool playing) { PlayerObject* player = this; bool oldplayingstate = player->playing; if(oldplayingstate != playing) outOfSync = true; PyScopedGIL gil; { PyScopedGIUnlock gunlock; player->workerThread.start(); // if not running yet, start if(!player->outStream.get()) player->outStream.reset(new OutStream(this)); assert(player->outStream.get() != NULL); if(soundcardOutputEnabled) { if(playing && !player->outStream->isOpen()) { if(!player->outStream->open()) playing = false; } } if(soundcardOutputEnabled && player->outStream.get() && player->outStream->isOpen() && oldplayingstate != playing) fader.change(playing ? 1 : -1, outSamplerate); player->playing = playing; } if(!PyErr_Occurred() && player->dict) { Py_INCREF(player->dict); PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange"); if(onPlayingStateChange && onPlayingStateChange != Py_None) { Py_INCREF(onPlayingStateChange); PyObject* kwargs = PyDict_New(); assert(kwargs); PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate)); PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing)); PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs); Py_XDECREF(retObj); // errors are not fatal from the callback, so handle it now and go on if(PyErr_Occurred()) PyErr_Print(); Py_DECREF(kwargs); Py_DECREF(onPlayingStateChange); } Py_DECREF(player->dict); } return PyErr_Occurred() ? -1 : 0; } void PlayerObject::resetPlaying() { if(this->playing) this->setPlaying(false); if(this->outStream.get() != NULL) this->outStream.reset(); reinitPlayerOutput(); } #ifdef __APPLE__ // https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html // Also, from Google Native Client, osx/nacl_thread_nice.c has some related code. // Or, from Google Chrome, platform_thread_mac.mm. http://src.chromium.org/svn/trunk/src/base/threading/platform_thread_mac.mm void setRealtime(double dutyCicleMs) { kern_return_t ret; thread_port_t threadport = pthread_mach_thread_np(pthread_self()); thread_extended_policy_data_t policy; policy.timeshare = 0; ret = thread_policy_set(threadport, THREAD_EXTENDED_POLICY, (thread_policy_t)&policy, THREAD_EXTENDED_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } thread_precedence_policy_data_t precedence; precedence.importance = 63; ret = thread_policy_set(threadport, THREAD_PRECEDENCE_POLICY, (thread_policy_t)&precedence, THREAD_PRECEDENCE_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } // Get the conversion factor from milliseconds to absolute time // which is what the time-constraints call needs. mach_timebase_info_data_t tb_info; mach_timebase_info(&tb_info); double timeFact = ((double)tb_info.denom / (double)tb_info.numer) * 1000000; thread_time_constraint_policy_data_t ttcpolicy; // in Chrome: period = 2.9ms ~= 128 frames @44.1KHz, comp = 0.75 * period, constr = 0.85 * period. ttcpolicy.period = dutyCicleMs * timeFact; ttcpolicy.computation = dutyCicleMs * 0.75 * timeFact; ttcpolicy.constraint = dutyCicleMs * 0.85 * timeFact; ttcpolicy.preemptible = 0; ret = thread_policy_set(threadport, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } } #else void setRealtime(double dutyCicleMs) {} // not implemented yet #endif <|endoftext|>
<commit_before><commit_msg>add application/ogg mime type BUG=18000 TEST=unknown which websites this affects. ask andrew who reported the bug.<commit_after><|endoftext|>
<commit_before>#include "../columns/Communicator.hpp" #include <assert.h> #include <gdal_priv.h> #include <mpi.h> #include <ogr_spatialref.h> #undef DEBUG_OUTPUT static void copyToLocBuffer(int buf[], LayerLoc * loc) { buf[0] = loc->nx; buf[1] = loc->ny; buf[2] = loc->nxGlobal; buf[3] = loc->nyGlobal; buf[4] = loc->kx0; buf[5] = loc->ky0; buf[6] = loc->nPad; buf[7] = loc->nBands; } static void copyFromLocBuffer(int buf[], LayerLoc * loc) { loc->nx = buf[0]; loc->ny = buf[1]; loc->nxGlobal = buf[2]; loc->nyGlobal = buf[3]; loc->kx0 = buf[4]; loc->ky0 = buf[5]; loc->nPad = buf[6]; loc->nBands = buf[7]; } /** * Calculates location information given processor distribution and the * size of the image. * * @filename the name of the image file (in) * @ic the inter-column communicator (in) * @loc location information (inout) (loc->nx and loc->ny are out) */ int getImageInfo(const char* filename, PV::Communicator * comm, LayerLoc * loc) { const int locSize = sizeof(LayerLoc) / sizeof(int); int locBuf[locSize]; int status = 0; // LayerLoc should contain 8 ints assert(locSize == 8); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icCol = comm->commColumn(); const int icRow = comm->commRow(); #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: nxProcs==%d nyProcs==%d icRow==%d icCol==%d\n", comm->commRank(), nxProcs, nyProcs, icRow, icCol); #endif if (comm->commRank() == 0) { GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); if (dataset == NULL) return 1; int xImageSize = dataset->GetRasterXSize(); int yImageSize = dataset->GetRasterYSize(); loc->nBands = dataset->GetRasterCount(); // calculate local layer size int nx = xImageSize / nxProcs; int ny = yImageSize / nyProcs; loc->nx = nx; loc->ny = ny; loc->nxGlobal = nxProcs * nx; loc->nyGlobal = nyProcs * ny; copyToLocBuffer(locBuf, loc); GDALClose(dataset); } // broadcast location information MPI_Bcast(locBuf, 1+locSize, MPI_INT, 0, comm->communicator()); copyFromLocBuffer(locBuf, loc); // fix up layer indices loc->kx0 = loc->nx * icCol; loc->ky0 = loc->ny * icRow; return status; } /** * @filename */ int scatterImageFile(const char * filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; const int tag = 13; const int maxBands = 3; const MPI_Comm mpi_comm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int nx = loc->nx; const int ny = loc->ny; const int numBands = loc->nBands; assert(numBands <= maxBands); const int nxny = nx * ny; const int numTotal = nxny * numBands; if (icRank > 0) { const int src = 0; for (int b = 0; b < numBands; b++) { MPI_Recv(&buf[b*nxny], numTotal, MPI_FLOAT, src, tag, mpi_comm, MPI_STATUS_IGNORE); } #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: scatter: received from 0, nx==%d ny==%d size==%d\n", comm->commRank(), nx, ny, numTotal); #endif } else { GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); int xImageSize = dataset->GetRasterXSize(); int yImageSize = dataset->GetRasterYSize(); int xTotalSize = nx * nxProcs; int yTotalSize = ny * nyProcs; if (xTotalSize > xImageSize || yTotalSize > yImageSize) { fprintf(stderr, "[ 0]: scatterImageFile: image size too small, " "xTotalSize==%d xImageSize==%d yTotalSize==%d yImageSize==%d\n", xTotalSize, xImageSize, yTotalSize, yImageSize); fprintf(stderr, "[ 0]: xSize==%d ySize==%d nxProcs==%d nyProcs==%d\n", nx, ny, nxProcs, nyProcs); GDALClose(dataset); return -1; } GDALRasterBand * band[maxBands]; assert(numBands <= dataset->GetRasterCount()); for (int b = 0; b < numBands; b++) { band[b] = dataset->GetRasterBand(b+1); } int dest = -1; for (int py = 0; py < nyProcs; py++) { for (int px = 0; px < nxProcs; px++) { if (++dest == 0) continue; int kx = nx * px; int ky = ny * py; #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: scatter: sending to %d xSize==%d" " ySize==%d size==%d total==%d\n", comm->commRank(), dest, nx, ny, nx*ny, nx*ny*comm->commSize()); #endif for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Read, kx, ky, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); MPI_Send(&buf[b*nxny], nx*ny, MPI_FLOAT, dest, tag, mpi_comm); } } } // get local image portion for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Read, 0, 0, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } GDALClose(dataset); } return status; } /** * @filename */ int gatherImageFile(const char * filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; const int tag = 14; const int maxBands = 3; const MPI_Comm mpi_comm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int nx = loc->nx; const int ny = loc->ny; const int numBands = loc->nBands; assert(numBands <= maxBands); const int nxny = nx * ny; const int numTotal = nxny * numBands; if (icRank > 0) { const int dest = 0; for (int b = 0; b < numBands; b++) { MPI_Send(&buf[b*nxny], nx*ny, MPI_FLOAT, dest, tag, mpi_comm); } #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: sent to 0, nx==%d ny==%d size==%d\n", comm->commRank(), nx, ny, nx*ny); #endif } else { //#include "cpl_string.h" GDALAllRegister(); char ** metadata; GDALDriver * driver = GetGDALDriverManager()->GetDriverByName("GTiff"); if( driver == NULL ) exit( 1 ); metadata = driver->GetMetadata(); if( CSLFetchBoolean( metadata, GDAL_DCAP_CREATE, FALSE ) ) { // printf("Driver %s supports Create() method.\n", "GTiff"); } GDALDataset * dataset; char ** options = NULL; int xImageSize = nx * nxProcs; int yImageSize = ny * nyProcs; dataset = driver->Create(filename, xImageSize, yImageSize, numBands, GDT_Byte, options); if (dataset == NULL) { fprintf(stderr, "[%2d]: gather: failed to open file %s\n", comm->commRank(), filename); } else { #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: opened file %s\n", comm->commRank(), filename); #endif } // double adfGeoTransform[6] = { 444720, 30, 0, 3751320, 0, -30 }; // OGRSpatialReference oSRS; // char *pszSRS_WKT = NULL; // dataset->SetGeoTransform( adfGeoTransform ); // oSRS.SetUTM( 11, TRUE ); // oSRS.SetWellKnownGeogCS( "NAD27" ); // oSRS.exportToWkt( &pszSRS_WKT ); // dataset->SetProjection( pszSRS_WKT ); // CPLFree( pszSRS_WKT ); GDALRasterBand * band[maxBands]; assert(numBands <= dataset->GetRasterCount()); for (int b = 0; b < numBands; b++) { band[b] = dataset->GetRasterBand(b+1); } // write local image portion for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Write, 0, 0, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } int src = -1; for (int py = 0; py < nyProcs; py++) { for (int px = 0; px < nxProcs; px++) { if (++src == 0) continue; int kx = nx * px; int ky = ny * py; #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: receiving from %d xSize==%d" " ySize==%d size==%d total==%d\n", comm->commRank(), src, nx, ny, numTotal, numTotal*comm->commSize()); #endif for (int b = 0; b < numBands; b++) { MPI_Recv(&buf[b*nxny], numTotal, MPI_FLOAT, src, tag, mpi_comm, MPI_STATUS_IGNORE); band[b]->RasterIO(GF_Write, kx, ky, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } } } GDALClose(dataset); } return status; } int scatterImageBlocks(const char* filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; #ifdef UNIMPLEMENTED const MPI_Comm icComm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int icCol = comm->commColumn(); const int icRow = comm->commRow(); const int nx = loc->nx; const int ny = loc->ny; const int nxGlobal = loc->nxGlobal; const int nyBorder = loc->nyBorder; const int xSize = nx + 2 * nxGlobal; const int ySize = ny + 2 * nyBorder; if (icRank > 0) { } else { int nxBlocks, nyBlocks, nxBlockSize, nyBlockSize; int ixBlock, iyBlock; GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); GDALRasterBand * band = dataset->GetRasterBand(1); CPLAssert(band->GetRasterDataType() == GDT_Byte); band->GetBlockSize(&nxBlockSize, &nyBlockSize); nxBlocks = (band->GetXSize() + nxBlockSize - 1) / nxBlockSize; nyBlocks = (band->GetYSize() + nyBlockSize - 1) / nyBlockSize; GByte * data = (GByte *) CPLMalloc(nxBlockSize * nyBlockSize); fprintf(stderr, "[ 0]: nxBlockSize==%d nyBlockSize==%d" " nxBlocks==%d nyBlocks==%d\n", nxBlockSize, nyBlockSize, nxBlocks, nyBlocks); for (iyBlock = 0; iyBlock < nyBlocks; iyBlock++) { for (ixBlock = 0; ixBlock < nxBlocks; ixBlock++) { int nxValid, nyValid; band->ReadBlock(ixBlock, ixBlock, data); } } } #endif return status; } /** * gather relevant portions of buf on root process from all others * NOTE: buf is np times larger on root process */ int gather (PV::Communicator * comm, LayerLoc * loc, float * buf) { return -1; } /** * scatter relevant portions of buf from root process to all others * NOTE: buf is np times larger on root process */ int scatter(PV::Communicator * comm, LayerLoc * loc, float * buf) { return -1; } int writeWithBorders(const char * filename, LayerLoc * loc, float * buf) { int X = loc->nx + 2 * loc->nPad; int Y = loc->ny + 2 * loc->nPad; int B = loc->nBands; GDALDriver * driver = GetGDALDriverManager()->GetDriverByName("GTiff"); GDALDataset* layer_file = driver->Create(filename, X, Y, B, GDT_Byte, NULL); // TODO - add multiple raster bands GDALRasterBand * band = layer_file->GetRasterBand(1); band->RasterIO(GF_Write, 0, 0, X, Y, buf, X, Y, GDT_Float32, 0, 0); GDALClose(layer_file); return 0; } <commit_msg>Added optional use of MPI (for PANN).<commit_after>#include "imageio.hpp" #include <assert.h> #include <gdal_priv.h> #include <ogr_spatialref.h> #undef DEBUG_OUTPUT static void copyToLocBuffer(int buf[], LayerLoc * loc) { buf[0] = loc->nx; buf[1] = loc->ny; buf[2] = loc->nxGlobal; buf[3] = loc->nyGlobal; buf[4] = loc->kx0; buf[5] = loc->ky0; buf[6] = loc->nPad; buf[7] = loc->nBands; } static void copyFromLocBuffer(int buf[], LayerLoc * loc) { loc->nx = buf[0]; loc->ny = buf[1]; loc->nxGlobal = buf[2]; loc->nyGlobal = buf[3]; loc->kx0 = buf[4]; loc->ky0 = buf[5]; loc->nPad = buf[6]; loc->nBands = buf[7]; } /** * Calculates location information given processor distribution and the * size of the image. * * @filename the name of the image file (in) * @ic the inter-column communicator (in) * @loc location information (inout) (loc->nx and loc->ny are out) */ int getImageInfo(const char* filename, PV::Communicator * comm, LayerLoc * loc) { const int locSize = sizeof(LayerLoc) / sizeof(int); int locBuf[locSize]; int status = 0; // LayerLoc should contain 8 ints assert(locSize == 8); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icCol = comm->commColumn(); const int icRow = comm->commRow(); #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: nxProcs==%d nyProcs==%d icRow==%d icCol==%d\n", comm->commRank(), nxProcs, nyProcs, icRow, icCol); #endif if (comm->commRank() == 0) { GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); if (dataset == NULL) return 1; int xImageSize = dataset->GetRasterXSize(); int yImageSize = dataset->GetRasterYSize(); loc->nBands = dataset->GetRasterCount(); // calculate local layer size int nx = xImageSize / nxProcs; int ny = yImageSize / nyProcs; loc->nx = nx; loc->ny = ny; loc->nxGlobal = nxProcs * nx; loc->nyGlobal = nyProcs * ny; copyToLocBuffer(locBuf, loc); GDALClose(dataset); } #ifdef PV_USE_MPI // broadcast location information MPI_Bcast(locBuf, 1+locSize, MPI_INT, 0, comm->communicator()); #endif copyFromLocBuffer(locBuf, loc); // fix up layer indices loc->kx0 = loc->nx * icCol; loc->ky0 = loc->ny * icRow; return status; } /** * @filename */ int scatterImageFile(const char * filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; const int maxBands = 3; const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int nx = loc->nx; const int ny = loc->ny; const int numBands = loc->nBands; assert(numBands <= maxBands); const int nxny = nx * ny; if (icRank > 0) { #ifdef PV_USE_MPI const int numTotal = nxny * numBands; const int src = 0; const int tag = 13; const MPI_Comm mpi_comm = comm->communicator(); for (int b = 0; b < numBands; b++) { MPI_Recv(&buf[b*nxny], numTotal, MPI_FLOAT, src, tag, mpi_comm, MPI_STATUS_IGNORE); } #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: scatter: received from 0, nx==%d ny==%d size==%d\n", comm->commRank(), nx, ny, numTotal); #endif #endif // PV_USE_MPI } else { GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); int xImageSize = dataset->GetRasterXSize(); int yImageSize = dataset->GetRasterYSize(); int xTotalSize = nx * nxProcs; int yTotalSize = ny * nyProcs; if (xTotalSize > xImageSize || yTotalSize > yImageSize) { fprintf(stderr, "[ 0]: scatterImageFile: image size too small, " "xTotalSize==%d xImageSize==%d yTotalSize==%d yImageSize==%d\n", xTotalSize, xImageSize, yTotalSize, yImageSize); fprintf(stderr, "[ 0]: xSize==%d ySize==%d nxProcs==%d nyProcs==%d\n", nx, ny, nxProcs, nyProcs); GDALClose(dataset); return -1; } GDALRasterBand * band[maxBands]; assert(numBands <= dataset->GetRasterCount()); for (int b = 0; b < numBands; b++) { band[b] = dataset->GetRasterBand(b+1); } #ifdef PV_USE_MPI int dest = -1; const int tag = 13; const MPI_Comm mpi_comm = comm->communicator(); for (int py = 0; py < nyProcs; py++) { for (int px = 0; px < nxProcs; px++) { if (++dest == 0) continue; int kx = nx * px; int ky = ny * py; #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: scatter: sending to %d xSize==%d" " ySize==%d size==%d total==%d\n", comm->commRank(), dest, nx, ny, nx*ny, nx*ny*comm->commSize()); #endif for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Read, kx, ky, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); MPI_Send(&buf[b*nxny], nx*ny, MPI_FLOAT, dest, tag, mpi_comm); } } } #endif // PV_USE_MPI // get local image portion for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Read, 0, 0, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } GDALClose(dataset); } return status; } /** * @filename */ int gatherImageFile(const char * filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; const int maxBands = 3; const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int nx = loc->nx; const int ny = loc->ny; const int numBands = loc->nBands; assert(numBands <= maxBands); const int nxny = nx * ny; #ifdef PV_USE_MPI const int tag = 14; const int numTotal = nxny * numBands; const MPI_Comm mpi_comm = comm->communicator(); #endif // PV_USE_MPI if (icRank > 0) { #ifdef PV_USE_MPI const int dest = 0; for (int b = 0; b < numBands; b++) { MPI_Send(&buf[b*nxny], nx*ny, MPI_FLOAT, dest, tag, mpi_comm); } #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: sent to 0, nx==%d ny==%d size==%d\n", comm->commRank(), nx, ny, nx*ny); #endif #endif // PV_USE_MPI } else { GDALAllRegister(); char ** metadata; GDALDriver * driver = GetGDALDriverManager()->GetDriverByName("GTiff"); if( driver == NULL ) exit( 1 ); metadata = driver->GetMetadata(); if( CSLFetchBoolean( metadata, GDAL_DCAP_CREATE, FALSE ) ) { // printf("Driver %s supports Create() method.\n", "GTiff"); } GDALDataset * dataset; char ** options = NULL; int xImageSize = nx * nxProcs; int yImageSize = ny * nyProcs; dataset = driver->Create(filename, xImageSize, yImageSize, numBands, GDT_Byte, options); if (dataset == NULL) { fprintf(stderr, "[%2d]: gather: failed to open file %s\n", comm->commRank(), filename); } else { #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: opened file %s\n", comm->commRank(), filename); #endif } // double adfGeoTransform[6] = { 444720, 30, 0, 3751320, 0, -30 }; // OGRSpatialReference oSRS; // char *pszSRS_WKT = NULL; // dataset->SetGeoTransform( adfGeoTransform ); // oSRS.SetUTM( 11, TRUE ); // oSRS.SetWellKnownGeogCS( "NAD27" ); // oSRS.exportToWkt( &pszSRS_WKT ); // dataset->SetProjection( pszSRS_WKT ); // CPLFree( pszSRS_WKT ); GDALRasterBand * band[maxBands]; assert(numBands <= dataset->GetRasterCount()); for (int b = 0; b < numBands; b++) { band[b] = dataset->GetRasterBand(b+1); } // write local image portion for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Write, 0, 0, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } #ifdef PV_USE_MPI int src = -1; for (int py = 0; py < nyProcs; py++) { for (int px = 0; px < nxProcs; px++) { if (++src == 0) continue; int kx = nx * px; int ky = ny * py; #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: receiving from %d xSize==%d" " ySize==%d size==%d total==%d\n", comm->commRank(), src, nx, ny, numTotal, numTotal*comm->commSize()); #endif for (int b = 0; b < numBands; b++) { MPI_Recv(&buf[b*nxny], numTotal, MPI_FLOAT, src, tag, mpi_comm, MPI_STATUS_IGNORE); band[b]->RasterIO(GF_Write, kx, ky, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } } } #endif // PV_USE_MPI GDALClose(dataset); } return status; } int scatterImageBlocks(const char* filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; #ifdef UNIMPLEMENTED const MPI_Comm icComm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int icCol = comm->commColumn(); const int icRow = comm->commRow(); const int nx = loc->nx; const int ny = loc->ny; const int nxGlobal = loc->nxGlobal; const int nyBorder = loc->nyBorder; const int xSize = nx + 2 * nxGlobal; const int ySize = ny + 2 * nyBorder; if (icRank > 0) { } else { int nxBlocks, nyBlocks, nxBlockSize, nyBlockSize; int ixBlock, iyBlock; GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); GDALRasterBand * band = dataset->GetRasterBand(1); CPLAssert(band->GetRasterDataType() == GDT_Byte); band->GetBlockSize(&nxBlockSize, &nyBlockSize); nxBlocks = (band->GetXSize() + nxBlockSize - 1) / nxBlockSize; nyBlocks = (band->GetYSize() + nyBlockSize - 1) / nyBlockSize; GByte * data = (GByte *) CPLMalloc(nxBlockSize * nyBlockSize); fprintf(stderr, "[ 0]: nxBlockSize==%d nyBlockSize==%d" " nxBlocks==%d nyBlocks==%d\n", nxBlockSize, nyBlockSize, nxBlocks, nyBlocks); for (iyBlock = 0; iyBlock < nyBlocks; iyBlock++) { for (ixBlock = 0; ixBlock < nxBlocks; ixBlock++) { int nxValid, nyValid; band->ReadBlock(ixBlock, ixBlock, data); } } } #endif return status; } /** * gather relevant portions of buf on root process from all others * NOTE: buf is np times larger on root process */ int gather (PV::Communicator * comm, LayerLoc * loc, float * buf) { return -1; } /** * scatter relevant portions of buf from root process to all others * NOTE: buf is np times larger on root process */ int scatter(PV::Communicator * comm, LayerLoc * loc, float * buf) { return -1; } int writeWithBorders(const char * filename, LayerLoc * loc, float * buf) { int X = loc->nx + 2 * loc->nPad; int Y = loc->ny + 2 * loc->nPad; int B = loc->nBands; GDALDriver * driver = GetGDALDriverManager()->GetDriverByName("GTiff"); GDALDataset* layer_file = driver->Create(filename, X, Y, B, GDT_Byte, NULL); // TODO - add multiple raster bands GDALRasterBand * band = layer_file->GetRasterBand(1); band->RasterIO(GF_Write, 0, 0, X, Y, buf, X, Y, GDT_Float32, 0, 0); GDALClose(layer_file); return 0; } <|endoftext|>
<commit_before>#pragma once #ifndef SIMRANK_HPP #define SIMRANK_HPP #include <unordered_map> #include <unordered_set> #include <vector> #include <cmath> #include <algorithm> #include <iterator> template<typename T, typename I> class Iterator_Wrapper { private: const T &collection_; public: inline Iterator_Wrapper(const T &collection) : collection_(collection) {} inline const I begin(void) const { return I(collection_.begin()); } inline const I end(void) const { return I(collection_.end()); } inline Iterator_Wrapper &operator=(const Iterator_Wrapper &) { return *this; } }; template<typename T> class Key_Iterator { private: typename T::const_iterator pos_; public: inline Key_Iterator(typename T::const_iterator pos) : pos_(pos) {} inline typename T::key_type operator*() { return pos_->first; } inline bool operator!=(const Key_Iterator &other) const { return pos_ != other.pos_; } inline const Key_Iterator &operator++() { ++pos_; return *this; } }; template<typename T> using Key_Iterator_Wrapper = Iterator_Wrapper<T, Key_Iterator<T>>; template<typename T> using Const_Iterator_Wrapper = Iterator_Wrapper<T, typename T::const_iterator>; template<typename K, typename V> using umap = std::unordered_map<K, V>; template<typename T> using uset = std::unordered_set<T>; template<typename node_t, typename float_t> class SimRank { public: SimRank(size_t K = 6, float_t C = 0.6, float_t D = 0.05); ~SimRank(); // Reserve space in memory for at least n nodes void reserve(size_t n); // Add an edge to the graph void add_edge(node_t head, node_t tail, float_t weight = 1); // Calculate SimRank scores after adding all the edges void calculate_simrank(void); // Return the similarity score between nodes a and b float_t similarity(node_t a, node_t b) const; // Return the number of iterations inline size_t K(void) const { return K_; } // Return the decay factor inline float_t C(void) const { return C_; } // Return the delta for threshold sieving inline float_t D(void) const { return D_; } // Return the number of nodes in the graph inline size_t num_nodes(void) const { return node_properties_.size(); } // Return the number of nodes with out-degree > 0 inline size_t num_heads(void) const { return edge_weights_.size(); } // Return the number of nodes with in-degree > 0 inline size_t num_tails(void) const { return in_neighbors_.size(); } // Edge data accessible via edges() struct edge_t { node_t head, tail; float_t weight; inline edge_t(node_t head, node_t tail, float_t weight) : head(head), tail(tail), weight(weight) {} }; struct node_prop_t; // Iterate over all nodes, e.g. "for (node_t x : simrank.nodes()) { ... }" inline const Key_Iterator_Wrapper<umap<node_t, node_prop_t>> nodes(void) const { return Key_Iterator_Wrapper<umap<node_t, node_prop_t>>(node_properties_); } class edge_iterable; // Iterate over all edges, e.g. "for (SimRank::edge_t e : simrank.edges()) { ... }" inline const edge_iterable edges(void) const { return edge_iterable(edge_weights_); } // Return the out-degree of node x (the sum of the outgoing edges' weights) inline float_t out_degree(node_t x) { return node_properties_[x].out_degree; } // Return the in-degree of node x (the sum of the incoming edges' weights) inline float_t in_degree(node_t x) { return node_properties_[x].in_degree; } // Iterate over the out-neighbors of node x, e.g. "for (node_t y : simrank.out_neighbors(x)) { ... }" inline const Key_Iterator_Wrapper<umap<node_t, float_t>> out_neighbors(node_t x) { return Key_Iterator_Wrapper<umap<node_t, float_t>>(edge_weights_[x]); } // Iterate over the in-neighbors of node x, e.g. "for (node_t y : simrank.in_neighbors(x)) { ... }" inline const Const_Iterator_Wrapper<uset<node_t>> in_neighbors(node_t x) { return Const_Iterator_Wrapper<uset<node_t>>(in_neighbors_[x]); } // Return the weight of the edge from a to b (normalized after calling calculate_simrank()) inline float_t edge_weight(node_t a, node_t b) { return edge_weights_[a][b]; } private: struct node_prop_t { umap<node_t, float_t> simrank; float_t partial_sum; float_t in_degree, out_degree; inline node_prop_t(void) : simrank(), partial_sum(), in_degree(), out_degree() {} }; size_t K_; float_t C_; float_t D_; umap<node_t, node_prop_t> node_properties_; // {node1 -> <{node2 -> SimRank}, etc>} (node1 <= node2) umap<node_t, uset<node_t>> in_neighbors_; // {node -> {in-neighbors}} umap<node_t, umap<node_t, float_t>> edge_weights_; // {head -> {tail -> weight}} std::vector<node_t> temp_nodes_; // temporary node storage for calculating essential paired nodes std::vector<node_t> essential_nodes_; // essential paired nodes (reused in each update iteration) float_t *delta_; // deltas for threshold sieving void normalize_edges(void); void update_simrank_scores(node_t a, int k); public: class edge_iterator { typedef typename umap<node_t, umap<node_t, float_t>>::const_iterator pos_iterator; typedef typename umap<node_t, float_t>::const_iterator subpos_iterator; private: pos_iterator pos_, pos_end_; subpos_iterator subpos_, subpos_end_; public: inline edge_iterator(pos_iterator pos, subpos_iterator subpos, pos_iterator pos_end, subpos_iterator subpos_end) : pos_(pos), subpos_(subpos), pos_end_(pos_end), subpos_end_(subpos_end) {} inline edge_t operator*() { return edge_t(pos_->first, subpos_->first, subpos_->second); } inline bool operator!=(const edge_iterator &other) const { return pos_ != other.pos_ || subpos_ != other.subpos_; } inline const edge_iterator &operator++(void) { ++subpos_; if (subpos_ == pos_->second.end()) { ++pos_; subpos_ = pos_ == pos_end_ ? subpos_end_ : pos_->second.begin(); } return *this; } }; class edge_iterable { private: const umap<node_t, umap<node_t, float_t>> &edges_; public: inline edge_iterable(const umap<node_t, umap<node_t, float_t>> &edges) : edges_(edges) {} inline const edge_iterator begin(void) const { return edge_iterator(edges_.begin(), edges_.begin()->second.begin(), edges_.end(), edges_.begin()->second.end()); } inline const edge_iterator end(void) const { return edge_iterator(edges_.end(), edges_.begin()->second.end(), edges_.end(), edges_.begin()->second.end()); } inline edge_iterable &operator=(const edge_iterable &) { return *this; } }; }; template<typename node_t, typename float_t> SimRank<node_t, float_t>::SimRank(size_t K, float_t C, float_t D) : K_(K), C_(C), D_(D), node_properties_(), in_neighbors_(), edge_weights_(), temp_nodes_(), essential_nodes_() { delta_ = new float_t[K]; } template<typename node_t, typename float_t> SimRank<node_t, float_t>::~SimRank() { delete [] delta_; } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::reserve(size_t n) { node_properties_.reserve(n); edge_weights_.reserve(n); in_neighbors_.reserve(n); temp_nodes_.reserve(n); essential_nodes_.reserve(n); } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::add_edge(node_t head, node_t tail, float_t weight) { node_properties_[head].out_degree += weight; node_properties_[tail].in_degree += weight; in_neighbors_[tail].insert(head); edge_weights_[head][tail] += weight; } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::calculate_simrank() { normalize_edges(); // Calculate deltas for threshold sieving for (int m = 0; m < K_; m++) { delta_[m] = (float_t)(D_ / (K_ * pow(C_, K_ - m + 1))); } // Initialize similarity scores for (auto const &a_aps_p : node_properties_) { node_t a = a_aps_p.first; node_properties_[a].simrank.clear(); } // Main loop: update scores for K iterations for (int k = 0; k < K_; k++) { for (auto const &a_aps_p : node_properties_) { node_t a = a_aps_p.first; float_t a_od = a_aps_p.second.out_degree; if (a_od == 0 && k < K_ - 1) { continue; } update_simrank_scores(a, k); } } } template<typename node_t, typename float_t> float_t SimRank<node_t, float_t>::similarity(node_t a, node_t b) const { // similarity(a, a) == 1 if (a == b) { return 1; } // similarity(a, b) == similarity(b, a), so standardize on a < b if (a > b) { std::swap(a, b); } auto a_props = node_properties_.at(a); auto a_b_simrank = a_props.simrank.find(b); if (a_b_simrank == a_props.simrank.end()) { return 0; } return a_b_simrank->second; } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::normalize_edges() { // Divide each edge from a to b by the in-degree of b for (auto &a_bws_p : edge_weights_) { node_t a = a_bws_p.first; auto &bws = a_bws_p.second; for (auto &b_w_p : bws) { node_t b = b_w_p.first; float_t w = b_w_p.second; edge_weights_[a][b] = w / node_properties_[b].in_degree; } } } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::update_simrank_scores(node_t a, int k) { // Calculate partial sums for node a's in-neighbors for (auto &u_ups_p : node_properties_) { node_t u = u_ups_p.first; float_t partial_sum_u = 0; for (node_t i : in_neighbors_[a]) { partial_sum_u += similarity(i, u) * edge_weights_[i][a]; } node_properties_[u].partial_sum = partial_sum_u; } // Calculate essential paired nodes for node a essential_nodes_.clear(); // Construct set of temporary nodes temp_nodes_.clear(); for (auto const &v_vps_p : node_properties_) { node_t v = v_vps_p.first; for (node_t u : in_neighbors_[a]) { if (similarity(u, v) > 0) { temp_nodes_.push_back(v); break; } } } // Construct set of essential paired nodes for (auto const &b_bps_p : node_properties_) { node_t b = b_bps_p.first; for (node_t v : temp_nodes_) { if (in_neighbors_[b].find(v) != in_neighbors_[b].end()) { essential_nodes_.push_back(b); break; } } } // Main loop: account for node b's in-neighbors for (node_t b : essential_nodes_) { float_t score_a_b = 0; for (node_t j : in_neighbors_[b]) { score_a_b += node_properties_[j].partial_sum * edge_weights_[j][b]; } score_a_b *= C_; if (score_a_b > delta_[k] || similarity(a, b) > 0) { node_properties_[a].simrank[b] = score_a_b; } } } #endif <commit_msg>Make forward declaration of node_prop_t private.<commit_after>#pragma once #ifndef SIMRANK_HPP #define SIMRANK_HPP #include <unordered_map> #include <unordered_set> #include <vector> #include <cmath> #include <algorithm> #include <iterator> template<typename T, typename I> class Iterator_Wrapper { private: const T &collection_; public: inline Iterator_Wrapper(const T &collection) : collection_(collection) {} inline const I begin(void) const { return I(collection_.begin()); } inline const I end(void) const { return I(collection_.end()); } inline Iterator_Wrapper &operator=(const Iterator_Wrapper &) { return *this; } }; template<typename T> class Key_Iterator { private: typename T::const_iterator pos_; public: inline Key_Iterator(typename T::const_iterator pos) : pos_(pos) {} inline typename T::key_type operator*() { return pos_->first; } inline bool operator!=(const Key_Iterator &other) const { return pos_ != other.pos_; } inline const Key_Iterator &operator++() { ++pos_; return *this; } }; template<typename T> using Key_Iterator_Wrapper = Iterator_Wrapper<T, Key_Iterator<T>>; template<typename T> using Const_Iterator_Wrapper = Iterator_Wrapper<T, typename T::const_iterator>; template<typename K, typename V> using umap = std::unordered_map<K, V>; template<typename T> using uset = std::unordered_set<T>; template<typename node_t, typename float_t> class SimRank { public: SimRank(size_t K = 6, float_t C = 0.6, float_t D = 0.05); ~SimRank(); // Reserve space in memory for at least n nodes void reserve(size_t n); // Add an edge to the graph void add_edge(node_t head, node_t tail, float_t weight = 1); // Calculate SimRank scores after adding all the edges void calculate_simrank(void); // Return the similarity score between nodes a and b float_t similarity(node_t a, node_t b) const; // Return the number of iterations inline size_t K(void) const { return K_; } // Return the decay factor inline float_t C(void) const { return C_; } // Return the delta for threshold sieving inline float_t D(void) const { return D_; } // Return the number of nodes in the graph inline size_t num_nodes(void) const { return node_properties_.size(); } // Return the number of nodes with out-degree > 0 inline size_t num_heads(void) const { return edge_weights_.size(); } // Return the number of nodes with in-degree > 0 inline size_t num_tails(void) const { return in_neighbors_.size(); } // Edge data accessible via edges() struct edge_t { node_t head, tail; float_t weight; inline edge_t(node_t head, node_t tail, float_t weight) : head(head), tail(tail), weight(weight) {} }; private: struct node_prop_t; public: // Iterate over all nodes, e.g. "for (node_t x : simrank.nodes()) { ... }" inline const Key_Iterator_Wrapper<umap<node_t, node_prop_t>> nodes(void) const { return Key_Iterator_Wrapper<umap<node_t, node_prop_t>>(node_properties_); } class edge_iterable; // Iterate over all edges, e.g. "for (SimRank::edge_t e : simrank.edges()) { ... }" inline const edge_iterable edges(void) const { return edge_iterable(edge_weights_); } // Return the out-degree of node x (the sum of the outgoing edges' weights) inline float_t out_degree(node_t x) { return node_properties_[x].out_degree; } // Return the in-degree of node x (the sum of the incoming edges' weights) inline float_t in_degree(node_t x) { return node_properties_[x].in_degree; } // Iterate over the out-neighbors of node x, e.g. "for (node_t y : simrank.out_neighbors(x)) { ... }" inline const Key_Iterator_Wrapper<umap<node_t, float_t>> out_neighbors(node_t x) { return Key_Iterator_Wrapper<umap<node_t, float_t>>(edge_weights_[x]); } // Iterate over the in-neighbors of node x, e.g. "for (node_t y : simrank.in_neighbors(x)) { ... }" inline const Const_Iterator_Wrapper<uset<node_t>> in_neighbors(node_t x) { return Const_Iterator_Wrapper<uset<node_t>>(in_neighbors_[x]); } // Return the weight of the edge from a to b (normalized after calling calculate_simrank()) inline float_t edge_weight(node_t a, node_t b) { return edge_weights_[a][b]; } private: struct node_prop_t { umap<node_t, float_t> simrank; float_t partial_sum; float_t in_degree, out_degree; inline node_prop_t(void) : simrank(), partial_sum(), in_degree(), out_degree() {} }; size_t K_; float_t C_; float_t D_; umap<node_t, node_prop_t> node_properties_; // {node1 -> <{node2 -> SimRank}, etc>} (node1 <= node2) umap<node_t, uset<node_t>> in_neighbors_; // {node -> {in-neighbors}} umap<node_t, umap<node_t, float_t>> edge_weights_; // {head -> {tail -> weight}} std::vector<node_t> temp_nodes_; // temporary node storage for calculating essential paired nodes std::vector<node_t> essential_nodes_; // essential paired nodes (reused in each update iteration) float_t *delta_; // deltas for threshold sieving void normalize_edges(void); void update_simrank_scores(node_t a, int k); public: class edge_iterator { typedef typename umap<node_t, umap<node_t, float_t>>::const_iterator pos_iterator; typedef typename umap<node_t, float_t>::const_iterator subpos_iterator; private: pos_iterator pos_, pos_end_; subpos_iterator subpos_, subpos_end_; public: inline edge_iterator(pos_iterator pos, subpos_iterator subpos, pos_iterator pos_end, subpos_iterator subpos_end) : pos_(pos), subpos_(subpos), pos_end_(pos_end), subpos_end_(subpos_end) {} inline edge_t operator*() { return edge_t(pos_->first, subpos_->first, subpos_->second); } inline bool operator!=(const edge_iterator &other) const { return pos_ != other.pos_ || subpos_ != other.subpos_; } inline const edge_iterator &operator++(void) { ++subpos_; if (subpos_ == pos_->second.end()) { ++pos_; subpos_ = pos_ == pos_end_ ? subpos_end_ : pos_->second.begin(); } return *this; } }; class edge_iterable { private: const umap<node_t, umap<node_t, float_t>> &edges_; public: inline edge_iterable(const umap<node_t, umap<node_t, float_t>> &edges) : edges_(edges) {} inline const edge_iterator begin(void) const { return edge_iterator(edges_.begin(), edges_.begin()->second.begin(), edges_.end(), edges_.begin()->second.end()); } inline const edge_iterator end(void) const { return edge_iterator(edges_.end(), edges_.begin()->second.end(), edges_.end(), edges_.begin()->second.end()); } inline edge_iterable &operator=(const edge_iterable &) { return *this; } }; }; template<typename node_t, typename float_t> SimRank<node_t, float_t>::SimRank(size_t K, float_t C, float_t D) : K_(K), C_(C), D_(D), node_properties_(), in_neighbors_(), edge_weights_(), temp_nodes_(), essential_nodes_() { delta_ = new float_t[K]; } template<typename node_t, typename float_t> SimRank<node_t, float_t>::~SimRank() { delete [] delta_; } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::reserve(size_t n) { node_properties_.reserve(n); edge_weights_.reserve(n); in_neighbors_.reserve(n); temp_nodes_.reserve(n); essential_nodes_.reserve(n); } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::add_edge(node_t head, node_t tail, float_t weight) { node_properties_[head].out_degree += weight; node_properties_[tail].in_degree += weight; in_neighbors_[tail].insert(head); edge_weights_[head][tail] += weight; } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::calculate_simrank() { normalize_edges(); // Calculate deltas for threshold sieving for (int m = 0; m < K_; m++) { delta_[m] = (float_t)(D_ / (K_ * pow(C_, K_ - m + 1))); } // Initialize similarity scores for (auto const &a_aps_p : node_properties_) { node_t a = a_aps_p.first; node_properties_[a].simrank.clear(); } // Main loop: update scores for K iterations for (int k = 0; k < K_; k++) { for (auto const &a_aps_p : node_properties_) { node_t a = a_aps_p.first; float_t a_od = a_aps_p.second.out_degree; if (a_od == 0 && k < K_ - 1) { continue; } update_simrank_scores(a, k); } } } template<typename node_t, typename float_t> float_t SimRank<node_t, float_t>::similarity(node_t a, node_t b) const { // similarity(a, a) == 1 if (a == b) { return 1; } // similarity(a, b) == similarity(b, a), so standardize on a < b if (a > b) { std::swap(a, b); } auto a_props = node_properties_.at(a); auto a_b_simrank = a_props.simrank.find(b); if (a_b_simrank == a_props.simrank.end()) { return 0; } return a_b_simrank->second; } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::normalize_edges() { // Divide each edge from a to b by the in-degree of b for (auto &a_bws_p : edge_weights_) { node_t a = a_bws_p.first; auto &bws = a_bws_p.second; for (auto &b_w_p : bws) { node_t b = b_w_p.first; float_t w = b_w_p.second; edge_weights_[a][b] = w / node_properties_[b].in_degree; } } } template<typename node_t, typename float_t> void SimRank<node_t, float_t>::update_simrank_scores(node_t a, int k) { // Calculate partial sums for node a's in-neighbors for (auto &u_ups_p : node_properties_) { node_t u = u_ups_p.first; float_t partial_sum_u = 0; for (node_t i : in_neighbors_[a]) { partial_sum_u += similarity(i, u) * edge_weights_[i][a]; } node_properties_[u].partial_sum = partial_sum_u; } // Calculate essential paired nodes for node a essential_nodes_.clear(); // Construct set of temporary nodes temp_nodes_.clear(); for (auto const &v_vps_p : node_properties_) { node_t v = v_vps_p.first; for (node_t u : in_neighbors_[a]) { if (similarity(u, v) > 0) { temp_nodes_.push_back(v); break; } } } // Construct set of essential paired nodes for (auto const &b_bps_p : node_properties_) { node_t b = b_bps_p.first; for (node_t v : temp_nodes_) { if (in_neighbors_[b].find(v) != in_neighbors_[b].end()) { essential_nodes_.push_back(b); break; } } } // Main loop: account for node b's in-neighbors for (node_t b : essential_nodes_) { float_t score_a_b = 0; for (node_t j : in_neighbors_[b]) { score_a_b += node_properties_[j].partial_sum * edge_weights_[j][b]; } score_a_b *= C_; if (score_a_b > delta_[k] || similarity(a, b) > 0) { node_properties_[a].simrank[b] = score_a_b; } } } #endif <|endoftext|>
<commit_before>#include "lexer.h" #include "parser.h" #include "binary.h" #include "types.h" #include <iostream> #include <fstream> #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Support/raw_os_ostream.h" #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/JIT.h> #include <llvm/Analysis/Passes.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/DataLayout.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Transforms/Scalar.h> static std::string ErrStr; llvm::FunctionPassManager* fpm; static llvm::ExecutionEngine* theExecutionEngine; llvm::Module* theModule = new llvm::Module("TheModule", llvm::getGlobalContext()); Types types; void DumpModule(llvm::Module* module) { module->dump(); } llvm::Module* CodeGen(ExprAST* ast) { for(auto a = ast; a; a = a->Next()) { llvm::Value* v = a->CodeGen(); if (!v) { std::cerr << "Sorry, something went wrong here..." << std::endl; a->Dump(std::cerr); return 0; } } return theModule; } void OptimizerInit() { fpm = new llvm::FunctionPassManager(theModule); llvm::InitializeNativeTarget(); theExecutionEngine = llvm::EngineBuilder(theModule).setErrorStr(&ErrStr).create(); if (!theExecutionEngine) { std::cerr << "Could not create ExecutionEngine:" << ErrStr << std::endl; exit(1); } // Set up the optimizer pipeline. Start with registering info about how the // target lays out data structures. fpm->add(new llvm::DataLayout(*theExecutionEngine->getDataLayout())); // Promote allocas to registers. fpm->add(llvm::createPromoteMemoryToRegisterPass()); // Provide basic AliasAnalysis support for GVN. fpm->add(llvm::createBasicAliasAnalysisPass()); // Do simple "peephole" optimizations and bit-twiddling optzns. fpm->add(llvm::createInstructionCombiningPass()); // Reassociate expressions. fpm->add(llvm::createReassociatePass()); // Eliminate Common SubExpressions. fpm->add(llvm::createGVNPass()); // Simplify the control flow graph (deleting unreachable blocks, etc). fpm->add(llvm::createCFGSimplificationPass()); } std::string replace_ext(const std::string &origName, const std::string& expectedExt, const std::string& newExt) { if (origName.substr(origName.size() - expectedExt.size()) != expectedExt) { std::cerr << "Could not find extension..." << std::endl; exit(1); return ""; } return origName.substr(0, origName.size() - expectedExt.size()) + newExt; } static void Compile(const std::string& filename) { try { ExprAST* ast; Lexer l(filename, types); Parser p(l, types); OptimizerInit(); ast = p.Parse(); int e = p.GetErrors(); if (e > 0) { std::cout << "Errors in parsing: " << e << ". Exiting..." << std::endl; return; } llvm::Module* module = CodeGen(ast); DumpModule(module); CreateBinary(module, replace_ext(filename, ".pas", ".o"), replace_ext(filename, ".pas", "")); } catch(std::exception e) { std::cerr << "Exception: " << e.what() << std::endl; } catch(...) { std::cerr << "Unknown Exception - this should not happen??? " << std::endl; } } int main(int argc, char** argv) { for(int i = 1; i < argc; i++) { Compile(argv[i]); } } <commit_msg>Revert changes to lacsap.cpp<commit_after>#include "lexer.h" #include "parser.h" #include "binary.h" #include <iostream> #include <fstream> #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Support/raw_os_ostream.h" #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/JIT.h> #include <llvm/Analysis/Passes.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/DataLayout.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Transforms/Scalar.h> static std::string ErrStr; llvm::FunctionPassManager* fpm; static llvm::ExecutionEngine* theExecutionEngine; llvm::Module* theModule = new llvm::Module("TheModule", llvm::getGlobalContext()); void DumpModule(llvm::Module* module) { module->dump(); } llvm::Module* CodeGen(ExprAST* ast) { for(auto a = ast; a; a = a->Next()) { llvm::Value* v = a->CodeGen(); if (!v) { std::cerr << "Sorry, something went wrong here..." << std::endl; a->Dump(std::cerr); return 0; } } return theModule; } void OptimizerInit() { fpm = new llvm::FunctionPassManager(theModule); llvm::InitializeNativeTarget(); theExecutionEngine = llvm::EngineBuilder(theModule).setErrorStr(&ErrStr).create(); if (!theExecutionEngine) { std::cerr << "Could not create ExecutionEngine:" << ErrStr << std::endl; exit(1); } // Set up the optimizer pipeline. Start with registering info about how the // target lays out data structures. fpm->add(new llvm::DataLayout(*theExecutionEngine->getDataLayout())); // Promote allocas to registers. fpm->add(llvm::createPromoteMemoryToRegisterPass()); // Provide basic AliasAnalysis support for GVN. fpm->add(llvm::createBasicAliasAnalysisPass()); // Do simple "peephole" optimizations and bit-twiddling optzns. fpm->add(llvm::createInstructionCombiningPass()); // Reassociate expressions. fpm->add(llvm::createReassociatePass()); // Eliminate Common SubExpressions. fpm->add(llvm::createGVNPass()); // Simplify the control flow graph (deleting unreachable blocks, etc). fpm->add(llvm::createCFGSimplificationPass()); } std::string replace_ext(const std::string &origName, const std::string& expectedExt, const std::string& newExt) { if (origName.substr(origName.size() - expectedExt.size()) != expectedExt) { std::cerr << "Could not find extension..." << std::endl; exit(1); return ""; } return origName.substr(0, origName.size() - expectedExt.size()) + newExt; } static void Compile(const std::string& filename) { try { ExprAST* ast; Types types; Lexer l(filename, types); Parser p(l, types); OptimizerInit(); ast = p.Parse(); int e = p.GetErrors(); if (e > 0) { std::cout << "Errors in parsing: " << e << ". Exiting..." << std::endl; return; } llvm::Module* module = CodeGen(ast); DumpModule(module); CreateBinary(module, replace_ext(filename, ".pas", ".o"), replace_ext(filename, ".pas", "")); } catch(std::exception e) { std::cerr << "Exception: " << e.what() << std::endl; } catch(...) { std::cerr << "Unknown Exception - this should not happen??? " << std::endl; } } int main(int argc, char** argv) { for(int i = 1; i < argc; i++) { Compile(argv[i]); } } <|endoftext|>
<commit_before>#include "framework/logger.h" #include "game/state/tileview/collision.h" #include "game/state/tileview/tile.h" #include "library/voxel.h" using namespace OpenApoc; class FakeSceneryTileObject : public TileObject { public: Vec3<float> position; sp<VoxelMap> voxel; Vec3<float> getPosition() const override { return this->position; } sp<VoxelMap> getVoxelMap(Vec3<int>) override { return this->voxel; } FakeSceneryTileObject(TileMap &map, Vec3<float> bounds, sp<VoxelMap> voxelMap) : TileObject(map, Type::Scenery, bounds), position(0, 0, 0), voxel(voxelMap) { this->name = "FAKE_SCENERY"; } ~FakeSceneryTileObject() override = default; void setPosition(Vec3<float> newPosition) override { this->position = newPosition; TileObject::setPosition(newPosition); } void draw(Renderer &, TileTransform &, Vec2<float>, TileViewMode, int) override { LogError("DRAW CALLED ON FAKE SCENERY??"); exit(EXIT_FAILURE); } }; static void test_collision(const TileMap &map, Vec3<float> line_start, Vec3<float> line_end, sp<TileObject> expected_collision) { auto collision = map.findCollision(line_start, line_end); if (collision.obj != expected_collision) { LogError("Line between {%f,%f,%f} and {%f,%f,%f} collided with %s, expected %s", line_start.x, line_start.y, line_start.z, line_end.x, line_end.y, line_end.z, collision.obj ? collision.obj->getName().cStr() : "NONE", expected_collision ? expected_collision->getName().cStr() : "NONE"); exit(EXIT_FAILURE); } } int main(int, char **) { auto filled_slice_32_32 = mksp<VoxelSlice>(Vec2<int>{32, 32}); for (int y = 0; y < 32; y++) { for (int x = 0; x < 32; x++) { filled_slice_32_32->setBit({x, y}, true); } } auto empty_tilemap_32_32_16 = mksp<VoxelMap>(Vec3<int>{32, 32, 16}); auto filled_tilemap_32_32_16 = mksp<VoxelMap>(Vec3<int>{32, 32, 16}); for (int z = 0; z < 16; z++) { filled_tilemap_32_32_16->setSlice(z, filled_slice_32_32); } // LayerMap is only used for drawing TileMap map{{100, 100, 10}, {1, 1, 1}, {32, 32, 16}, {{TileObject::Type::Scenery}}}; // Spawn some objects std::vector<std::pair<Vec3<float>, sp<TileObject>>> objects = { {Vec3<float>{2.5, 2.5, 2.5}, mksp<FakeSceneryTileObject>(map, Vec3<float>{1, 1, 1}, filled_tilemap_32_32_16)}, {Vec3<float>{99.5, 99.5, 9.5}, mksp<FakeSceneryTileObject>(map, Vec3<float>{1, 1, 1}, filled_tilemap_32_32_16)}, }; for (auto &object : objects) { auto initialPosition = object.first; object.second->setPosition(initialPosition); if (initialPosition != object.second->getPosition()) { LogError("Object %s moved from {%f,%f,%f} to {%f,%f,%f}", object.second->getName().cStr(), initialPosition.x, initialPosition.y, initialPosition.z, object.second->getPosition().x, object.second->getPosition().y, object.second->getPosition().z); exit(EXIT_FAILURE); } } // Compare some expected collisions //{{line_start,line_end},expected_object} std::vector<std::pair<std::array<Vec3<float>, 2>, sp<TileObject>>> collisions = { {{{Vec3<float>{0, 0, 0}, Vec3<float>{1, 1, 1}}}, nullptr}, {{{Vec3<float>{2.1, 2.1, 0}, Vec3<float>{2.1, 2.1, 4}}}, objects[0].second}, {{{Vec3<float>{2.6, 2.6, 0}, Vec3<float>{2.6, 2.6, 4}}}, objects[0].second}, {{{Vec3<float>{2.6, 0, 2.1}, Vec3<float>{2.6, 4, 2.1}}}, objects[0].second}, {{{Vec3<float>{2.6, 0, 2.6}, Vec3<float>{2.6, 4, 2.6}}}, objects[0].second}, {{{Vec3<float>{0, 2.1, 2.1}, Vec3<float>{4, 2.1, 2.1}}}, objects[0].second}, {{{Vec3<float>{0, 2.6, 2.6}, Vec3<float>{4, 2.6, 2.6}}}, objects[0].second}, {{{Vec3<float>{2.1, 2.1, 0}, Vec3<float>{2.1, 2.6, 4}}}, objects[0].second}, {{{Vec3<float>{2.6, 2.6, 0}, Vec3<float>{2.1, 2.6, 4}}}, objects[0].second}, {{{Vec3<float>{2.6, 0, 2.1}, Vec3<float>{2.1, 4, 2.1}}}, objects[0].second}, {{{Vec3<float>{2.1, 0, 2.6}, Vec3<float>{2.6, 4, 2.6}}}, objects[0].second}, {{{Vec3<float>{0, 2.6, 2.6}, Vec3<float>{4, 2.1, 2.6}}}, objects[0].second}, {{{Vec3<float>{0, 2.1, 2.6}, Vec3<float>{4, 2.6, 2.6}}}, objects[0].second}, }; for (auto &collision : collisions) { test_collision(map, collision.first[0], collision.first[1], collision.second); } return EXIT_SUCCESS; } <commit_msg>travis nth fix<commit_after>#include "framework/logger.h" #include "game/state/tileview/collision.h" #include "game/state/tileview/tile.h" #include "library/voxel.h" using namespace OpenApoc; class FakeSceneryTileObject : public TileObject { public: Vec3<float> position; sp<VoxelMap> voxel; Vec3<float> getPosition() const override { return this->position; } bool hasVoxelMap() override { return true; } sp<VoxelMap> getVoxelMap(Vec3<int>) override { return this->voxel; } FakeSceneryTileObject(TileMap &map, Vec3<float> bounds, sp<VoxelMap> voxelMap) : TileObject(map, Type::Scenery, bounds), position(0, 0, 0), voxel(voxelMap) { this->name = "FAKE_SCENERY"; } ~FakeSceneryTileObject() override = default; void setPosition(Vec3<float> newPosition) override { this->position = newPosition; TileObject::setPosition(newPosition); } void draw(Renderer &, TileTransform &, Vec2<float>, TileViewMode, int) override { LogError("DRAW CALLED ON FAKE SCENERY??"); exit(EXIT_FAILURE); } }; static void test_collision(const TileMap &map, Vec3<float> line_start, Vec3<float> line_end, sp<TileObject> expected_collision) { auto collision = map.findCollision(line_start, line_end); if (collision.obj != expected_collision) { LogError("Line between {%f,%f,%f} and {%f,%f,%f} collided with %s, expected %s", line_start.x, line_start.y, line_start.z, line_end.x, line_end.y, line_end.z, collision.obj ? collision.obj->getName().cStr() : "NONE", expected_collision ? expected_collision->getName().cStr() : "NONE"); exit(EXIT_FAILURE); } } int main(int, char **) { auto filled_slice_32_32 = mksp<VoxelSlice>(Vec2<int>{32, 32}); for (int y = 0; y < 32; y++) { for (int x = 0; x < 32; x++) { filled_slice_32_32->setBit({x, y}, true); } } auto empty_tilemap_32_32_16 = mksp<VoxelMap>(Vec3<int>{32, 32, 16}); auto filled_tilemap_32_32_16 = mksp<VoxelMap>(Vec3<int>{32, 32, 16}); for (int z = 0; z < 16; z++) { filled_tilemap_32_32_16->setSlice(z, filled_slice_32_32); } // LayerMap is only used for drawing TileMap map{{100, 100, 10}, {1, 1, 1}, {32, 32, 16}, {{TileObject::Type::Scenery}}}; // Spawn some objects std::vector<std::pair<Vec3<float>, sp<TileObject>>> objects = { {Vec3<float>{2.5, 2.5, 2.5}, mksp<FakeSceneryTileObject>(map, Vec3<float>{1, 1, 1}, filled_tilemap_32_32_16)}, {Vec3<float>{99.5, 99.5, 9.5}, mksp<FakeSceneryTileObject>(map, Vec3<float>{1, 1, 1}, filled_tilemap_32_32_16)}, }; for (auto &object : objects) { auto initialPosition = object.first; object.second->setPosition(initialPosition); if (initialPosition != object.second->getPosition()) { LogError("Object %s moved from {%f,%f,%f} to {%f,%f,%f}", object.second->getName().cStr(), initialPosition.x, initialPosition.y, initialPosition.z, object.second->getPosition().x, object.second->getPosition().y, object.second->getPosition().z); exit(EXIT_FAILURE); } } // Compare some expected collisions //{{line_start,line_end},expected_object} std::vector<std::pair<std::array<Vec3<float>, 2>, sp<TileObject>>> collisions = { {{{Vec3<float>{0, 0, 0}, Vec3<float>{1, 1, 1}}}, nullptr}, {{{Vec3<float>{2.1, 2.1, 0}, Vec3<float>{2.1, 2.1, 4}}}, objects[0].second}, {{{Vec3<float>{2.6, 2.6, 0}, Vec3<float>{2.6, 2.6, 4}}}, objects[0].second}, {{{Vec3<float>{2.6, 0, 2.1}, Vec3<float>{2.6, 4, 2.1}}}, objects[0].second}, {{{Vec3<float>{2.6, 0, 2.6}, Vec3<float>{2.6, 4, 2.6}}}, objects[0].second}, {{{Vec3<float>{0, 2.1, 2.1}, Vec3<float>{4, 2.1, 2.1}}}, objects[0].second}, {{{Vec3<float>{0, 2.6, 2.6}, Vec3<float>{4, 2.6, 2.6}}}, objects[0].second}, {{{Vec3<float>{2.1, 2.1, 0}, Vec3<float>{2.1, 2.6, 4}}}, objects[0].second}, {{{Vec3<float>{2.6, 2.6, 0}, Vec3<float>{2.1, 2.6, 4}}}, objects[0].second}, {{{Vec3<float>{2.6, 0, 2.1}, Vec3<float>{2.1, 4, 2.1}}}, objects[0].second}, {{{Vec3<float>{2.1, 0, 2.6}, Vec3<float>{2.6, 4, 2.6}}}, objects[0].second}, {{{Vec3<float>{0, 2.6, 2.6}, Vec3<float>{4, 2.1, 2.6}}}, objects[0].second}, {{{Vec3<float>{0, 2.1, 2.6}, Vec3<float>{4, 2.6, 2.6}}}, objects[0].second}, }; for (auto &collision : collisions) { test_collision(map, collision.first[0], collision.first[1], collision.second); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2021 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "ComputeDebugSelector.h" #include "Code/QRDUtils.h" #include "ui_ComputeDebugSelector.h" ComputeDebugSelector::ComputeDebugSelector(QWidget *parent) : QDialog(parent), ui(new Ui::ComputeDebugSelector) { ui->setupUi(this); m_threadGroupSize[0] = m_threadGroupSize[1] = m_threadGroupSize[2] = 1; setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->groupX->setFont(Formatter::PreferredFont()); ui->groupY->setFont(Formatter::PreferredFont()); ui->groupZ->setFont(Formatter::PreferredFont()); ui->threadX->setFont(Formatter::PreferredFont()); ui->threadY->setFont(Formatter::PreferredFont()); ui->threadZ->setFont(Formatter::PreferredFont()); ui->dispatchX->setFont(Formatter::PreferredFont()); ui->dispatchY->setFont(Formatter::PreferredFont()); ui->dispatchZ->setFont(Formatter::PreferredFont()); // A threadgroup's size in any dimension can be up to 1024, but a dispatch can be 65535 // threadgroups for a dimension. Use that upper bound to fix the min size of all fields. ui->groupX->setMaximum(65535); int sizeHint = ui->groupX->minimumSizeHint().width(); ui->groupX->setMinimumWidth(sizeHint); ui->groupY->setMinimumWidth(sizeHint); ui->groupZ->setMinimumWidth(sizeHint); ui->threadX->setMinimumWidth(sizeHint); ui->threadY->setMinimumWidth(sizeHint); ui->threadZ->setMinimumWidth(sizeHint); ui->dispatchX->setMinimumWidth(sizeHint); ui->dispatchY->setMinimumWidth(sizeHint); ui->dispatchZ->setMinimumWidth(sizeHint); } ComputeDebugSelector::~ComputeDebugSelector() { delete ui; } void ComputeDebugSelector::SetThreadBounds(const rdcfixedarray<uint32_t, 3> &group, const rdcfixedarray<uint32_t, 3> &thread) { // Set maximums for CS debugging ui->groupX->setMaximum(group[0] - 1); ui->groupY->setMaximum(group[1] - 1); ui->groupZ->setMaximum(group[2] - 1); ui->threadX->setMaximum(thread[0] - 1); ui->threadY->setMaximum(thread[1] - 1); ui->threadZ->setMaximum(thread[2] - 1); ui->dispatchX->setMaximum(group[0] * thread[0] - 1); ui->dispatchY->setMaximum(group[1] * thread[1] - 1); ui->dispatchZ->setMaximum(group[2] * thread[2] - 1); m_threadGroupSize = thread; } void ComputeDebugSelector::SyncGroupThreadValue() { ui->dispatchX->setValue(ui->groupX->value() * m_threadGroupSize[0] + ui->threadX->value()); ui->dispatchY->setValue(ui->groupY->value() * m_threadGroupSize[1] + ui->threadY->value()); ui->dispatchZ->setValue(ui->groupZ->value() * m_threadGroupSize[2] + ui->threadZ->value()); } void ComputeDebugSelector::SyncDispatchThreadValue() { uint32_t group[3] = {ui->dispatchX->value() / m_threadGroupSize[0], ui->dispatchY->value() / m_threadGroupSize[1], ui->dispatchZ->value() / m_threadGroupSize[2]}; uint32_t thread[3] = {ui->dispatchX->value() % m_threadGroupSize[0], ui->dispatchY->value() % m_threadGroupSize[1], ui->dispatchZ->value() % m_threadGroupSize[2]}; ui->groupX->setValue(group[0]); ui->groupY->setValue(group[1]); ui->groupZ->setValue(group[2]); ui->threadX->setValue(thread[0]); ui->threadY->setValue(thread[1]); ui->threadZ->setValue(thread[2]); } void ComputeDebugSelector::on_beginDebug_clicked() { // The dispatch thread IDs and the group/thread IDs are synced on editing either set, so we can // choose either one to begin debugging. uint32_t group[3] = {(uint32_t)ui->groupX->value(), (uint32_t)ui->groupY->value(), (uint32_t)ui->groupZ->value()}; uint32_t thread[3] = {(uint32_t)ui->threadX->value(), (uint32_t)ui->threadY->value(), (uint32_t)ui->threadZ->value()}; emit beginDebug(group, thread); close(); } void ComputeDebugSelector::on_cancelDebug_clicked() { close(); } <commit_msg>Prevent focus reset when typing in the compute debug selector<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2021 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "ComputeDebugSelector.h" #include "Code/QRDUtils.h" #include "ui_ComputeDebugSelector.h" ComputeDebugSelector::ComputeDebugSelector(QWidget *parent) : QDialog(parent), ui(new Ui::ComputeDebugSelector) { ui->setupUi(this); m_threadGroupSize[0] = m_threadGroupSize[1] = m_threadGroupSize[2] = 1; setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->groupX->setFont(Formatter::PreferredFont()); ui->groupY->setFont(Formatter::PreferredFont()); ui->groupZ->setFont(Formatter::PreferredFont()); ui->threadX->setFont(Formatter::PreferredFont()); ui->threadY->setFont(Formatter::PreferredFont()); ui->threadZ->setFont(Formatter::PreferredFont()); ui->dispatchX->setFont(Formatter::PreferredFont()); ui->dispatchY->setFont(Formatter::PreferredFont()); ui->dispatchZ->setFont(Formatter::PreferredFont()); // A threadgroup's size in any dimension can be up to 1024, but a dispatch can be 65535 // threadgroups for a dimension. Use that upper bound to fix the min size of all fields. ui->groupX->setMaximum(65535); int sizeHint = ui->groupX->minimumSizeHint().width(); ui->groupX->setMinimumWidth(sizeHint); ui->groupY->setMinimumWidth(sizeHint); ui->groupZ->setMinimumWidth(sizeHint); ui->threadX->setMinimumWidth(sizeHint); ui->threadY->setMinimumWidth(sizeHint); ui->threadZ->setMinimumWidth(sizeHint); ui->dispatchX->setMinimumWidth(sizeHint); ui->dispatchY->setMinimumWidth(sizeHint); ui->dispatchZ->setMinimumWidth(sizeHint); } ComputeDebugSelector::~ComputeDebugSelector() { delete ui; } void ComputeDebugSelector::SetThreadBounds(const rdcfixedarray<uint32_t, 3> &group, const rdcfixedarray<uint32_t, 3> &thread) { // Set maximums for CS debugging ui->groupX->setMaximum(group[0] - 1); ui->groupY->setMaximum(group[1] - 1); ui->groupZ->setMaximum(group[2] - 1); ui->threadX->setMaximum(thread[0] - 1); ui->threadY->setMaximum(thread[1] - 1); ui->threadZ->setMaximum(thread[2] - 1); ui->dispatchX->setMaximum(group[0] * thread[0] - 1); ui->dispatchY->setMaximum(group[1] * thread[1] - 1); ui->dispatchZ->setMaximum(group[2] * thread[2] - 1); m_threadGroupSize = thread; } void ComputeDebugSelector::SyncGroupThreadValue() { QSignalBlocker blockers[3] = {QSignalBlocker(ui->dispatchX), QSignalBlocker(ui->dispatchY), QSignalBlocker(ui->dispatchZ)}; ui->dispatchX->setValue(ui->groupX->value() * m_threadGroupSize[0] + ui->threadX->value()); ui->dispatchY->setValue(ui->groupY->value() * m_threadGroupSize[1] + ui->threadY->value()); ui->dispatchZ->setValue(ui->groupZ->value() * m_threadGroupSize[2] + ui->threadZ->value()); } void ComputeDebugSelector::SyncDispatchThreadValue() { uint32_t group[3] = {ui->dispatchX->value() / m_threadGroupSize[0], ui->dispatchY->value() / m_threadGroupSize[1], ui->dispatchZ->value() / m_threadGroupSize[2]}; uint32_t thread[3] = {ui->dispatchX->value() % m_threadGroupSize[0], ui->dispatchY->value() % m_threadGroupSize[1], ui->dispatchZ->value() % m_threadGroupSize[2]}; QSignalBlocker blockers[6] = {QSignalBlocker(ui->groupX), QSignalBlocker(ui->groupY), QSignalBlocker(ui->groupZ), QSignalBlocker(ui->threadX), QSignalBlocker(ui->threadY), QSignalBlocker(ui->threadZ)}; ui->groupX->setValue(group[0]); ui->groupY->setValue(group[1]); ui->groupZ->setValue(group[2]); ui->threadX->setValue(thread[0]); ui->threadY->setValue(thread[1]); ui->threadZ->setValue(thread[2]); } void ComputeDebugSelector::on_beginDebug_clicked() { // The dispatch thread IDs and the group/thread IDs are synced on editing either set, so we can // choose either one to begin debugging. uint32_t group[3] = {(uint32_t)ui->groupX->value(), (uint32_t)ui->groupY->value(), (uint32_t)ui->groupZ->value()}; uint32_t thread[3] = {(uint32_t)ui->threadX->value(), (uint32_t)ui->threadY->value(), (uint32_t)ui->threadZ->value()}; emit beginDebug(group, thread); close(); } void ComputeDebugSelector::on_cancelDebug_clicked() { close(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkContextInteractorStyle.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkContextInteractorStyle.h" #include "vtkContextMouseEvent.h" #include "vtkContextKeyEvent.h" #include "vtkContextScene.h" #include "vtkCallbackCommand.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include <cassert> vtkStandardNewMacro(vtkContextInteractorStyle); //-------------------------------------------------------------------------- vtkContextInteractorStyle::vtkContextInteractorStyle() { this->Scene = NULL; this->ProcessingEvents = 0; this->SceneCallbackCommand->SetClientData(this); this->SceneCallbackCommand->SetCallback( vtkContextInteractorStyle::ProcessSceneEvents); this->InteractorCallbackCommand->SetClientData(this); this->InteractorCallbackCommand->SetCallback( vtkContextInteractorStyle::ProcessInteractorEvents); this->LastSceneRepaintMTime = 0; this->TimerId = 0; this->TimerCallbackInitialized = false; } //-------------------------------------------------------------------------- vtkContextInteractorStyle::~vtkContextInteractorStyle() { // to remove observers. this->SetScene(0); if (this->TimerCallbackInitialized && this->Interactor) { this->Interactor->RemoveObserver(this->InteractorCallbackCommand.Get()); this->TimerCallbackInitialized = false; } } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Scene: " << this->Scene << endl; if (this->Scene) { this->Scene->PrintSelf(os, indent.GetNextIndent()); } } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::SetScene(vtkContextScene* scene) { if (this->Scene == scene) { return; } if (this->Scene) { this->Scene->RemoveObserver(this->SceneCallbackCommand.GetPointer()); } this->Scene = scene; if (this->Scene) { this->Scene->AddObserver(vtkCommand::ModifiedEvent, this->SceneCallbackCommand.GetPointer(), this->Priority); } this->Modified(); } //---------------------------------------------------------------------------- vtkContextScene* vtkContextInteractorStyle::GetScene() { return this->Scene; } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::ProcessSceneEvents(vtkObject*, unsigned long event, void* clientdata, void* vtkNotUsed(calldata)) { vtkContextInteractorStyle* self = reinterpret_cast<vtkContextInteractorStyle *>( clientdata ); switch (event) { case vtkCommand::ModifiedEvent: self->OnSceneModified(); break; default: break; } } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::ProcessInteractorEvents(vtkObject*, unsigned long, void* clientdata, void* vtkNotUsed(calldata)) { vtkContextInteractorStyle* self = reinterpret_cast<vtkContextInteractorStyle *>(clientdata); self->RenderNow(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::RenderNow() { this->TimerId = 0; if (this->Scene && !this->ProcessingEvents && this->Interactor->GetInitialized()) { this->Interactor->GetRenderWindow()->Render(); } } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnSceneModified() { if (!this->Scene || !this->Scene->GetDirty() || this->ProcessingEvents || this->Scene->GetMTime() == this->LastSceneRepaintMTime || !this->Interactor->GetInitialized()) { return; } this->BeginProcessingEvent(); if (!this->TimerCallbackInitialized && this->Interactor) { this->Interactor->AddObserver(vtkCommand::TimerEvent, this->InteractorCallbackCommand.GetPointer(), 0.0); this->TimerCallbackInitialized = true; } this->LastSceneRepaintMTime = this->Scene->GetMTime(); // If there is no timer, create a one shot timer to render an updated scene if (this->TimerId == 0) { this->Interactor->CreateOneShotTimer(40); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::BeginProcessingEvent() { ++this->ProcessingEvents; } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::EndProcessingEvent() { --this->ProcessingEvents; assert(this->ProcessingEvents >= 0); if (this->ProcessingEvents == 0) { this->OnSceneModified(); } } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseMove() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::NO_BUTTON); eatEvent = this->Scene->MouseMoveEvent(event); } if (!eatEvent) { this->Superclass::OnMouseMove(); } this->EndProcessingEvent(); } inline bool vtkContextInteractorStyle::ProcessMousePress( const vtkContextMouseEvent &event) { bool eatEvent(false); if (this->Interactor->GetRepeatCount()) { eatEvent = this->Scene->DoubleClickEvent(event); // // The second ButtonRelease event seems not to be processed automatically, // need manually processing here so that the following MouseMove event will // not think the mouse button is still pressed down, and we don't really // care about the return result from the second ButtonRelease. // if (eatEvent) { this->Scene->ButtonReleaseEvent(event); } } else { eatEvent = this->Scene->ButtonPressEvent(event); } return eatEvent; } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnLeftButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::LEFT_BUTTON); eatEvent = this->ProcessMousePress(event); } if (!eatEvent) { this->Superclass::OnLeftButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnLeftButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::LEFT_BUTTON); eatEvent = this->Scene->ButtonReleaseEvent(event); } if (!eatEvent) { this->Superclass::OnLeftButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMiddleButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON); eatEvent = this->ProcessMousePress(event); } if (!eatEvent) { this->Superclass::OnMiddleButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMiddleButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON); eatEvent = this->Scene->ButtonReleaseEvent(event); } if (!eatEvent) { this->Superclass::OnMiddleButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnRightButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::RIGHT_BUTTON); eatEvent = this->ProcessMousePress(event); } if (!eatEvent) { this->Superclass::OnRightButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnRightButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::RIGHT_BUTTON); eatEvent = this->Scene->ButtonReleaseEvent(event); } if (!eatEvent) { this->Superclass::OnRightButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseWheelForward() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON); eatEvent = this->Scene->MouseWheelEvent( static_cast<int>(this->MouseWheelMotionFactor), event); } if (!eatEvent) { this->Superclass::OnMouseWheelForward(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseWheelBackward() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON); eatEvent = this->Scene->MouseWheelEvent( -static_cast<int>(this->MouseWheelMotionFactor), event); } if (!eatEvent) { this->Superclass::OnMouseWheelBackward(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnSelection(unsigned int rect[5]) { this->BeginProcessingEvent(); if (this->Scene) { this->Scene->ProcessSelectionEvent(rect); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnChar() { this->Superclass::OnChar(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnKeyPress() { this->BeginProcessingEvent(); vtkContextKeyEvent event; vtkVector2i position(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[0]); event.SetInteractor(this->Interactor); event.SetPosition(position); bool keepEvent = false; if (this->Scene) { keepEvent = this->Scene->KeyPressEvent(event); } if (!keepEvent) { this->Superclass::OnKeyPress(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnKeyRelease() { this->BeginProcessingEvent(); vtkContextKeyEvent event; vtkVector2i position(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[0]); event.SetInteractor(this->Interactor); event.SetPosition(position); bool keepEvent = false; if (this->Scene) { keepEvent = this->Scene->KeyReleaseEvent(event); } if (!keepEvent) { this->Superclass::OnKeyRelease(); } this->EndProcessingEvent(); } //------------------------------------------------------------------------- inline void vtkContextInteractorStyle::ConstructMouseEvent( vtkContextMouseEvent &event, int button) { event.SetInteractor(this->Interactor); event.SetPos(vtkVector2f(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[1])); event.SetButton(button); } <commit_msg>BUG: Fixed error in passing position of key press<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkContextInteractorStyle.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkContextInteractorStyle.h" #include "vtkContextMouseEvent.h" #include "vtkContextKeyEvent.h" #include "vtkContextScene.h" #include "vtkCallbackCommand.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include <cassert> vtkStandardNewMacro(vtkContextInteractorStyle); //-------------------------------------------------------------------------- vtkContextInteractorStyle::vtkContextInteractorStyle() { this->Scene = NULL; this->ProcessingEvents = 0; this->SceneCallbackCommand->SetClientData(this); this->SceneCallbackCommand->SetCallback( vtkContextInteractorStyle::ProcessSceneEvents); this->InteractorCallbackCommand->SetClientData(this); this->InteractorCallbackCommand->SetCallback( vtkContextInteractorStyle::ProcessInteractorEvents); this->LastSceneRepaintMTime = 0; this->TimerId = 0; this->TimerCallbackInitialized = false; } //-------------------------------------------------------------------------- vtkContextInteractorStyle::~vtkContextInteractorStyle() { // to remove observers. this->SetScene(0); if (this->TimerCallbackInitialized && this->Interactor) { this->Interactor->RemoveObserver(this->InteractorCallbackCommand.Get()); this->TimerCallbackInitialized = false; } } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Scene: " << this->Scene << endl; if (this->Scene) { this->Scene->PrintSelf(os, indent.GetNextIndent()); } } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::SetScene(vtkContextScene* scene) { if (this->Scene == scene) { return; } if (this->Scene) { this->Scene->RemoveObserver(this->SceneCallbackCommand.GetPointer()); } this->Scene = scene; if (this->Scene) { this->Scene->AddObserver(vtkCommand::ModifiedEvent, this->SceneCallbackCommand.GetPointer(), this->Priority); } this->Modified(); } //---------------------------------------------------------------------------- vtkContextScene* vtkContextInteractorStyle::GetScene() { return this->Scene; } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::ProcessSceneEvents(vtkObject*, unsigned long event, void* clientdata, void* vtkNotUsed(calldata)) { vtkContextInteractorStyle* self = reinterpret_cast<vtkContextInteractorStyle *>( clientdata ); switch (event) { case vtkCommand::ModifiedEvent: self->OnSceneModified(); break; default: break; } } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::ProcessInteractorEvents(vtkObject*, unsigned long, void* clientdata, void* vtkNotUsed(calldata)) { vtkContextInteractorStyle* self = reinterpret_cast<vtkContextInteractorStyle *>(clientdata); self->RenderNow(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::RenderNow() { this->TimerId = 0; if (this->Scene && !this->ProcessingEvents && this->Interactor->GetInitialized()) { this->Interactor->GetRenderWindow()->Render(); } } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnSceneModified() { if (!this->Scene || !this->Scene->GetDirty() || this->ProcessingEvents || this->Scene->GetMTime() == this->LastSceneRepaintMTime || !this->Interactor->GetInitialized()) { return; } this->BeginProcessingEvent(); if (!this->TimerCallbackInitialized && this->Interactor) { this->Interactor->AddObserver(vtkCommand::TimerEvent, this->InteractorCallbackCommand.GetPointer(), 0.0); this->TimerCallbackInitialized = true; } this->LastSceneRepaintMTime = this->Scene->GetMTime(); // If there is no timer, create a one shot timer to render an updated scene if (this->TimerId == 0) { this->Interactor->CreateOneShotTimer(40); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::BeginProcessingEvent() { ++this->ProcessingEvents; } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::EndProcessingEvent() { --this->ProcessingEvents; assert(this->ProcessingEvents >= 0); if (this->ProcessingEvents == 0) { this->OnSceneModified(); } } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseMove() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::NO_BUTTON); eatEvent = this->Scene->MouseMoveEvent(event); } if (!eatEvent) { this->Superclass::OnMouseMove(); } this->EndProcessingEvent(); } inline bool vtkContextInteractorStyle::ProcessMousePress( const vtkContextMouseEvent &event) { bool eatEvent(false); if (this->Interactor->GetRepeatCount()) { eatEvent = this->Scene->DoubleClickEvent(event); // // The second ButtonRelease event seems not to be processed automatically, // need manually processing here so that the following MouseMove event will // not think the mouse button is still pressed down, and we don't really // care about the return result from the second ButtonRelease. // if (eatEvent) { this->Scene->ButtonReleaseEvent(event); } } else { eatEvent = this->Scene->ButtonPressEvent(event); } return eatEvent; } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnLeftButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::LEFT_BUTTON); eatEvent = this->ProcessMousePress(event); } if (!eatEvent) { this->Superclass::OnLeftButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnLeftButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::LEFT_BUTTON); eatEvent = this->Scene->ButtonReleaseEvent(event); } if (!eatEvent) { this->Superclass::OnLeftButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMiddleButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON); eatEvent = this->ProcessMousePress(event); } if (!eatEvent) { this->Superclass::OnMiddleButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMiddleButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON); eatEvent = this->Scene->ButtonReleaseEvent(event); } if (!eatEvent) { this->Superclass::OnMiddleButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnRightButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::RIGHT_BUTTON); eatEvent = this->ProcessMousePress(event); } if (!eatEvent) { this->Superclass::OnRightButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnRightButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::RIGHT_BUTTON); eatEvent = this->Scene->ButtonReleaseEvent(event); } if (!eatEvent) { this->Superclass::OnRightButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseWheelForward() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON); eatEvent = this->Scene->MouseWheelEvent( static_cast<int>(this->MouseWheelMotionFactor), event); } if (!eatEvent) { this->Superclass::OnMouseWheelForward(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseWheelBackward() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { vtkContextMouseEvent event; this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON); eatEvent = this->Scene->MouseWheelEvent( -static_cast<int>(this->MouseWheelMotionFactor), event); } if (!eatEvent) { this->Superclass::OnMouseWheelBackward(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnSelection(unsigned int rect[5]) { this->BeginProcessingEvent(); if (this->Scene) { this->Scene->ProcessSelectionEvent(rect); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnChar() { this->Superclass::OnChar(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnKeyPress() { this->BeginProcessingEvent(); vtkContextKeyEvent event; vtkVector2i position(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[1]); event.SetInteractor(this->Interactor); event.SetPosition(position); bool keepEvent = false; if (this->Scene) { keepEvent = this->Scene->KeyPressEvent(event); } if (!keepEvent) { this->Superclass::OnKeyPress(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnKeyRelease() { this->BeginProcessingEvent(); vtkContextKeyEvent event; vtkVector2i position(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[1]); event.SetInteractor(this->Interactor); event.SetPosition(position); bool keepEvent = false; if (this->Scene) { keepEvent = this->Scene->KeyReleaseEvent(event); } if (!keepEvent) { this->Superclass::OnKeyRelease(); } this->EndProcessingEvent(); } //------------------------------------------------------------------------- inline void vtkContextInteractorStyle::ConstructMouseEvent( vtkContextMouseEvent &event, int button) { event.SetInteractor(this->Interactor); event.SetPos(vtkVector2f(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[1])); event.SetButton(button); } <|endoftext|>
<commit_before>#include "Direct3DHandler.h" Direct3DHandler::Direct3DHandler() { this->m_activeWindow = nullptr; this->m_backBufferRTV = nullptr; this->m_depthStencilBuffer = nullptr; this->m_gDevice = nullptr; this->m_gDeviceContext = nullptr; this->m_rasterizerState = nullptr; this->m_rasterizerStateWireFrame = nullptr; this->m_swapChain = nullptr; this->m_viewport = nullptr; this->m_SwapCount = 1; } Direct3DHandler::~Direct3DHandler() { } int Direct3DHandler::Initialize(HWND* windowHandle, const DirectX::XMINT2& resolution, bool editorMode) { HRESULT hResult; // Create the Device \\ D3D_FEATURE_LEVEL featureLevel; this->m_SwapCount = 1; if (editorMode) { featureLevel = D3D_FEATURE_LEVEL_11_0; this->m_SwapCount = 0; } else { featureLevel = D3D_FEATURE_LEVEL_11_1; this->m_SwapCount = 1; } #ifdef _DEBUG hResult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, &featureLevel, 1, D3D11_SDK_VERSION, &this->m_gDevice, NULL, &this->m_gDeviceContext); if (FAILED(hResult)) { return 1; } #else hResult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_SINGLETHREADED, &featureLevel, 1, D3D11_SDK_VERSION, &this->m_gDevice, NULL, &this->m_gDeviceContext); if (FAILED(hResult)) { return 1; } #endif // Create the rasterizer state \\ D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.AntialiasedLineEnable = false; rasterizerDesc.CullMode = D3D11_CULL_BACK; //Enable backface culling rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = true; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.MultisampleEnable = false; rasterizerDesc.ScissorEnable = false; rasterizerDesc.SlopeScaledDepthBias = 0.0f; hResult = this->m_gDevice->CreateRasterizerState(&rasterizerDesc, &this->m_rasterizerState); if (FAILED(hResult)) { return 1; } this->m_gDeviceContext->RSSetState(this->m_rasterizerState); //Set the rasterstate // Create the swapchain \\ DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 }; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.Height = resolution.y; swapChainDesc.Width = resolution.x; swapChainDesc.Stereo = false; swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; swapChainDesc.Scaling = DXGI_SCALING_NONE; swapChainDesc.SampleDesc.Count = 1; //No MSAA swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT; if (editorMode) { swapChainDesc.BufferCount = 1; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Flags = 0; } else { swapChainDesc.BufferCount = 2; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH /*DXGI_PRESENT_RESTART*/; } DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullScreenDesc; fullScreenDesc.RefreshRate.Numerator = 60; fullScreenDesc.RefreshRate.Denominator = 1; fullScreenDesc.Windowed = true; fullScreenDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; fullScreenDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; IDXGIDevice1* dxgiDevice = nullptr; hResult = this->m_gDevice->QueryInterface(__uuidof(IDXGIDevice1), (void**)&dxgiDevice); if (FAILED(hResult)) { return 1; } IDXGIAdapter2* dxgiAdapter = nullptr; hResult = dxgiDevice->GetParent(__uuidof(IDXGIAdapter2), (void**)&dxgiAdapter); if (FAILED(hResult)) { return 1; } IDXGIFactory2* dxgiFactory2 = nullptr; hResult = dxgiAdapter->GetParent(__uuidof(IDXGIFactory2), (void**)&dxgiFactory2); if (FAILED(hResult)) { return 1; } hResult = dxgiFactory2->CreateSwapChainForHwnd(this->m_gDevice, HWND(*windowHandle), &swapChainDesc, &fullScreenDesc, nullptr, &m_swapChain); if (FAILED(hResult)) { return 1; } // Create the backbuffer render target view \\ ID3D11Texture2D* backBufferPrt = nullptr; this->m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)(&backBufferPrt)); hResult = this->m_gDevice->CreateRenderTargetView(backBufferPrt, NULL, &this->m_backBufferRTV); if (FAILED(hResult)) { return 1; } hResult = this->m_gDevice->CreateShaderResourceView(backBufferPrt, nullptr, &this->m_backBufferSRV); if (FAILED(hResult)) { return 1; } backBufferPrt->Release(); this->m_viewport = new D3D11_VIEWPORT; this->m_viewport->TopLeftX = 0.0f; this->m_viewport->TopLeftY = 0.0f; this->m_viewport->Width = float(resolution.x); this->m_viewport->Height = float(resolution.y); this->m_viewport->MinDepth = 0.0f; this->m_viewport->MaxDepth = 1.0f; this->m_gDeviceContext->RSSetViewports(1, this->m_viewport); Resources::ResourceHandler::GetInstance()->SetDeviceAndContext(this->m_gDevice, this->m_gDeviceContext); D3D11_BLEND_DESC BlendState; ZeroMemory(&BlendState, sizeof(D3D11_BLEND_DESC)); BlendState.RenderTarget[0].BlendEnable = FALSE; BlendState.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; this->m_gDevice->CreateBlendState(&BlendState, &g_pBlendStateNoBlend); return 0; } int Direct3DHandler::InitializeGridRasterizer() { HRESULT hResult; D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.AntialiasedLineEnable = false; rasterizerDesc.CullMode = D3D11_CULL_NONE; //Enable backface culling rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = true; rasterizerDesc.FillMode = D3D11_FILL_WIREFRAME; rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.MultisampleEnable = false; rasterizerDesc.ScissorEnable = false; rasterizerDesc.SlopeScaledDepthBias = 0.0f; hResult = this->m_gDevice->CreateRasterizerState(&rasterizerDesc, &this->m_rasterizerStateWireFrame); if (FAILED(hResult)) { return 1; } return 0; } int Direct3DHandler::PresentScene() { //RECT dirtyRectPrev, dirtyRectCurrent, dirtyRectCopy; //IntersectRect(&dirtyRectCopy, &dirtyRectPrev, &dirtyRectCurrent); this->m_swapChain->Present(this->m_SwapCount, 0); return 0; } void Direct3DHandler::Shutdown() { if (this->m_depthStencilBuffer) { this->m_depthStencilBuffer->Release(); this->m_depthStencilBuffer = nullptr; } if (this->m_rasterizerState) { this->m_rasterizerState->Release(); this->m_rasterizerState = nullptr; } if (this->m_rasterizerState) { this->m_rasterizerState->Release(); this->m_rasterizerState = nullptr; } if (this->m_backBufferRTV) { this->m_backBufferRTV->Release(); this->m_backBufferRTV = nullptr; } if (this->m_backBufferSRV) { this->m_backBufferSRV->Release(); this->m_backBufferSRV = nullptr; } if (this->m_swapChain) { this->m_swapChain->Release(); this->m_swapChain = nullptr; } if (this->m_gDeviceContext) { this->m_gDeviceContext->Release(); this->m_gDeviceContext = nullptr; } if (this->m_gDevice) { this->m_gDevice->Release(); this->m_gDevice = nullptr; } if (this->m_viewport) { delete this->m_viewport; this->m_viewport = nullptr; } if (this->m_rasterizerStateWireFrame) { m_rasterizerStateWireFrame->Release(); this->m_rasterizerStateWireFrame = nullptr; } } ID3D11Device * Direct3DHandler::GetDevice() { return this->m_gDevice; } ID3D11DeviceContext * Direct3DHandler::GetDeviceContext() { return this->m_gDeviceContext; } ID3D11RenderTargetView * Direct3DHandler::GetBackbufferRTV() { return this->m_backBufferRTV; } ID3D11ShaderResourceView * Direct3DHandler::GetBackbufferSRV() { return this->m_backBufferSRV; } D3D11_VIEWPORT * Direct3DHandler::GetViewPort() { return m_viewport; } int Direct3DHandler::SetRasterizerState(D3D11_FILL_MODE mode) { switch (mode) { case D3D11_FILL_WIREFRAME: { this->m_gDeviceContext->RSSetState(this->m_rasterizerStateWireFrame); break; } case D3D11_FILL_SOLID: { this->m_gDeviceContext->RSSetState(this->m_rasterizerState); break; } default: break; } return 0; } int Direct3DHandler::ClearBlendState() { this->m_gDeviceContext->OMSetBlendState(this->g_pBlendStateNoBlend, this->blendFactor, this->sampleMask); return 0; } <commit_msg>FIX merge override that removed exact ideal screen update<commit_after>#include "Direct3DHandler.h" Direct3DHandler::Direct3DHandler() { this->m_activeWindow = nullptr; this->m_backBufferRTV = nullptr; this->m_depthStencilBuffer = nullptr; this->m_gDevice = nullptr; this->m_gDeviceContext = nullptr; this->m_rasterizerState = nullptr; this->m_rasterizerStateWireFrame = nullptr; this->m_swapChain = nullptr; this->m_viewport = nullptr; this->m_SwapCount = 1; } Direct3DHandler::~Direct3DHandler() { } int Direct3DHandler::Initialize(HWND* windowHandle, const DirectX::XMINT2& resolution, bool editorMode) { HRESULT hResult; // Create the Device \\ D3D_FEATURE_LEVEL featureLevel; this->m_SwapCount = 1; if (editorMode) { featureLevel = D3D_FEATURE_LEVEL_11_0; this->m_SwapCount = 0; } else { featureLevel = D3D_FEATURE_LEVEL_11_1; this->m_SwapCount = 1; } #ifdef _DEBUG hResult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, &featureLevel, 1, D3D11_SDK_VERSION, &this->m_gDevice, NULL, &this->m_gDeviceContext); if (FAILED(hResult)) { return 1; } #else hResult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_SINGLETHREADED, &featureLevel, 1, D3D11_SDK_VERSION, &this->m_gDevice, NULL, &this->m_gDeviceContext); if (FAILED(hResult)) { return 1; } #endif // Create the rasterizer state \\ D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.AntialiasedLineEnable = false; rasterizerDesc.CullMode = D3D11_CULL_BACK; //Enable backface culling rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = true; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.MultisampleEnable = false; rasterizerDesc.ScissorEnable = false; rasterizerDesc.SlopeScaledDepthBias = 0.0f; hResult = this->m_gDevice->CreateRasterizerState(&rasterizerDesc, &this->m_rasterizerState); if (FAILED(hResult)) { return 1; } this->m_gDeviceContext->RSSetState(this->m_rasterizerState); //Set the rasterstate // Create the swapchain \\ DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 }; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.Height = resolution.y; swapChainDesc.Width = resolution.x; swapChainDesc.Stereo = false; swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; swapChainDesc.Scaling = DXGI_SCALING_NONE; swapChainDesc.SampleDesc.Count = 1; //No MSAA swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT; if (editorMode) { swapChainDesc.BufferCount = 1; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Flags = 0; } else { swapChainDesc.BufferCount = 2; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH /*DXGI_PRESENT_RESTART*/; } DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullScreenDesc; fullScreenDesc.RefreshRate.Numerator = 59994; fullScreenDesc.RefreshRate.Denominator = 1002; fullScreenDesc.Windowed = true; fullScreenDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; fullScreenDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; IDXGIDevice1* dxgiDevice = nullptr; hResult = this->m_gDevice->QueryInterface(__uuidof(IDXGIDevice1), (void**)&dxgiDevice); if (FAILED(hResult)) { return 1; } IDXGIAdapter2* dxgiAdapter = nullptr; hResult = dxgiDevice->GetParent(__uuidof(IDXGIAdapter2), (void**)&dxgiAdapter); if (FAILED(hResult)) { return 1; } IDXGIFactory2* dxgiFactory2 = nullptr; hResult = dxgiAdapter->GetParent(__uuidof(IDXGIFactory2), (void**)&dxgiFactory2); if (FAILED(hResult)) { return 1; } hResult = dxgiFactory2->CreateSwapChainForHwnd(this->m_gDevice, HWND(*windowHandle), &swapChainDesc, &fullScreenDesc, nullptr, &m_swapChain); if (FAILED(hResult)) { return 1; } // Create the backbuffer render target view \\ ID3D11Texture2D* backBufferPrt = nullptr; this->m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)(&backBufferPrt)); hResult = this->m_gDevice->CreateRenderTargetView(backBufferPrt, NULL, &this->m_backBufferRTV); if (FAILED(hResult)) { return 1; } hResult = this->m_gDevice->CreateShaderResourceView(backBufferPrt, nullptr, &this->m_backBufferSRV); if (FAILED(hResult)) { return 1; } backBufferPrt->Release(); this->m_viewport = new D3D11_VIEWPORT; this->m_viewport->TopLeftX = 0.0f; this->m_viewport->TopLeftY = 0.0f; this->m_viewport->Width = float(resolution.x); this->m_viewport->Height = float(resolution.y); this->m_viewport->MinDepth = 0.0f; this->m_viewport->MaxDepth = 1.0f; this->m_gDeviceContext->RSSetViewports(1, this->m_viewport); Resources::ResourceHandler::GetInstance()->SetDeviceAndContext(this->m_gDevice, this->m_gDeviceContext); D3D11_BLEND_DESC BlendState; ZeroMemory(&BlendState, sizeof(D3D11_BLEND_DESC)); BlendState.RenderTarget[0].BlendEnable = FALSE; BlendState.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; this->m_gDevice->CreateBlendState(&BlendState, &g_pBlendStateNoBlend); return 0; } int Direct3DHandler::InitializeGridRasterizer() { HRESULT hResult; D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.AntialiasedLineEnable = false; rasterizerDesc.CullMode = D3D11_CULL_NONE; //Enable backface culling rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = true; rasterizerDesc.FillMode = D3D11_FILL_WIREFRAME; rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.MultisampleEnable = false; rasterizerDesc.ScissorEnable = false; rasterizerDesc.SlopeScaledDepthBias = 0.0f; hResult = this->m_gDevice->CreateRasterizerState(&rasterizerDesc, &this->m_rasterizerStateWireFrame); if (FAILED(hResult)) { return 1; } return 0; } int Direct3DHandler::PresentScene() { //RECT dirtyRectPrev, dirtyRectCurrent, dirtyRectCopy; //IntersectRect(&dirtyRectCopy, &dirtyRectPrev, &dirtyRectCurrent); this->m_swapChain->Present(this->m_SwapCount, 0); return 0; } void Direct3DHandler::Shutdown() { if (this->m_depthStencilBuffer) { this->m_depthStencilBuffer->Release(); this->m_depthStencilBuffer = nullptr; } if (this->m_rasterizerState) { this->m_rasterizerState->Release(); this->m_rasterizerState = nullptr; } if (this->m_rasterizerState) { this->m_rasterizerState->Release(); this->m_rasterizerState = nullptr; } if (this->m_backBufferRTV) { this->m_backBufferRTV->Release(); this->m_backBufferRTV = nullptr; } if (this->m_backBufferSRV) { this->m_backBufferSRV->Release(); this->m_backBufferSRV = nullptr; } if (this->m_swapChain) { this->m_swapChain->Release(); this->m_swapChain = nullptr; } if (this->m_gDeviceContext) { this->m_gDeviceContext->Release(); this->m_gDeviceContext = nullptr; } if (this->m_gDevice) { this->m_gDevice->Release(); this->m_gDevice = nullptr; } if (this->m_viewport) { delete this->m_viewport; this->m_viewport = nullptr; } if (this->m_rasterizerStateWireFrame) { m_rasterizerStateWireFrame->Release(); this->m_rasterizerStateWireFrame = nullptr; } } ID3D11Device * Direct3DHandler::GetDevice() { return this->m_gDevice; } ID3D11DeviceContext * Direct3DHandler::GetDeviceContext() { return this->m_gDeviceContext; } ID3D11RenderTargetView * Direct3DHandler::GetBackbufferRTV() { return this->m_backBufferRTV; } ID3D11ShaderResourceView * Direct3DHandler::GetBackbufferSRV() { return this->m_backBufferSRV; } D3D11_VIEWPORT * Direct3DHandler::GetViewPort() { return m_viewport; } int Direct3DHandler::SetRasterizerState(D3D11_FILL_MODE mode) { switch (mode) { case D3D11_FILL_WIREFRAME: { this->m_gDeviceContext->RSSetState(this->m_rasterizerStateWireFrame); break; } case D3D11_FILL_SOLID: { this->m_gDeviceContext->RSSetState(this->m_rasterizerState); break; } default: break; } return 0; } int Direct3DHandler::ClearBlendState() { this->m_gDeviceContext->OMSetBlendState(this->g_pBlendStateNoBlend, this->blendFactor, this->sampleMask); return 0; } <|endoftext|>
<commit_before>// ffmpeg player output (portaudio) // part of MusicPlayer, https://github.com/albertz/music-player // Copyright (c) 2012, Albert Zeyer, www.az2000.de // All rights reserved. // This code is under the 2-clause BSD license, see License.txt in the root directory of this project. #include "ffmpeg.h" #include <portaudio.h> // For setting the thread priority to realtime on MacOSX. #ifdef __APPLE__ #include <mach/mach_init.h> #include <mach/thread_policy.h> #include <mach/thread_act.h> // the doc says mach/sched.h but that seems outdated... #include <pthread.h> #include <mach/mach_error.h> #include <mach/mach_time.h> #endif static void setRealtime(); #define AUDIO_BUFFER_SIZE (2048 * 10) // soundcard buffer int initPlayerOutput() { PaError ret = Pa_Initialize(); if(ret != paNoError) Py_FatalError("PortAudio init failed"); return 0; } struct PlayerObject::OutStream { PlayerObject* const player; PaStream* stream; OutStream(PlayerObject* p) : player(p), stream(NULL) {} ~OutStream() { close(); } void close() { // we expect that we have the player lock here. // we must release the lock so that any thread-join can be done. PaStream* stream = NULL; std::swap(stream, this->stream); PyScopedUnlock unlock(player->lock); Pa_CloseStream(stream); } void stop() { // we expect that we have the lock here. // we must release the lock so that any thread-join can be done. PaStream* stream = this->stream; // buffer for unlock-scope PyScopedUnlock unlock(player->lock); Pa_StopStream(stream); } }; static int paStreamCallback( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { PlayerObject* player = (PlayerObject*) userData; // We must not hold the PyGIL here! PyScopedLock lock(player->lock); if(player->needRealtimeReset) { player->needRealtimeReset = 0; setRealtime(); } player->readOutStream((int16_t*) output, frameCount * player->outNumChannels, NULL); return paContinue; } int PlayerObject::setPlaying(bool playing) { PlayerObject* player = this; bool oldplayingstate = false; PyScopedGIL gil; { PyScopedGIUnlock gunlock; player->workerThread.start(); // if not running yet, start if(!player->outStream.get()) player->outStream.reset(new OutStream(this)); assert(player->outStream.get() != NULL); if(soundcardOutputEnabled) { if(playing && !player->outStream->stream) { PaError ret; ret = Pa_OpenDefaultStream( &player->outStream->stream, 0, player->outNumChannels, // numOutputChannels paInt16, // sampleFormat player->outSamplerate, // sampleRate AUDIO_BUFFER_SIZE / 2, // framesPerBuffer, &paStreamCallback, player //void *userData ); if(ret != paNoError) { PyErr_SetString(PyExc_RuntimeError, "Pa_OpenDefaultStream failed"); if(player->outStream->stream) player->outStream->close(); playing = 0; } } if(playing) { player->needRealtimeReset = 1; Pa_StartStream(player->outStream->stream); } else player->outStream->stop(); } oldplayingstate = player->playing; player->playing = playing; } if(!PyErr_Occurred() && player->dict) { Py_INCREF(player->dict); PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange"); if(onPlayingStateChange && onPlayingStateChange != Py_None) { Py_INCREF(onPlayingStateChange); PyObject* kwargs = PyDict_New(); assert(kwargs); PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate)); PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing)); PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs); Py_XDECREF(retObj); // errors are not fatal from the callback, so handle it now and go on if(PyErr_Occurred()) PyErr_Print(); Py_DECREF(kwargs); Py_DECREF(onPlayingStateChange); } Py_DECREF(player->dict); } return PyErr_Occurred() ? -1 : 0; } #ifdef __APPLE__ // https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html // Also, from Google Native Client, osx/nacl_thread_nice.c has some related code. // Or, from Google Chrome, platform_thread_mac.mm. void setRealtime() { kern_return_t ret; thread_port_t threadport = pthread_mach_thread_np(pthread_self()); thread_extended_policy_data_t policy; policy.timeshare = 0; ret = thread_policy_set(threadport, THREAD_EXTENDED_POLICY, (thread_policy_t)&policy, THREAD_EXTENDED_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } thread_precedence_policy_data_t precedence; precedence.importance = 63; ret = thread_policy_set(threadport, THREAD_PRECEDENCE_POLICY, (thread_policy_t)&precedence, THREAD_PRECEDENCE_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } mach_timebase_info_data_t tb_info; mach_timebase_info(&tb_info); double timeFact = ((double)tb_info.denom / (double)tb_info.numer) * 1000000; thread_time_constraint_policy_data_t ttcpolicy; ttcpolicy.period = 2.9 * timeFact; // about 128 frames @44.1KHz ttcpolicy.computation = 0.75 * 2.9 * timeFact; ttcpolicy.constraint = 0.85 * 2.9 * timeFact; ttcpolicy.preemptible = 1; ret = thread_policy_set(threadport, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } } #else void setRealtime() {} // not implemented yet #endif <commit_msg>ffmpeg: portaudio: some mac options<commit_after>// ffmpeg player output (portaudio) // part of MusicPlayer, https://github.com/albertz/music-player // Copyright (c) 2012, Albert Zeyer, www.az2000.de // All rights reserved. // This code is under the 2-clause BSD license, see License.txt in the root directory of this project. #include "ffmpeg.h" #include <portaudio.h> #ifdef __APPLE__ // PortAudio specific Mac stuff #include "pa_mac_core.h" #endif // For setting the thread priority to realtime on MacOSX. #ifdef __APPLE__ #include <mach/mach_init.h> #include <mach/thread_policy.h> #include <mach/thread_act.h> // the doc says mach/sched.h but that seems outdated... #include <pthread.h> #include <mach/mach_error.h> #include <mach/mach_time.h> #endif static void setRealtime(); #define AUDIO_BUFFER_SIZE (2048 * 10) // soundcard buffer int initPlayerOutput() { PaError ret = Pa_Initialize(); if(ret != paNoError) Py_FatalError("PortAudio init failed"); return 0; } struct PlayerObject::OutStream { PlayerObject* const player; PaStream* stream; OutStream(PlayerObject* p) : player(p), stream(NULL) {} ~OutStream() { close(); } void close() { // we expect that we have the player lock here. // we must release the lock so that any thread-join can be done. PaStream* stream = NULL; std::swap(stream, this->stream); PyScopedUnlock unlock(player->lock); Pa_CloseStream(stream); } void stop() { // we expect that we have the lock here. // we must release the lock so that any thread-join can be done. PaStream* stream = this->stream; // buffer for unlock-scope PyScopedUnlock unlock(player->lock); Pa_StopStream(stream); } }; static int paStreamCallback( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { PlayerObject* player = (PlayerObject*) userData; // We must not hold the PyGIL here! PyScopedLock lock(player->lock); if(player->needRealtimeReset) { player->needRealtimeReset = 0; setRealtime(); } player->readOutStream((int16_t*) output, frameCount * player->outNumChannels, NULL); return paContinue; } int PlayerObject::setPlaying(bool playing) { PlayerObject* player = this; bool oldplayingstate = false; PyScopedGIL gil; { PyScopedGIUnlock gunlock; player->workerThread.start(); // if not running yet, start if(!player->outStream.get()) player->outStream.reset(new OutStream(this)); assert(player->outStream.get() != NULL); if(soundcardOutputEnabled) { if(playing && !player->outStream->stream) { PaError ret; PaStreamParameters outputParameters; #ifdef __APPLE__ PaMacCoreStreamInfo macInfo; PaMacCore_SetupStreamInfo( &macInfo, paMacCorePlayNice | paMacCorePro ); #endif outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ //if (outputParameters.device == paNoDevice) { // is this handled anyway by Pa_OpenStream? //} outputParameters.channelCount = player->outNumChannels; outputParameters.sampleFormat = paInt16; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; #ifdef __APPLE__ outputParameters.hostApiSpecificStreamInfo = &macInfo; #else outputParameters.hostApiSpecificStreamInfo = NULL; #endif ret = Pa_OpenStream( &player->outStream->stream, NULL, // no input &outputParameters, player->outSamplerate, // sampleRate AUDIO_BUFFER_SIZE / 2, // framesPerBuffer, paClipOff | paDitherOff, &paStreamCallback, player //void *userData ); if(ret != paNoError) { PyErr_Format(PyExc_RuntimeError, "Pa_OpenDefaultStream failed: (err %i) %s", ret, Pa_GetErrorText(ret)); if(player->outStream->stream) player->outStream->close(); playing = 0; } } if(playing) { player->needRealtimeReset = 1; Pa_StartStream(player->outStream->stream); } else player->outStream->stop(); } oldplayingstate = player->playing; player->playing = playing; } if(!PyErr_Occurred() && player->dict) { Py_INCREF(player->dict); PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange"); if(onPlayingStateChange && onPlayingStateChange != Py_None) { Py_INCREF(onPlayingStateChange); PyObject* kwargs = PyDict_New(); assert(kwargs); PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate)); PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing)); PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs); Py_XDECREF(retObj); // errors are not fatal from the callback, so handle it now and go on if(PyErr_Occurred()) PyErr_Print(); Py_DECREF(kwargs); Py_DECREF(onPlayingStateChange); } Py_DECREF(player->dict); } return PyErr_Occurred() ? -1 : 0; } #ifdef __APPLE__ // https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html // Also, from Google Native Client, osx/nacl_thread_nice.c has some related code. // Or, from Google Chrome, platform_thread_mac.mm. void setRealtime() { kern_return_t ret; thread_port_t threadport = pthread_mach_thread_np(pthread_self()); thread_extended_policy_data_t policy; policy.timeshare = 0; ret = thread_policy_set(threadport, THREAD_EXTENDED_POLICY, (thread_policy_t)&policy, THREAD_EXTENDED_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } thread_precedence_policy_data_t precedence; precedence.importance = 63; ret = thread_policy_set(threadport, THREAD_PRECEDENCE_POLICY, (thread_policy_t)&precedence, THREAD_PRECEDENCE_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } mach_timebase_info_data_t tb_info; mach_timebase_info(&tb_info); double timeFact = ((double)tb_info.denom / (double)tb_info.numer) * 1000000; thread_time_constraint_policy_data_t ttcpolicy; ttcpolicy.period = 2.9 * timeFact; // about 128 frames @44.1KHz ttcpolicy.computation = 0.75 * 2.9 * timeFact; ttcpolicy.constraint = 0.85 * 2.9 * timeFact; ttcpolicy.preemptible = 1; ret = thread_policy_set(threadport, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT); if(ret != KERN_SUCCESS) { fprintf(stderr, "setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\n", ret, mach_error_string(ret)); return; } } #else void setRealtime() {} // not implemented yet #endif <|endoftext|>
<commit_before>#include "ircchannel.hpp" #include "hub.hpp" #include "messages.hpp" #include <stdexcept> #include <utility> #include <typeinfo> #include <regex> #include <memory> namespace ircChannel { IrcChannel::IrcChannel(Hub::Hub* hub, const std::string& config) : channeling::Channel(hub, config), _server(_config["server"]), _port(_config["port"]), _channel(_config["channel"]), _ping_time(std::chrono::high_resolution_clock::now()) {} std::future<void> IrcChannel::activate() { return std::async(std::launch::async, [this]() { if (_active) return; _fd = connect(_server, _port); startPolling(); std::async(std::launch::async, [this]() { std::this_thread::sleep_for(std::chrono::milliseconds (2000)); registerConnection(); }); _active = true; }); } IrcChannel::~IrcChannel() { disconnect(); stopPolling(); } void IrcChannel::incoming(const messaging::message_ptr&& msg) { char message[irc_message_max]; checkTimeout(); if (msg->type() == messaging::MessageType::Text) { const auto textmsg = messaging::TextMessage::fromMessage(msg); snprintf(message, irc_message_max, "PRIVMSG #%s :[%s]: %s\r\n", _channel.c_str(), textmsg->user()->name().c_str(), textmsg->data().c_str()); std::cerr << "[DEBUG] #irc " << _name << " " << textmsg->data() << " inside " << _name << std::endl; send(message); } } const messaging::message_ptr IrcChannel::parse(const char* line) const { // :[email protected] PRIVMSG #chatsync :ololo const std::string toParse(line); std::cerr << "[DEBUG] Parsing irc line:" << toParse << std::endl; std::regex msgRe(":(\\S+)!(\\S+)\\s+PRIVMSG\\s+#(\\S+)\\s+:(.*)\r\n$"); std::regex pingRe("PING\\s+:(.*)\r\n$"); std::regex pongRe("PONG\\s+(.*)\r\n$"); std::smatch msgMatches; std::string name = "irc"; std::string text = toParse; if (std::regex_search(toParse, msgMatches, pongRe)) { const auto ping_end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = ping_end - _ping_time; std::cerr << "[DEBUG] #irc: " << name << "Server pong reply: '" << msgMatches[1].str() << "' in " << diff.count() << "s" << std::endl; return nullptr; } if (std::regex_search(toParse, msgMatches, pingRe)) { const std::string pong = "PONG " + msgMatches[1].str(); std::cerr << "[DEBUG] #irc: sending " << pong << std::endl; send(pong); return nullptr; }; if (std::regex_search(toParse, msgMatches, msgRe)) { name = msgMatches[1].str(); text = msgMatches[4].str(); std::cerr << "[DEBUG] #irc:" << name << ": " << text << std::endl; }; const auto msg = std::make_shared<const messaging::TextMessage>(_id, std::make_shared<const messaging::User>(messaging::User(name.c_str())), text.c_str()); return msg; } int IrcChannel::registerConnection() { const std::string nick = _config.get("nickname", "chatsyncbot"); const std::string mode = _config.get("mode", "*"); const std::string hostname = _config.get("hostname", "chatsynchost"); const std::string servername = _config.get("servername", "chatsyncserver"); const std::string realname = _config.get("realname", "Chat Sync"); const std::string servicePassword = _config.get("servicepassword", ""); const auto passline = "PASS *\r\n"; const auto nickline = "NICK " + nick + "\r\n"; const auto userline = "USER " + nick + " " + hostname + " " + servername + " :" + realname + "\r\n"; const auto loginline = "PRIVMSG nickserv :id " + servicePassword + "\r\n"; const auto joinline = "JOIN #" + _channel + " \r\n"; send(passline); send(nickline); send(userline); std::this_thread::sleep_for(std::chrono::milliseconds (1000)); if (servicePassword.length() > 0) { std::async(std::launch::async, [this, loginline]() { send(_fd, loginline); std::this_thread::sleep_for(std::chrono::milliseconds (1000)); send(loginline); }); } send(joinline); std::this_thread::sleep_for(std::chrono::milliseconds (500)); send("PRIVMSG #" + _channel + " :Hello there\r\n"); return 0; } void IrcChannel::ping() { _ping_time = std::chrono::high_resolution_clock::now(); std::cerr << "[DEBUG] #irc: Sending ping" << std::endl; send("PING " + _server + "\r\n"); } void IrcChannel::checkTimeout() { const auto timestamp = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = timestamp - _ping_time; if (diff > max_timeout) { ping(); std::this_thread::sleep_for(std::chrono::milliseconds (150)); } } } <commit_msg>[Irc] Handling JOIN and QUIT<commit_after>#include "ircchannel.hpp" #include "hub.hpp" #include "messages.hpp" #include <stdexcept> #include <utility> #include <typeinfo> #include <regex> #include <memory> namespace ircChannel { IrcChannel::IrcChannel(Hub::Hub* hub, const std::string& config) : channeling::Channel(hub, config), _server(_config["server"]), _port(_config["port"]), _channel(_config["channel"]), _ping_time(std::chrono::high_resolution_clock::now()) {} std::future<void> IrcChannel::activate() { return std::async(std::launch::async, [this]() { if (_active) return; _fd = connect(_server, _port); startPolling(); std::async(std::launch::async, [this]() { std::this_thread::sleep_for(std::chrono::milliseconds (2000)); registerConnection(); }); _active = true; }); } IrcChannel::~IrcChannel() { disconnect(); stopPolling(); } void IrcChannel::incoming(const messaging::message_ptr&& msg) { char message[irc_message_max]; checkTimeout(); if (msg->type() == messaging::MessageType::Text) { const auto textmsg = messaging::TextMessage::fromMessage(msg); snprintf(message, irc_message_max, "PRIVMSG #%s :[%s]: %s\r\n", _channel.c_str(), textmsg->user()->name().c_str(), textmsg->data().c_str()); std::cerr << "[DEBUG] #irc " << _name << " " << textmsg->data() << " inside " << _name << std::endl; send(message); } } const messaging::message_ptr IrcChannel::parse(const char* line) const { // :[email protected] PRIVMSG #chatsync :ololo const std::string toParse(line); std::cerr << "[DEBUG] Parsing irc line:" << toParse << std::endl; std::regex msgRe (":(\\S+)!(\\S+)\\s+PRIVMSG\\s+#(\\S+)\\s+:(.*)\r\n$"); std::regex joinRe(":(\\S+)!(\\S+)\\s+JOIN\\s+:#(\\S+)$"); std::regex quitRe(":(\\S+)!(\\S+)\\s+QUIT\\s+:#(\\S+)$"); std::regex pingRe("PING\\s+:(.*)\r\n$"); std::regex pongRe("PONG\\s+(.*)\r\n$"); std::smatch msgMatches; std::string name = "irc"; std::string text = toParse; if (std::regex_search(toParse, msgMatches, pongRe)) { const auto ping_end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = ping_end - _ping_time; std::cerr << "[DEBUG] #irc: " << name << "Server pong reply: '" << msgMatches[1].str() << "' in " << diff.count() << "s" << std::endl; } if (std::regex_search(toParse, msgMatches, pingRe)) { const std::string pong = "PONG " + msgMatches[1].str(); std::cerr << "[DEBUG] #irc: sending " << pong << std::endl; send(pong); }; if (std::regex_search(toParse, msgMatches, joinRe)) { const auto name = msgMatches[1].str(); const auto host = msgMatches[2].str(); const auto chan = msgMatches[3].str(); std::cerr << "[DEBUG] #irc: user " << name << " has joined " << chan << " from " << host << std::endl; }; if (std::regex_search(toParse, msgMatches, quitRe)) { const auto name = msgMatches[1].str(); const auto host = msgMatches[2].str(); const auto msg = msgMatches[3].str(); std::cerr << "[DEBUG] #irc: user " << name << " has left because of " << msg << std::endl; }; if (std::regex_search(toParse, msgMatches, msgRe)) { name = msgMatches[1].str(); text = msgMatches[4].str(); std::cerr << "[DEBUG] #irc:" << name << ": " << text << std::endl; const auto msg = std::make_shared<const messaging::TextMessage>(_id, std::make_shared<const messaging::User>(messaging::User(name.c_str())), text.c_str()); return msg; }; return nullptr; } int IrcChannel::registerConnection() { const std::string nick = _config.get("nickname", "chatsyncbot"); const std::string mode = _config.get("mode", "*"); const std::string hostname = _config.get("hostname", "chatsynchost"); const std::string servername = _config.get("servername", "chatsyncserver"); const std::string realname = _config.get("realname", "Chat Sync"); const std::string servicePassword = _config.get("servicepassword", ""); const auto passline = "PASS *\r\n"; const auto nickline = "NICK " + nick + "\r\n"; const auto userline = "USER " + nick + " " + hostname + " " + servername + " :" + realname + "\r\n"; const auto loginline = "PRIVMSG nickserv :id " + servicePassword + "\r\n"; const auto joinline = "JOIN #" + _channel + " \r\n"; send(passline); send(nickline); send(userline); std::this_thread::sleep_for(std::chrono::milliseconds (1000)); if (servicePassword.length() > 0) { std::async(std::launch::async, [this, loginline]() { send(_fd, loginline); std::this_thread::sleep_for(std::chrono::milliseconds (1000)); send(loginline); }); } send(joinline); std::this_thread::sleep_for(std::chrono::milliseconds (500)); send("PRIVMSG #" + _channel + " :Hello there\r\n"); return 0; } void IrcChannel::ping() { _ping_time = std::chrono::high_resolution_clock::now(); std::cerr << "[DEBUG] #irc: Sending ping" << std::endl; send("PING " + _server + "\r\n"); } void IrcChannel::checkTimeout() { const auto timestamp = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = timestamp - _ping_time; if (diff > max_timeout) { ping(); std::this_thread::sleep_for(std::chrono::milliseconds (150)); } } } <|endoftext|>
<commit_before>// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "spatialdata/spatialdb/UserFunctionDB.hh" // Implementation of class methods // Include ios here to avoid some Python/gcc issues #include <ios> #include "spatialdata/geocoords/CoordSys.hh" // USES CoordSys #include "spatialdata/geocoords/Converter.hh" // USES Converter #include "spatialdata/units/Parser.hh" // USES Parser #include <stdexcept> // USES std::runtime_error #include <sstream> // USES std::ostringstream #include <cassert> // USES assert() // ---------------------------------------------------------------------- namespace spatialdata { namespace spatialdb { class UserFunctionDB::QueryFn1D : public UserFunctionDB::QueryFn { public: QueryFn1D(UserFunctionDB::userfn1D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 1 != dim) { return 1; } *value = _fn(coords[0]); return 0; }; private: UserFunctionDB::userfn1D_type _fn; }; class UserFunctionDB::QueryFn2D : public UserFunctionDB::QueryFn { public: QueryFn2D(UserFunctionDB::userfn2D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 2 != dim) { return 1; } *value = _fn(coords[0], coords[1]); return 0; }; private: UserFunctionDB::userfn2D_type _fn; }; class UserFunctionDB::QueryFn3D : public UserFunctionDB::QueryFn { public: QueryFn3D(UserFunctionDB::userfn3D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 3 != dim) { return 1; } *value = _fn(coords[0], coords[1], coords[2]); return 0; }; private: UserFunctionDB::userfn3D_type _fn; }; } // namespace spatialdb } // namespace spatialdata // ---------------------------------------------------------------------- // Constructor spatialdata::spatialdb::UserFunctionDB::UserFunctionDB(void) : _queryFunctions(NULL), _cs(NULL), _querySize(0) { // constructor } // constructor // ---------------------------------------------------------------------- // Destructor spatialdata::spatialdb::UserFunctionDB::~UserFunctionDB(void) { delete[] _queryFunctions; _queryFunctions = NULL; _querySize = 0; for (function_map::iterator iter=_functions.begin(); iter != _functions.end(); ++iter) { delete iter->second.fn; iter->second.fn = NULL; } // for delete _cs; _cs = NULL; } // destructor // ---------------------------------------------------------------------- // Add function/value to database in 1-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn1D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn1D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Add function/value to database in 2-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn2D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn2D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Add function/value to database in 3-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn3D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn3D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Open the database and prepare for querying. void spatialdata::spatialdb::UserFunctionDB::open(void) { // Compute conversion to SI units. spatialdata::units::Parser parser; const std::string& none = "none"; for (function_map::iterator iter=_functions.begin(); iter != _functions.end(); ++iter) { if (none != iter->second.units) { iter->second.scale = parser.parse(iter->second.units.c_str()); } else { iter->second.scale = 1.0; } // if/else } // for _checkCompatibility(); } // open // ---------------------------------------------------------------------- // Close the database. void spatialdata::spatialdb::UserFunctionDB::close(void) { delete[] _queryFunctions; _queryFunctions = NULL; } // close // ---------------------------------------------------------------------- // Set values to be returned by queries. void spatialdata::spatialdb::UserFunctionDB::queryVals(const char* const* names, const int numVals) { if (0 == numVals) { std::ostringstream msg; msg << "Number of values for query in spatial database " << label() << "\n must be positive.\n"; throw std::runtime_error(msg.str()); } // if assert(names && 0 < numVals); _querySize = numVals; delete[] _queryFunctions; _queryFunctions = numVals > 0 ? new UserData*[numVals] : NULL; for (int iVal=0; iVal < numVals; ++iVal) { const function_map::iterator iter = _functions.find(names[iVal]); if (_functions.end() == iter) { std::ostringstream msg; msg << "Could not find value '" << names[iVal] << "' in spatial database '" << label() << "'. Available values are:"; for (function_map::iterator viter = _functions.begin(); viter != _functions.end(); ++viter) { msg << "\n " << viter->first; } // for msg << "\n"; throw std::runtime_error(msg.str()); } // if _queryFunctions[iVal] = &iter->second; } // for } // queryVals // ---------------------------------------------------------------------- // Query the database. int spatialdata::spatialdb::UserFunctionDB::query(double* vals, const int numVals, const double* coords, const int numDims, const spatialdata::geocoords::CoordSys* csQuery) { // query const int querySize = _querySize; assert(_cs); if (0 == querySize) { std::ostringstream msg; msg << "Values to be returned by spatial database " << label() << " have not been set. Please call queryVals() before query().\n"; throw std::runtime_error(msg.str()); } else if (numVals != querySize) { std::ostringstream msg; msg << "Number of values to be returned by spatial database " << label() << " (" << querySize << ") does not match size of array provided (" << numVals << ").\n"; throw std::runtime_error(msg.str()); } else if (numDims != _cs->spaceDim()) { std::ostringstream msg; msg << "Spatial dimension (" << numDims << ") does not match spatial dimension of spatial database (" << _cs->spaceDim() << ")."; throw std::runtime_error(msg.str()); } // if // Convert coordinates assert(numDims <= 3); double xyz[3]; memcpy(xyz, coords, numDims*sizeof(double)); spatialdata::geocoords::Converter::convert(xyz, 1, numDims, _cs, csQuery); int queryFlag = 0; for (int iVal=0; iVal < querySize; ++iVal) { assert(_queryFunctions[iVal]->fn); queryFlag = _queryFunctions[iVal]->fn->query(&vals[iVal], xyz, numDims); if (queryFlag) { break; } vals[iVal] *= _queryFunctions[iVal]->scale; // Convert to SI units. } // for return queryFlag; } // query // ---------------------------------------------------------------------- // Set filename containing data. void spatialdata::spatialdb::UserFunctionDB::coordsys(const geocoords::CoordSys& cs) { // coordsys delete _cs; _cs = cs.clone(); assert(_cs); _cs->initialize(); } // coordsys // ---------------------------------------------------------------------- void spatialdata::spatialdb::UserFunctionDB::_checkAdd(const char* name, void* fn, const char* units) const { if (!name) { std::ostringstream msg; msg << "NULL name passed to addValue() for spatial database " << label() << "."; throw std::logic_error(msg.str()); } // if if (!units) { std::ostringstream msg; msg << "NULL units passed to addValue() for spatial database " << label() << "."; throw std::logic_error(msg.str()); } // if // Verify user function for value does not already exist. const function_map::const_iterator& iter = _functions.find(name); if (iter != _functions.end()) { std::ostringstream msg; msg << "Cannot add user function for value " << name << " to spatial database " << label() << ". User function for value already exists."; throw std::runtime_error(msg.str()); } // if if (!fn) { std::ostringstream msg; msg << "Cannot add NULL user function for value " << name << " to spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if } // _checkAdd // ---------------------------------------------------------------------- // Check compatibility of spatial database parameters. void spatialdata::spatialdb::UserFunctionDB::_checkCompatibility(void) const { // _checkCompatibility // Verify that we can call all user functions for given spatial dimension. if (!_cs) { std::ostringstream msg; msg << "Coordinate system has not been set for spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if double coords[3] = { 0.0, 0.0, 0.0 }; const int spaceDim = _cs->spaceDim(); assert(0 < spaceDim && spaceDim <= 3); double value; for (function_map::const_iterator iter = _functions.begin(); iter != _functions.end(); ++iter) { assert(iter->second.fn); const int flag = iter->second.fn->query(&value, coords, spaceDim); if (flag) { std::ostringstream msg; msg << "Error encountered in verifying compatibility for user function " << iter->second.fn << " for value '" << iter->first << "' in spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if } // for } // _checkCompatibility // End of file <commit_msg>Make no units for UserFunctionDB case insensitive.<commit_after>// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "spatialdata/spatialdb/UserFunctionDB.hh" // Implementation of class methods // Include ios here to avoid some Python/gcc issues #include <ios> #include "spatialdata/geocoords/CoordSys.hh" // USES CoordSys #include "spatialdata/geocoords/Converter.hh" // USES Converter #include "spatialdata/units/Parser.hh" // USES Parser #include <string> // USES std::string #include <stdexcept> // USES std::runtime_error #include <sstream> // USES std::ostringstream #include <cassert> // USES assert() // ---------------------------------------------------------------------- namespace spatialdata { namespace spatialdb { class UserFunctionDB::QueryFn1D : public UserFunctionDB::QueryFn { public: QueryFn1D(UserFunctionDB::userfn1D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 1 != dim) { return 1; } *value = _fn(coords[0]); return 0; }; private: UserFunctionDB::userfn1D_type _fn; }; class UserFunctionDB::QueryFn2D : public UserFunctionDB::QueryFn { public: QueryFn2D(UserFunctionDB::userfn2D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 2 != dim) { return 1; } *value = _fn(coords[0], coords[1]); return 0; }; private: UserFunctionDB::userfn2D_type _fn; }; class UserFunctionDB::QueryFn3D : public UserFunctionDB::QueryFn { public: QueryFn3D(UserFunctionDB::userfn3D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 3 != dim) { return 1; } *value = _fn(coords[0], coords[1], coords[2]); return 0; }; private: UserFunctionDB::userfn3D_type _fn; }; } // namespace spatialdb } // namespace spatialdata // ---------------------------------------------------------------------- // Constructor spatialdata::spatialdb::UserFunctionDB::UserFunctionDB(void) : _queryFunctions(NULL), _cs(NULL), _querySize(0) { // constructor } // constructor // ---------------------------------------------------------------------- // Destructor spatialdata::spatialdb::UserFunctionDB::~UserFunctionDB(void) { delete[] _queryFunctions; _queryFunctions = NULL; _querySize = 0; for (function_map::iterator iter=_functions.begin(); iter != _functions.end(); ++iter) { delete iter->second.fn; iter->second.fn = NULL; } // for delete _cs; _cs = NULL; } // destructor // ---------------------------------------------------------------------- // Add function/value to database in 1-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn1D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn1D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Add function/value to database in 2-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn2D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn2D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Add function/value to database in 3-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn3D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn3D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Open the database and prepare for querying. void spatialdata::spatialdb::UserFunctionDB::open(void) { // Compute conversion to SI units. spatialdata::units::Parser parser; const std::string& none = "none"; for (function_map::iterator iter=_functions.begin(); iter != _functions.end(); ++iter) { if (strcasecmp(none.c_str(), iter->second.units.c_str()) != 0) { iter->second.scale = parser.parse(iter->second.units.c_str()); } else { iter->second.scale = 1.0; } // if/else } // for _checkCompatibility(); } // open // ---------------------------------------------------------------------- // Close the database. void spatialdata::spatialdb::UserFunctionDB::close(void) { delete[] _queryFunctions; _queryFunctions = NULL; } // close // ---------------------------------------------------------------------- // Set values to be returned by queries. void spatialdata::spatialdb::UserFunctionDB::queryVals(const char* const* names, const int numVals) { if (0 == numVals) { std::ostringstream msg; msg << "Number of values for query in spatial database " << label() << "\n must be positive.\n"; throw std::runtime_error(msg.str()); } // if assert(names && 0 < numVals); _querySize = numVals; delete[] _queryFunctions; _queryFunctions = numVals > 0 ? new UserData*[numVals] : NULL; for (int iVal=0; iVal < numVals; ++iVal) { const function_map::iterator iter = _functions.find(names[iVal]); if (_functions.end() == iter) { std::ostringstream msg; msg << "Could not find value '" << names[iVal] << "' in spatial database '" << label() << "'. Available values are:"; for (function_map::iterator viter = _functions.begin(); viter != _functions.end(); ++viter) { msg << "\n " << viter->first; } // for msg << "\n"; throw std::runtime_error(msg.str()); } // if _queryFunctions[iVal] = &iter->second; } // for } // queryVals // ---------------------------------------------------------------------- // Query the database. int spatialdata::spatialdb::UserFunctionDB::query(double* vals, const int numVals, const double* coords, const int numDims, const spatialdata::geocoords::CoordSys* csQuery) { // query const int querySize = _querySize; assert(_cs); if (0 == querySize) { std::ostringstream msg; msg << "Values to be returned by spatial database " << label() << " have not been set. Please call queryVals() before query().\n"; throw std::runtime_error(msg.str()); } else if (numVals != querySize) { std::ostringstream msg; msg << "Number of values to be returned by spatial database " << label() << " (" << querySize << ") does not match size of array provided (" << numVals << ").\n"; throw std::runtime_error(msg.str()); } else if (numDims != _cs->spaceDim()) { std::ostringstream msg; msg << "Spatial dimension (" << numDims << ") does not match spatial dimension of spatial database (" << _cs->spaceDim() << ")."; throw std::runtime_error(msg.str()); } // if // Convert coordinates assert(numDims <= 3); double xyz[3]; memcpy(xyz, coords, numDims*sizeof(double)); spatialdata::geocoords::Converter::convert(xyz, 1, numDims, _cs, csQuery); int queryFlag = 0; for (int iVal=0; iVal < querySize; ++iVal) { assert(_queryFunctions[iVal]->fn); queryFlag = _queryFunctions[iVal]->fn->query(&vals[iVal], xyz, numDims); if (queryFlag) { break; } vals[iVal] *= _queryFunctions[iVal]->scale; // Convert to SI units. } // for return queryFlag; } // query // ---------------------------------------------------------------------- // Set filename containing data. void spatialdata::spatialdb::UserFunctionDB::coordsys(const geocoords::CoordSys& cs) { // coordsys delete _cs; _cs = cs.clone(); assert(_cs); _cs->initialize(); } // coordsys // ---------------------------------------------------------------------- void spatialdata::spatialdb::UserFunctionDB::_checkAdd(const char* name, void* fn, const char* units) const { if (!name) { std::ostringstream msg; msg << "NULL name passed to addValue() for spatial database " << label() << "."; throw std::logic_error(msg.str()); } // if if (!units) { std::ostringstream msg; msg << "NULL units passed to addValue() for spatial database " << label() << "."; throw std::logic_error(msg.str()); } // if // Verify user function for value does not already exist. const function_map::const_iterator& iter = _functions.find(name); if (iter != _functions.end()) { std::ostringstream msg; msg << "Cannot add user function for value " << name << " to spatial database " << label() << ". User function for value already exists."; throw std::runtime_error(msg.str()); } // if if (!fn) { std::ostringstream msg; msg << "Cannot add NULL user function for value " << name << " to spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if } // _checkAdd // ---------------------------------------------------------------------- // Check compatibility of spatial database parameters. void spatialdata::spatialdb::UserFunctionDB::_checkCompatibility(void) const { // _checkCompatibility // Verify that we can call all user functions for given spatial dimension. if (!_cs) { std::ostringstream msg; msg << "Coordinate system has not been set for spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if double coords[3] = { 0.0, 0.0, 0.0 }; const int spaceDim = _cs->spaceDim(); assert(0 < spaceDim && spaceDim <= 3); double value; for (function_map::const_iterator iter = _functions.begin(); iter != _functions.end(); ++iter) { assert(iter->second.fn); const int flag = iter->second.fn->query(&value, coords, spaceDim); if (flag) { std::ostringstream msg; msg << "Error encountered in verifying compatibility for user function " << iter->second.fn << " for value '" << iter->first << "' in spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if } // for } // _checkCompatibility // End of file <|endoftext|>
<commit_before>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /* 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 HOLDER 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 <vl/Renderer.hpp> #include <vl/RenderQueue.hpp> #include <vl/Effect.hpp> #include <vl/Transform.hpp> #include <vl/checks.hpp> #include <vl/GLSL.hpp> #include <vl/Light.hpp> #include <vl/ClipPlane.hpp> #include <vl/Time.hpp> #include <vl/Log.hpp> #include <vl/Say.hpp> using namespace vl; //------------------------------------------------------------------------------ // Renderer //------------------------------------------------------------------------------ Renderer::Renderer() { #ifndef NDEBUG mObjectName = className(); #endif mProjViewTranfCallback = new ProjViewTranfCallbackStandard; mDummyEnables = new EnableSet; mDummyStateSet = new RenderStateSet; } //------------------------------------------------------------------------------ namespace { struct ShaderInfo { public: ShaderInfo(): mTransform(NULL), mShaderUniformSet(NULL), mActorUniformSet(NULL) {} bool operator<(const ShaderInfo& other) const { if (mTransform != other.mTransform) return mTransform < other.mTransform; else if ( mShaderUniformSet != other.mShaderUniformSet ) return mShaderUniformSet < other.mShaderUniformSet; else return mActorUniformSet < other.mActorUniformSet; } const Transform* mTransform; const UniformSet* mShaderUniformSet; const UniformSet* mActorUniformSet; }; } //------------------------------------------------------------------------------ const RenderQueue* Renderer::render(const RenderQueue* render_queue, Camera* camera, Real frame_clock) { VL_CHECK_OGL() // skip if renderer is disabled if (enableMask() == 0) return render_queue; // enter/exit behavior contract class InOutContract { Renderer* mRenderer; public: InOutContract(Renderer* renderer, Camera* camera): mRenderer(renderer) { // increment the render tick. mRenderer->mRenderTick++; // render-target activation. // note: an OpenGL context can have multiple rendering targets! mRenderer->renderTarget()->activate(); // viewport setup. camera->viewport()->setClearFlags( mRenderer->clearFlags() ); camera->viewport()->activate(); // dispatch the renderer-started event. mRenderer->dispatchOnRendererStarted(); // check user-generated errors. VL_CHECK_OGL() } ~InOutContract() { // dispatch the renderer-finished event mRenderer->dispatchOnRendererFinished(); // check user-generated errors. VL_CHECK_OGL() // note: we don't reset the render target here } }; InOutContract contract(this, camera); // --------------- rendering --------------- std::map<const GLSLProgram*, ShaderInfo> glslprogram_map; OpenGLContext* opengl_context = renderTarget()->openglContext(); // --------------- default scissor --------------- // non GLSLProgram state sets const RenderStateSet* cur_render_state_set = NULL; const EnableSet* cur_enable_set = NULL; const Scissor* cur_scissor = NULL; // scissor the viewport by default: needed for points and lines sice they are not clipped against the viewport #if 1 glEnable(GL_SCISSOR_TEST); glScissor(camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height()); #else glDisable(GL_SCISSOR_TEST); #endif // --------------- rendering --------------- for(int itok=0; itok < render_queue->size(); ++itok) { const RenderToken* tok = render_queue->at(itok); VL_CHECK(tok); Actor* actor = tok->mActor; VL_CHECK(actor); if ( !isEnabled(actor->enableMask()) ) continue; // --------------- Actor's scissor --------------- const Scissor* scissor = actor->scissor() ? actor->scissor() : tok->mShader->scissor(); if (cur_scissor != scissor) { cur_scissor = scissor; if (cur_scissor) { cur_scissor->enable(camera->viewport()); } else { #if 1 // scissor the viewport by default: needed for points and lines with size > 1.0 as they are not clipped against the viewport. VL_CHECK(glIsEnabled(GL_SCISSOR_TEST)) glScissor(camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height()); #else glDisable(GL_SCISSOR_TEST); #endif } } // multipassing for( int ipass=0; tok != NULL; tok = tok->mNextPass, ++ipass ) { VL_CHECK_OGL() // --------------- shader setup --------------- const Shader* shader = tok->mShader; // shader override for( std::map< unsigned int, ref<Shader> >::const_iterator eom_it = mShaderOverrideMask.begin(); eom_it != mShaderOverrideMask.end(); ++eom_it ) { if ( eom_it->first & actor->enableMask() ) shader = eom_it->second.get(); } // shader's render states if ( cur_render_state_set != shader->getRenderStateSet() ) { opengl_context->applyRenderStates(cur_render_state_set, shader->getRenderStateSet(), camera ); cur_render_state_set = shader->getRenderStateSet(); } VL_CHECK_OGL() // shader's enables if ( cur_enable_set != shader->getEnableSet() ) { opengl_context->applyEnables(cur_enable_set, shader->getEnableSet() ); cur_enable_set = shader->getEnableSet(); } #ifndef NDEBUG if (glGetError() != GL_NO_ERROR) { Log::error("An unsupported OpenGL glEnable/glDisable capability has been enabled!\n"); VL_TRAP() } #endif // --------------- Actor pre-render callback --------------- // here the user has still the possibility to modify the Actor's uniforms /* mic fixme: document this */ actor->dispatchOnActorRenderStarted( frame_clock, camera, tok->mRenderable, shader, ipass ); VL_CHECK_OGL() // --------------- GLSLProgram setup --------------- VL_CHECK( !shader->glslProgram() || shader->glslProgram()->linked() ); VL_CHECK_OGL() // current transform const Transform* cur_transform = actor->transform(); const GLSLProgram* cur_glsl_program = NULL; // NULL == fixed function pipeline const UniformSet* cur_shader_uniform_set = NULL; const UniformSet* cur_actor_uniform_set = NULL; // make sure we update these things only if there is a valid GLSLProgram if (shader->glslProgram() && shader->glslProgram()->handle()) { cur_glsl_program = shader->glslProgram(); cur_shader_uniform_set = shader->getUniformSet(); cur_actor_uniform_set = actor->getUniformSet(); // consider them NULL if they are empty if (cur_shader_uniform_set && cur_shader_uniform_set->uniforms().empty()) cur_shader_uniform_set = NULL; if (cur_actor_uniform_set && cur_actor_uniform_set ->uniforms().empty()) cur_actor_uniform_set = NULL; } // is it the first update we do overall? (ie this is the first object rendered) bool is_first_overall = glslprogram_map.empty(); bool update_su = false; // update shader uniforms bool update_au = false; // update actor uniforms bool update_tr = false; // update transform ShaderInfo* shader_info = NULL; // retrieve the state of this GLSLProgram (including the NULL one) std::map<const GLSLProgram*, ShaderInfo>::iterator shader_info_it = glslprogram_map.find(cur_glsl_program); bool is_first_use = false; if ( shader_info_it == glslprogram_map.end() ) { // create a new shader-info entry shader_info = &glslprogram_map[cur_glsl_program]; // update_tr = true; not needed since is_first_use overrides it. update_su = cur_shader_uniform_set != NULL ? true : false; update_au = cur_actor_uniform_set != NULL ? true : false; // is it the first update to this GLSLProgram? Yes. is_first_use = true; } else { shader_info = &shader_info_it->second; // check for differences update_tr = shader_info->mTransform != cur_transform; update_su = shader_info->mShaderUniformSet != cur_shader_uniform_set && cur_shader_uniform_set; update_au = shader_info->mActorUniformSet != cur_actor_uniform_set && cur_actor_uniform_set; } // update shader-info structure shader_info->mTransform = cur_transform; shader_info->mShaderUniformSet = cur_shader_uniform_set; shader_info->mActorUniformSet = cur_actor_uniform_set; // fixme? // theoretically we can optimize further caching the last GLSLProgram used and it's shader-info and if // the new one is the same as the old one we can avoid looking up in the map. The gain should be minimal // and the code would get further clutterd. // --- update proj, view and transform matrices --- VL_CHECK_OGL() if (is_first_use) // note: 'is_first_overall' implies 'is_first_use' projViewTransfCallback()->programFirstUse(this, cur_glsl_program, cur_transform, camera, is_first_overall); else if (update_tr) projViewTransfCallback()->programTransfChange(this, cur_glsl_program, cur_transform, camera); VL_CHECK_OGL() // --- uniforms --- // note: the user must not make the shader's and actor's uniforms collide! VL_CHECK( !opengl_context->areUniformsColliding(cur_shader_uniform_set, cur_actor_uniform_set) ); // 'static' uniform set: update only once per rendering, if present. if (is_first_use && cur_glsl_program && cur_glsl_program->uniformSet()) { cur_glsl_program->applyUniformSet(cur_glsl_program->uniformSet()); } // shader uniform set if ( update_su ) { VL_CHECK( cur_shader_uniform_set && cur_shader_uniform_set->uniforms().size() ); VL_CHECK( shader->getRenderStateSet()->glslProgram() && shader->getRenderStateSet()->glslProgram()->handle() ) cur_glsl_program->applyUniformSet( cur_shader_uniform_set ); } VL_CHECK_OGL() // actor uniform set if ( update_au ) { VL_CHECK( cur_actor_uniform_set && cur_actor_uniform_set->uniforms().size() ); VL_CHECK( shader->getRenderStateSet()->glslProgram() && shader->getRenderStateSet()->glslProgram()->handle() ) cur_glsl_program->applyUniformSet( cur_actor_uniform_set ); } VL_CHECK_OGL() // --------------- Actor rendering --------------- // contract (mic fixme: to be changed for vertex-array and elem-array lazy bind): // 1 - all vertex arrays and VBOs are disabled before calling render() // 2 - all vertex arrays and VBOs are disabled after calling render() VL_CHECK( !tok->mRenderable->displayListEnabled() || (tok->mRenderable->displayListEnabled() && tok->mRenderable->displayList()) ) if (tok->mRenderable->displayListEnabled()) glCallList( tok->mRenderable->displayList() ); else tok->mRenderable->render( actor, camera ); VL_CHECK_OGL() // if shader is overridden it does not make sense to perform multipassing so we break the loop here. if (shader != tok->mShader) break; } } // clear enables opengl_context->applyEnables(cur_enable_set, mDummyEnables.get() ); // clear render states opengl_context->applyRenderStates(cur_render_state_set, mDummyStateSet.get(), camera ); glDisable(GL_SCISSOR_TEST); return render_queue; } //----------------------------------------------------------------------------- void ProjViewTranfCallbackStandard::programFirstUse(const Renderer*, const GLSLProgram*, const Transform* transform, const Camera* camera, bool first_overall) { if (mLastTransform != transform || first_overall) { if ( transform ) { glMatrixMode(GL_MODELVIEW); VL_glLoadMatrix( (camera->viewMatrix() * transform->worldMatrix() ).ptr() ); } else { glMatrixMode(GL_MODELVIEW); VL_glLoadMatrix( camera->viewMatrix().ptr() ); } } // set the projection matrix only once per rendering if (first_overall) { glMatrixMode(GL_PROJECTION); VL_glLoadMatrix( (camera->projectionMatrix() ).ptr() ); } // update last transform mLastTransform = transform; } //----------------------------------------------------------------------------- void ProjViewTranfCallbackStandard::programTransfChange(const Renderer*, const GLSLProgram*, const Transform* transform, const Camera* camera) { if (mLastTransform != transform) { if ( transform ) { glMatrixMode(GL_MODELVIEW); VL_glLoadMatrix( (camera->viewMatrix() * transform->worldMatrix() ).ptr() ); } else { glMatrixMode(GL_MODELVIEW); VL_glLoadMatrix( camera->viewMatrix().ptr() ); } } // update last transform mLastTransform = transform; } //----------------------------------------------------------------------------- <commit_msg>enable texture unit 0 on exit, extra checks in debug mode.<commit_after>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /* 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 HOLDER 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 <vl/Renderer.hpp> #include <vl/RenderQueue.hpp> #include <vl/Effect.hpp> #include <vl/Transform.hpp> #include <vl/checks.hpp> #include <vl/GLSL.hpp> #include <vl/Light.hpp> #include <vl/ClipPlane.hpp> #include <vl/Time.hpp> #include <vl/Log.hpp> #include <vl/Say.hpp> using namespace vl; //------------------------------------------------------------------------------ // Renderer //------------------------------------------------------------------------------ Renderer::Renderer() { #ifndef NDEBUG mObjectName = className(); #endif mProjViewTranfCallback = new ProjViewTranfCallbackStandard; mDummyEnables = new EnableSet; mDummyStateSet = new RenderStateSet; } //------------------------------------------------------------------------------ namespace { struct ShaderInfo { public: ShaderInfo(): mTransform(NULL), mShaderUniformSet(NULL), mActorUniformSet(NULL) {} bool operator<(const ShaderInfo& other) const { if (mTransform != other.mTransform) return mTransform < other.mTransform; else if ( mShaderUniformSet != other.mShaderUniformSet ) return mShaderUniformSet < other.mShaderUniformSet; else return mActorUniformSet < other.mActorUniformSet; } const Transform* mTransform; const UniformSet* mShaderUniformSet; const UniformSet* mActorUniformSet; }; } //------------------------------------------------------------------------------ const RenderQueue* Renderer::render(const RenderQueue* render_queue, Camera* camera, Real frame_clock) { VL_CHECK_OGL() // skip if renderer is disabled if (enableMask() == 0) return render_queue; // enter/exit behavior contract class InOutContract { Renderer* mRenderer; public: InOutContract(Renderer* renderer, Camera* camera): mRenderer(renderer) { // increment the render tick. mRenderer->mRenderTick++; // render-target activation. // note: an OpenGL context can have multiple rendering targets! mRenderer->renderTarget()->activate(); // viewport setup. camera->viewport()->setClearFlags( mRenderer->clearFlags() ); camera->viewport()->activate(); // dispatch the renderer-started event. mRenderer->dispatchOnRendererStarted(); // check user-generated errors. VL_CHECK_OGL() } ~InOutContract() { // dispatch the renderer-finished event mRenderer->dispatchOnRendererFinished(); // check user-generated errors. VL_CHECK_OGL() // note: we don't reset the render target here } }; InOutContract contract(this, camera); // --------------- rendering --------------- std::map<const GLSLProgram*, ShaderInfo> glslprogram_map; OpenGLContext* opengl_context = renderTarget()->openglContext(); // --------------- default scissor --------------- // non GLSLProgram state sets const RenderStateSet* cur_render_state_set = NULL; const EnableSet* cur_enable_set = NULL; const Scissor* cur_scissor = NULL; // scissor the viewport by default: needed for points and lines sice they are not clipped against the viewport #if 1 glEnable(GL_SCISSOR_TEST); glScissor(camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height()); #else glDisable(GL_SCISSOR_TEST); #endif // --------------- rendering --------------- for(int itok=0; itok < render_queue->size(); ++itok) { const RenderToken* tok = render_queue->at(itok); VL_CHECK(tok); Actor* actor = tok->mActor; VL_CHECK(actor); if ( !isEnabled(actor->enableMask()) ) continue; // --------------- Actor's scissor --------------- const Scissor* scissor = actor->scissor() ? actor->scissor() : tok->mShader->scissor(); if (cur_scissor != scissor) { cur_scissor = scissor; if (cur_scissor) { cur_scissor->enable(camera->viewport()); } else { #if 1 // scissor the viewport by default: needed for points and lines with size > 1.0 as they are not clipped against the viewport. VL_CHECK(glIsEnabled(GL_SCISSOR_TEST)) glScissor(camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height()); #else glDisable(GL_SCISSOR_TEST); #endif } } // multipassing for( int ipass=0; tok != NULL; tok = tok->mNextPass, ++ipass ) { VL_CHECK_OGL() // --------------- shader setup --------------- const Shader* shader = tok->mShader; // shader override for( std::map< unsigned int, ref<Shader> >::const_iterator eom_it = mShaderOverrideMask.begin(); eom_it != mShaderOverrideMask.end(); ++eom_it ) { if ( eom_it->first & actor->enableMask() ) shader = eom_it->second.get(); } // shader's render states if ( cur_render_state_set != shader->getRenderStateSet() ) { opengl_context->applyRenderStates(cur_render_state_set, shader->getRenderStateSet(), camera ); cur_render_state_set = shader->getRenderStateSet(); } VL_CHECK_OGL() // shader's enables if ( cur_enable_set != shader->getEnableSet() ) { opengl_context->applyEnables(cur_enable_set, shader->getEnableSet() ); cur_enable_set = shader->getEnableSet(); } #ifndef NDEBUG if (glGetError() != GL_NO_ERROR) { Log::error("An unsupported OpenGL glEnable/glDisable capability has been enabled!\n"); VL_TRAP() } #endif // --------------- Actor pre-render callback --------------- // here the user has still the possibility to modify the Actor's uniforms /* mic fixme: document this */ actor->dispatchOnActorRenderStarted( frame_clock, camera, tok->mRenderable, shader, ipass ); VL_CHECK_OGL() // --------------- GLSLProgram setup --------------- VL_CHECK( !shader->glslProgram() || shader->glslProgram()->linked() ); VL_CHECK_OGL() // current transform const Transform* cur_transform = actor->transform(); const GLSLProgram* cur_glsl_program = NULL; // NULL == fixed function pipeline const UniformSet* cur_shader_uniform_set = NULL; const UniformSet* cur_actor_uniform_set = NULL; // make sure we update these things only if there is a valid GLSLProgram if (shader->glslProgram() && shader->glslProgram()->handle()) { cur_glsl_program = shader->glslProgram(); cur_shader_uniform_set = shader->getUniformSet(); cur_actor_uniform_set = actor->getUniformSet(); // consider them NULL if they are empty if (cur_shader_uniform_set && cur_shader_uniform_set->uniforms().empty()) cur_shader_uniform_set = NULL; if (cur_actor_uniform_set && cur_actor_uniform_set ->uniforms().empty()) cur_actor_uniform_set = NULL; } // is it the first update we do overall? (ie this is the first object rendered) bool is_first_overall = glslprogram_map.empty(); bool update_su = false; // update shader uniforms bool update_au = false; // update actor uniforms bool update_tr = false; // update transform ShaderInfo* shader_info = NULL; // retrieve the state of this GLSLProgram (including the NULL one) std::map<const GLSLProgram*, ShaderInfo>::iterator shader_info_it = glslprogram_map.find(cur_glsl_program); bool is_first_use = false; if ( shader_info_it == glslprogram_map.end() ) { // create a new shader-info entry shader_info = &glslprogram_map[cur_glsl_program]; // update_tr = true; not needed since is_first_use overrides it. update_su = cur_shader_uniform_set != NULL ? true : false; update_au = cur_actor_uniform_set != NULL ? true : false; // is it the first update to this GLSLProgram? Yes. is_first_use = true; } else { shader_info = &shader_info_it->second; // check for differences update_tr = shader_info->mTransform != cur_transform; update_su = shader_info->mShaderUniformSet != cur_shader_uniform_set && cur_shader_uniform_set; update_au = shader_info->mActorUniformSet != cur_actor_uniform_set && cur_actor_uniform_set; } // update shader-info structure shader_info->mTransform = cur_transform; shader_info->mShaderUniformSet = cur_shader_uniform_set; shader_info->mActorUniformSet = cur_actor_uniform_set; // fixme? // theoretically we can optimize further caching the last GLSLProgram used and it's shader-info and if // the new one is the same as the old one we can avoid looking up in the map. The gain should be minimal // and the code would get further clutterd. // --- update proj, view and transform matrices --- VL_CHECK_OGL() if (is_first_use) // note: 'is_first_overall' implies 'is_first_use' projViewTransfCallback()->programFirstUse(this, cur_glsl_program, cur_transform, camera, is_first_overall); else if (update_tr) projViewTransfCallback()->programTransfChange(this, cur_glsl_program, cur_transform, camera); VL_CHECK_OGL() // --- uniforms --- // note: the user must not make the shader's and actor's uniforms collide! VL_CHECK( !opengl_context->areUniformsColliding(cur_shader_uniform_set, cur_actor_uniform_set) ); // 'static' uniform set: update only once per rendering, if present. if (is_first_use && cur_glsl_program && cur_glsl_program->uniformSet()) { cur_glsl_program->applyUniformSet(cur_glsl_program->uniformSet()); } // shader uniform set if ( update_su ) { VL_CHECK( cur_shader_uniform_set && cur_shader_uniform_set->uniforms().size() ); VL_CHECK( shader->getRenderStateSet()->glslProgram() && shader->getRenderStateSet()->glslProgram()->handle() ) cur_glsl_program->applyUniformSet( cur_shader_uniform_set ); } VL_CHECK_OGL() // actor uniform set if ( update_au ) { VL_CHECK( cur_actor_uniform_set && cur_actor_uniform_set->uniforms().size() ); VL_CHECK( shader->getRenderStateSet()->glslProgram() && shader->getRenderStateSet()->glslProgram()->handle() ) cur_glsl_program->applyUniformSet( cur_actor_uniform_set ); } VL_CHECK_OGL() // --------------- Actor rendering --------------- // contract (mic fixme: to be changed for vertex-array and elem-array lazy bind): // 1 - all vertex arrays and VBOs are disabled before calling render() // 2 - all vertex arrays and VBOs are disabled after calling render() VL_CHECK( !tok->mRenderable->displayListEnabled() || (tok->mRenderable->displayListEnabled() && tok->mRenderable->displayList()) ) if (tok->mRenderable->displayListEnabled()) glCallList( tok->mRenderable->displayList() ); else tok->mRenderable->render( actor, camera ); VL_CHECK_OGL() // if shader is overridden it does not make sense to perform multipassing so we break the loop here. if (shader != tok->mShader) break; } } // clear enables opengl_context->applyEnables(cur_enable_set, mDummyEnables.get() ); // clear render states opengl_context->applyRenderStates(cur_render_state_set, mDummyStateSet.get(), camera ); // enabled texture unit #0 VL_glActiveTexture( GL_TEXTURE0 ); VL_glClientActiveTexture( GL_TEXTURE0 ); glDisable(GL_SCISSOR_TEST); VL_CHECK( opengl_context->isCleanState(true) ); return render_queue; } //----------------------------------------------------------------------------- void ProjViewTranfCallbackStandard::programFirstUse(const Renderer*, const GLSLProgram*, const Transform* transform, const Camera* camera, bool first_overall) { if (mLastTransform != transform || first_overall) { if ( transform ) { glMatrixMode(GL_MODELVIEW); VL_glLoadMatrix( (camera->viewMatrix() * transform->worldMatrix() ).ptr() ); } else { glMatrixMode(GL_MODELVIEW); VL_glLoadMatrix( camera->viewMatrix().ptr() ); } } // set the projection matrix only once per rendering if (first_overall) { glMatrixMode(GL_PROJECTION); VL_glLoadMatrix( (camera->projectionMatrix() ).ptr() ); } // update last transform mLastTransform = transform; } //----------------------------------------------------------------------------- void ProjViewTranfCallbackStandard::programTransfChange(const Renderer*, const GLSLProgram*, const Transform* transform, const Camera* camera) { if (mLastTransform != transform) { if ( transform ) { glMatrixMode(GL_MODELVIEW); VL_glLoadMatrix( (camera->viewMatrix() * transform->worldMatrix() ).ptr() ); } else { glMatrixMode(GL_MODELVIEW); VL_glLoadMatrix( camera->viewMatrix().ptr() ); } } // update last transform mLastTransform = transform; } //----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "UASQuickTabView.h" #include "ui_UASQuickTabView.h" #include <QTextCodec> #include <QDebug> #include <QTableWidget> UASQuickTabView::UASQuickTabView(QWidget *parent) : ui(new Ui::UASQuickTabView) { ui->setupUi(this); this->setLayout(ui->gridLayout); QStringList nameList;// = new QStringList(); // nameList.append("Широта:"); // nameList.append("Долгота:"); // nameList.append("Высота:"); // nameList.append("Курс:"); // nameList.append("Крен:"); // nameList.append("Тангаж:"); nameList.append(tr("Latitude:")); nameList.append(tr("Longitude:")); nameList.append(tr("Altitude:")); nameList.append(tr("Roll:")); nameList.append(tr("Pitch:")); nameList.append(tr("Yaw:")); fieldNameList << "M24:GLOBAL_POSITION_INT.lat" << "M24:GLOBAL_POSITION_INT.lon" << "M24:GLOBAL_POSITION_INT.alt" << "M24:ATTITUDE.roll" << "M24:ATTITUDE.pitch" << "M24:ATTITUDE.yaw"; foreach(QString str, fieldNameList){ uasPropertyValueMap.insert(str, 0.0); } QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); ui->tableWidget->setColumnCount(2); ui->tableWidget->setRowCount(6); ui->tableWidget->setLineWidth(1); ui->tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->tableWidget->setStyleSheet("gridline-color : gray"); //tableFont = new QFont("Times New Roman", 14, 3); // tableFont.setFamily("Times New Roman"); tableFont.setPixelSize(14); tableFont.setBold(3); for(int i = 0; i < nameList.count(); i++) { /* Add first column that shows lable names.*/ QTableWidgetItem* item = new QTableWidgetItem(); Q_ASSERT(item); if (item) { item->setText(nameList.at(i)); tableNameList.append(item); item->setFont(tableFont); item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable); ui->tableWidget->setItem(i, 0, item); } /* Add column with values.*/ item = new QTableWidgetItem(); Q_ASSERT(item); if (item) { tableValueList.append(item); item->setFont(tableFont); item->setText("0.0"); item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable); ui->tableWidget->setItem(i, 1, item); } } updateTimer = new QTimer(this); connect(updateTimer,SIGNAL(timeout()),this,SLOT(updateTimerTick())); updateTimer->start(1000); // testTimerValue = true; // testTimer = new QTimer(this); // testTimer->setSingleShot(false); // connect(testTimer,SIGNAL(timeout()),this,SLOT(testTimerExpired())); // testTimer->start(750); } UASQuickTabView::~UASQuickTabView() { delete ui; foreach (QTableWidgetItem* item, tableNameList) { delete item; } foreach (QTableWidgetItem* item, tableValueList) { delete item; } delete updateTimer; } void UASQuickTabView::addSource(MAVLinkDecoder *decoder) { connect(decoder,SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),this,SLOT(valueChanged(int,QString,QString,QVariant,quint64))); } void UASQuickTabView::valueChanged(const int uasId, const QString& name, const QString& unit, const QVariant &variant, const quint64 msec) { Q_UNUSED(uasId); Q_UNUSED(unit); Q_UNUSED(msec); bool ok; double value = variant.toDouble(&ok); QMetaType::Type metaType = static_cast<QMetaType::Type>(variant.type()); if(!ok || metaType == QMetaType::QString || metaType == QMetaType::QByteArray) return; //qDebug()<<name<<" "<<value; // if (!uasPropertyValueMap.contains(name)) // { // if (quickViewSelectDialog) // { // quickViewSelectDialog->addItem(name); // } // } if((name == "M24:GLOBAL_POSITION_INT.lat")||(name == "M24:GLOBAL_POSITION_INT.lon")) uasPropertyValueMap[name] = value/10000000; else if(name == "M24:GLOBAL_POSITION_INT.alt") uasPropertyValueMap[name] = value/1000; else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw")) uasPropertyValueMap[name] = value/M_PI*180; } void UASQuickTabView::updateTimerTick() { for(int i = 0; i < fieldNameList.size(); i++){ //QString str = QString::number(uasPropertyValueMap[fieldNameList.at(i)]); QString str = formText(fieldNameList.at(i), uasPropertyValueMap[fieldNameList.at(i)]); ui->tableWidget->item(i,1)->setText(str); } } //void UASQuickTabView::testTimerExpired(){ // if(testTimerValue == true){ // valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",538893530,0); // valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",275296780,0); // valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",272000,0); // valueChanged(0,"M24:ATTITUDE.roll","unit",0.36814,0); // valueChanged(0,"M24:ATTITUDE.pitch","unit",0.56715,0); // valueChanged(0,"M24:ATTITUDE.yaw","unit",0.24715,0); // testTimerValue = false; // } // else{ // valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",-549993530,0); // valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",-277796780,0); // valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",284000,0); // valueChanged(0,"M24:ATTITUDE.roll","unit",0.35614,0); // valueChanged(0,"M24:ATTITUDE.pitch","unit",0.46815,0); // valueChanged(0,"M24:ATTITUDE.yaw","unit",0.67895,0); // testTimerValue = true; // } //} void UASQuickTabView::setTableGeometry(){ ui->tableWidget->setColumnWidth(0, ((this->width() - 5)/2)); ui->tableWidget->setColumnWidth(1, ((this->width())/2)); for(int i = 0; i < ui->tableWidget->rowCount(); i++) { ui->tableWidget->setRowHeight(i, (this->height() - 2)/6); //qDebug()<<"qgridrowminimumheight: "<<ui->gridLayout->rowMinimumHeight(0); } } QString UASQuickTabView::formText(QString name, double value){ QString str; if(name == "M24:GLOBAL_POSITION_INT.lat"){ if(value >= 0){ str = QString::number(value,'f',5); str += 0x00B0; str += tr(" N"); } else if(value < 0){ value *=-1; str = QString::number(value,'f',5); str += 0x00B0; str += tr(" S"); } } else if(name == "M24:GLOBAL_POSITION_INT.lon"){ if(value >= 0){ str = QString::number(value,'f',5); str += 0x00B0; str += tr(" E"); } else if(value < 0){ value *=-1; str = QString::number(value,'f',5); str += 0x00B0; str += tr(" W"); } } else if(name == "M24:GLOBAL_POSITION_INT.alt"){ str = QString::number(value,'f',1); str +=tr(" m."); } else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw")){ str = QString::number(value,'f',2); str += 0x00B0; } return str; } void UASQuickTabView::resizeEvent(QResizeEvent *event){ setTableGeometry(); } <commit_msg>Removed hardcode from quick tab view.<commit_after>#include "UASQuickTabView.h" #include "ui_UASQuickTabView.h" #include <QTextCodec> #include <QDebug> #include <QTableWidget> UASQuickTabView::UASQuickTabView(QWidget *parent) : ui(new Ui::UASQuickTabView) { ui->setupUi(this); this->setLayout(ui->gridLayout); QStringList nameList;// = new QStringList(); // nameList.append("Широта:"); // nameList.append("Долгота:"); // nameList.append("Высота:"); // nameList.append("Курс:"); // nameList.append("Крен:"); // nameList.append("Тангаж:"); nameList.append(tr("Latitude:")); nameList.append(tr("Longitude:")); nameList.append(tr("Altitude:")); nameList.append(tr("Roll:")); nameList.append(tr("Pitch:")); nameList.append(tr("Yaw:")); fieldNameList << "M24:GLOBAL_POSITION_INT.lat" << "M24:GLOBAL_POSITION_INT.lon" << "M24:GLOBAL_POSITION_INT.alt" << "M24:ATTITUDE.roll" << "M24:ATTITUDE.pitch" << "M24:ATTITUDE.yaw"; foreach(QString str, fieldNameList){ uasPropertyValueMap.insert(str, 0.0); } QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); ui->tableWidget->setColumnCount(2); ui->tableWidget->setRowCount(nameList.count()); ui->tableWidget->setLineWidth(1); ui->tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->tableWidget->setStyleSheet("gridline-color : gray"); //tableFont = new QFont("Times New Roman", 14, 3); // tableFont.setFamily("Times New Roman"); tableFont.setPixelSize(14); tableFont.setBold(3); for(int i = 0; i < nameList.count(); i++) { /* Add first column that shows lable names.*/ QTableWidgetItem* item = new QTableWidgetItem(); Q_ASSERT(item); if (item) { item->setText(nameList.at(i)); tableNameList.append(item); item->setFont(tableFont); item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable); ui->tableWidget->setItem(i, 0, item); } /* Add column with values.*/ item = new QTableWidgetItem(); Q_ASSERT(item); if (item) { tableValueList.append(item); item->setFont(tableFont); item->setText("0.0"); item->setFlags(item->flags() ^ Qt::ItemIsEditable ^ Qt::ItemIsSelectable); ui->tableWidget->setItem(i, 1, item); } } updateTimer = new QTimer(this); connect(updateTimer,SIGNAL(timeout()),this,SLOT(updateTimerTick())); updateTimer->start(1000); // testTimerValue = true; // testTimer = new QTimer(this); // testTimer->setSingleShot(false); // connect(testTimer,SIGNAL(timeout()),this,SLOT(testTimerExpired())); // testTimer->start(750); } UASQuickTabView::~UASQuickTabView() { delete ui; foreach (QTableWidgetItem* item, tableNameList) { delete item; } foreach (QTableWidgetItem* item, tableValueList) { delete item; } delete updateTimer; } void UASQuickTabView::addSource(MAVLinkDecoder *decoder) { connect(decoder,SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),this,SLOT(valueChanged(int,QString,QString,QVariant,quint64))); } void UASQuickTabView::valueChanged(const int uasId, const QString& name, const QString& unit, const QVariant &variant, const quint64 msec) { Q_UNUSED(uasId); Q_UNUSED(unit); Q_UNUSED(msec); bool ok; double value = variant.toDouble(&ok); QMetaType::Type metaType = static_cast<QMetaType::Type>(variant.type()); if(!ok || metaType == QMetaType::QString || metaType == QMetaType::QByteArray) return; //qDebug()<<name<<" "<<value; // if (!uasPropertyValueMap.contains(name)) // { // if (quickViewSelectDialog) // { // quickViewSelectDialog->addItem(name); // } // } if((name == "M24:GLOBAL_POSITION_INT.lat")||(name == "M24:GLOBAL_POSITION_INT.lon")) uasPropertyValueMap[name] = value/10000000; else if(name == "M24:GLOBAL_POSITION_INT.alt") uasPropertyValueMap[name] = value/1000; else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw")) uasPropertyValueMap[name] = value/M_PI*180; } void UASQuickTabView::updateTimerTick() { for(int i = 0; i < fieldNameList.size(); i++){ //QString str = QString::number(uasPropertyValueMap[fieldNameList.at(i)]); QString str = formText(fieldNameList.at(i), uasPropertyValueMap[fieldNameList.at(i)]); ui->tableWidget->item(i,1)->setText(str); } } //void UASQuickTabView::testTimerExpired(){ // if(testTimerValue == true){ // valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",538893530,0); // valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",275296780,0); // valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",272000,0); // valueChanged(0,"M24:ATTITUDE.roll","unit",0.36814,0); // valueChanged(0,"M24:ATTITUDE.pitch","unit",0.56715,0); // valueChanged(0,"M24:ATTITUDE.yaw","unit",0.24715,0); // testTimerValue = false; // } // else{ // valueChanged(0,"M24:GLOBAL_POSITION_INT.lat","unit",-549993530,0); // valueChanged(0,"M24:GLOBAL_POSITION_INT.lon","unit",-277796780,0); // valueChanged(0,"M24:GLOBAL_POSITION_INT.alt","unit",284000,0); // valueChanged(0,"M24:ATTITUDE.roll","unit",0.35614,0); // valueChanged(0,"M24:ATTITUDE.pitch","unit",0.46815,0); // valueChanged(0,"M24:ATTITUDE.yaw","unit",0.67895,0); // testTimerValue = true; // } //} void UASQuickTabView::setTableGeometry(){ ui->tableWidget->setColumnWidth(0, ((this->width() - 5)/2)); ui->tableWidget->setColumnWidth(1, ((this->width())/2)); for(int i = 0; i < ui->tableWidget->rowCount(); i++) { ui->tableWidget->setRowHeight(i, (this->height() - 2)/6); //qDebug()<<"qgridrowminimumheight: "<<ui->gridLayout->rowMinimumHeight(0); } } QString UASQuickTabView::formText(QString name, double value){ QString str; if(name == "M24:GLOBAL_POSITION_INT.lat"){ if(value >= 0){ str = QString::number(value,'f',5); str += 0x00B0; str += tr(" N"); } else if(value < 0){ value *=-1; str = QString::number(value,'f',5); str += 0x00B0; str += tr(" S"); } } else if(name == "M24:GLOBAL_POSITION_INT.lon"){ if(value >= 0){ str = QString::number(value,'f',5); str += 0x00B0; str += tr(" E"); } else if(value < 0){ value *=-1; str = QString::number(value,'f',5); str += 0x00B0; str += tr(" W"); } } else if(name == "M24:GLOBAL_POSITION_INT.alt"){ str = QString::number(value,'f',1); str +=tr(" m."); } else if((name == "M24:ATTITUDE.roll")||(name == "M24:ATTITUDE.pitch")||(name == "M24:ATTITUDE.yaw")){ str = QString::number(value,'f',2); str += 0x00B0; } return str; } void UASQuickTabView::resizeEvent(QResizeEvent *event){ setTableGeometry(); } <|endoftext|>
<commit_before>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /* 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 HOLDER 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. */ /* */ /**************************************************************************************/ #ifndef AABB_INCLUDE_ONCE #define AABB_INCLUDE_ONCE #include <vlCore/Vector3.hpp> #include <vlCore/Matrix4.hpp> namespace vl { //----------------------------------------------------------------------------- // AABB //----------------------------------------------------------------------------- /** * The AABB class implements an axis-aligned bounding box using vl::Real precision. */ class AABB { public: AABB(); AABB( const vec3& center, Real radius ); AABB( const vec3& pt1, const vec3& pt2, Real displace=0); void setNull() { mMin = 1; mMax = -1; } bool isNull() const { return mMin.x() > mMax.x() || mMin.y() > mMax.y() || mMin.z() > mMax.z(); } bool isPoint() const { return mMin == mMax; } void enlarge(Real displace); void addPoint(const vec3& v, Real radius); bool intersects(const AABB & bb) const; vec3 clip(const vec3& v, bool clipx=true, bool clipy=true, bool clipz=true) const; bool isInside(const vec3& v, bool clipx, bool clipy, bool clipz) const; bool isInside(const vec3& v) const; Real height() const; Real width() const; Real depth() const; AABB operator+(const AABB& aabb) const; const AABB& operator+=(const AABB& other) { *this = *this + other; return *this; } AABB operator+(const vec3& p) { AABB aabb = *this; aabb += p; return aabb; } const AABB& operator+=(const vec3& p) { addPoint(p); return *this; } vec3 center() const; Real area() const { if (isNull()) return 0; else return width()*height()*depth(); } Real longestSideLength() const { Real side = width(); if (height() > side) side = height(); if (depth() > side) side = depth(); return side; } void addPoint(const vec3& v) { if (isNull()) { mMax = v; mMin = v; return; } if ( mMax.x() < v.x() ) mMax.x() = v.x(); if ( mMax.y() < v.y() ) mMax.y() = v.y(); if ( mMax.z() < v.z() ) mMax.z() = v.z(); if ( mMin.x() > v.x() ) mMin.x() = v.x(); if ( mMin.y() > v.y() ) mMin.y() = v.y(); if ( mMin.z() > v.z() ) mMin.z() = v.z(); } void transformed(AABB& aabb, const mat4& mat) const { aabb.setNull(); if ( !isNull() ) { aabb.addPoint( mat * vec3(minCorner().x(), minCorner().y(), minCorner().z()) ); aabb.addPoint( mat * vec3(minCorner().x(), maxCorner().y(), minCorner().z()) ); aabb.addPoint( mat * vec3(maxCorner().x(), maxCorner().y(), minCorner().z()) ); aabb.addPoint( mat * vec3(maxCorner().x(), minCorner().y(), minCorner().z()) ); aabb.addPoint( mat * vec3(minCorner().x(), minCorner().y(), maxCorner().z()) ); aabb.addPoint( mat * vec3(minCorner().x(), maxCorner().y(), maxCorner().z()) ); aabb.addPoint( mat * vec3(maxCorner().x(), maxCorner().y(), maxCorner().z()) ); aabb.addPoint( mat * vec3(maxCorner().x(), minCorner().y(), maxCorner().z()) ); } } AABB transformed(const mat4& mat) const { AABB aabb; transformed(aabb, mat); return aabb; } const vec3& minCorner() const { return mMin; } const vec3& maxCorner() const { return mMax; } void setMinCorner(Real x, Real y, Real z) { mMin = vec3(x,y,z); } void setMinCorner(const vec3& v) { mMin = v; } void setMaxCorner(Real x, Real y, Real z) { mMax = vec3(x,y,z); } void setMaxCorner(const vec3& v) { mMax = v; } Real volume() const { return width() * height() * depth(); } protected: vec3 mMin; vec3 mMax; }; } #endif <commit_msg>AABB class: added missing operator== and operator!=<commit_after>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /* 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 HOLDER 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. */ /* */ /**************************************************************************************/ #ifndef AABB_INCLUDE_ONCE #define AABB_INCLUDE_ONCE #include <vlCore/Vector3.hpp> #include <vlCore/Matrix4.hpp> namespace vl { //----------------------------------------------------------------------------- // AABB //----------------------------------------------------------------------------- /** * The AABB class implements an axis-aligned bounding box using vl::Real precision. */ class AABB { public: AABB(); AABB( const vec3& center, Real radius ); AABB( const vec3& pt1, const vec3& pt2, Real displace=0); void setNull() { mMin = 1; mMax = -1; } bool isNull() const { return mMin.x() > mMax.x() || mMin.y() > mMax.y() || mMin.z() > mMax.z(); } bool isPoint() const { return mMin == mMax; } void enlarge(Real displace); void addPoint(const vec3& v, Real radius); bool intersects(const AABB & bb) const; vec3 clip(const vec3& v, bool clipx=true, bool clipy=true, bool clipz=true) const; bool isInside(const vec3& v, bool clipx, bool clipy, bool clipz) const; bool isInside(const vec3& v) const; Real height() const; Real width() const; Real depth() const; bool operator==(const AABB& aabb) const { return mMin == aabb.mMin && mMax == aabb.mMax; } bool operator!=(const AABB& aabb) const { return !operator==(aabb); } AABB operator+(const AABB& aabb) const; const AABB& operator+=(const AABB& other) { *this = *this + other; return *this; } AABB operator+(const vec3& p) { AABB aabb = *this; aabb += p; return aabb; } const AABB& operator+=(const vec3& p) { addPoint(p); return *this; } vec3 center() const; Real area() const { if (isNull()) return 0; else return width()*height()*depth(); } Real longestSideLength() const { Real side = width(); if (height() > side) side = height(); if (depth() > side) side = depth(); return side; } void addPoint(const vec3& v) { if (isNull()) { mMax = v; mMin = v; return; } if ( mMax.x() < v.x() ) mMax.x() = v.x(); if ( mMax.y() < v.y() ) mMax.y() = v.y(); if ( mMax.z() < v.z() ) mMax.z() = v.z(); if ( mMin.x() > v.x() ) mMin.x() = v.x(); if ( mMin.y() > v.y() ) mMin.y() = v.y(); if ( mMin.z() > v.z() ) mMin.z() = v.z(); } void transformed(AABB& aabb, const mat4& mat) const { aabb.setNull(); if ( !isNull() ) { aabb.addPoint( mat * vec3(minCorner().x(), minCorner().y(), minCorner().z()) ); aabb.addPoint( mat * vec3(minCorner().x(), maxCorner().y(), minCorner().z()) ); aabb.addPoint( mat * vec3(maxCorner().x(), maxCorner().y(), minCorner().z()) ); aabb.addPoint( mat * vec3(maxCorner().x(), minCorner().y(), minCorner().z()) ); aabb.addPoint( mat * vec3(minCorner().x(), minCorner().y(), maxCorner().z()) ); aabb.addPoint( mat * vec3(minCorner().x(), maxCorner().y(), maxCorner().z()) ); aabb.addPoint( mat * vec3(maxCorner().x(), maxCorner().y(), maxCorner().z()) ); aabb.addPoint( mat * vec3(maxCorner().x(), minCorner().y(), maxCorner().z()) ); } } AABB transformed(const mat4& mat) const { AABB aabb; transformed(aabb, mat); return aabb; } const vec3& minCorner() const { return mMin; } const vec3& maxCorner() const { return mMax; } void setMinCorner(Real x, Real y, Real z) { mMin = vec3(x,y,z); } void setMinCorner(const vec3& v) { mMin = v; } void setMaxCorner(Real x, Real y, Real z) { mMax = vec3(x,y,z); } void setMaxCorner(const vec3& v) { mMax = v; } Real volume() const { return width() * height() * depth(); } protected: vec3 mMin; vec3 mMax; }; } #endif <|endoftext|>
<commit_before>//#include "./stdafx.h" #include "FileContainer.h" #include "DocxFormat/Rels/File.h" #include "FileFactory.h" #include "DocxFormat/ContentTypes/File.h" #include "DocxFormat/FileType.h" #include "DocxFormat/FileTypes.h" #include "DocxFormat/External/Hyperlink.h" #include "WrapperFile.h" namespace PPTX { void FileContainer::read(const OOX::CPath& filename) { //not implement FileContainer.read } void FileContainer::read(const PPTX::Rels::File& rels, const OOX::CPath& path) { //not implement FileContainer.read } void FileContainer::read(const OOX::CPath& filename, FileMap& map, IPPTXEvent* Event) { PPTX::Rels::File rels(filename); OOX::CPath path = filename.GetDirectory(); read(rels, path, map, Event); } void FileContainer::read(const PPTX::Rels::File& rels, const OOX::CPath& path, FileMap& map, IPPTXEvent* Event) { bool bIsSlide = false; PPTX::File* pSrcFile = dynamic_cast<PPTX::File*>(this); if (NULL != pSrcFile) bIsSlide = (pSrcFile->type() == PPTX::FileTypes::Slide) ? true : false; size_t nCount = rels.Relations.m_items.size(); for (size_t i = 0; i < nCount; ++i) { const PPTX::Rels::RelationShip* pRelation = &(rels.Relations.m_items[i]); OOX::CPath normPath = path / pRelation->target(); CAtlMap<CString, smart_ptr<PPTX::File>>::CPair* pPair = map.find(normPath); if (bIsSlide && (pRelation->type() == PPTX::FileTypes::Slide)) { long percent = Event->GetPercent(); smart_ptr<PPTX::File> file = smart_ptr<PPTX::File>(new PPTX::HyperLink(pRelation->target())); bool res = Event->Progress(0, percent + m_lPercent); if (res) { m_bCancelled = true; break; } add(pRelation->rId(), file); } else { if (NULL != pPair) { add(pRelation->rId(), pPair->m_value); } else { long percent = Event->GetPercent(); smart_ptr<PPTX::File> file = PPTX::FileFactory::CreateFilePPTX(path, *pRelation, map); bool res = Event->Progress(0, percent + m_lPercent); if (res) { m_bCancelled = true; break; } map.add(normPath, file); add(pRelation->rId(), file); smart_ptr<FileContainer> pContainer = file.smart_dynamic_cast<FileContainer>(); if (pContainer.IsInit()) { pContainer->m_lPercent = m_lPercent; Event->AddPercent(m_lPercent); pContainer->read(normPath, map, Event); m_bCancelled = pContainer->m_bCancelled; } } } } } void FileContainer::write(const OOX::CPath& filename, const OOX::CPath& directory, PPTX::ContentTypes::File& content) const { PPTX::Rels::File rels; OOX::CPath current = filename.GetDirectory(); write(rels, current, directory, content); rels.write(filename); } void FileContainer::write(PPTX::Rels::File& rels, const OOX::CPath& curdir, const OOX::CPath& directory, PPTX::ContentTypes::File& content) const { CAtlMap<CString, size_t> namepair; POSITION pos = m_container.GetStartPosition(); while (NULL != pos) { const CAtlMap<CString, smart_ptr<PPTX::File>>::CPair* pPair = m_container.GetNext(pos); smart_ptr<PPTX::File> pFile = pPair->m_value; smart_ptr<PPTX::External> pExt = pFile.smart_dynamic_cast<PPTX::External>(); if (!pExt.IsInit()) { smart_ptr<PPTX::WrapperFile> file = pFile.smart_dynamic_cast<PPTX::WrapperFile>(); if (file.IsInit()) { if (file->GetWrittenStatus() == false) { OOX::CPath defdir = pFile->DefaultDirectory(); OOX::CPath name = pFile->DefaultFileName(); //name = name + max_name_index(curdir, name.string()); OOX::CSystemUtility::CreateDirectories(directory / defdir); pFile->write(directory / defdir / name, directory, content); rels.registration(pPair->m_key, pFile->type(), defdir / name); } else { OOX::CPath defdir = pFile->DefaultDirectory(); OOX::CPath name = file->GetWrittenFileName(); rels.registration(pPair->m_key, pFile->type(), defdir / name); } } else { OOX::CPath defdir = pFile->DefaultDirectory(); OOX::CPath name = pFile->DefaultFileName(); OOX::CSystemUtility::CreateDirectories(directory / defdir); pFile->write(directory / defdir / name, directory, content); rels.registration(pPair->m_key, pFile->type(), defdir / name); } } else { rels.registration(pPair->m_key, pExt); } } } void FileContainer::WrittenSetFalse() { POSITION pos = m_container.GetStartPosition(); while (NULL != pos) { smart_ptr<PPTX::File> pFile = m_container.GetNextValue(pos); smart_ptr<PPTX::WrapperFile> pWrapFile = pFile.smart_dynamic_cast<PPTX::WrapperFile>(); smart_ptr<PPTX::FileContainer> pWrapCont = pFile.smart_dynamic_cast<PPTX::FileContainer>(); if (pWrapFile.is_init() && !pWrapFile->GetWrittenStatus()) { pWrapFile->WrittenSetFalse(); if (pWrapCont.is_init()) { pWrapCont->WrittenSetFalse(); } } } } void CCommonRels::_read(const PPTX::Rels::File& rels, const OOX::CPath& path) { size_t nCount = rels.Relations.m_items.size(); for (size_t i = 0; i < nCount; ++i) { const PPTX::Rels::RelationShip* pRelation = &(rels.Relations.m_items[i]); smart_ptr<PPTX::File> _file = PPTX::FileFactory::CreateFilePPTX_OnlyMedia(path, *pRelation); add(pRelation->rId(), _file); } } void CCommonRels::_read(const OOX::CPath& filename) { PPTX::Rels::File rels(filename); OOX::CPath path = filename.GetDirectory(); _read(rels, path); } } // namespace PPTX<commit_msg>CAtlMap -> std::map<commit_after>//#include "./stdafx.h" #include "FileContainer.h" #include "DocxFormat/Rels/File.h" #include "FileFactory.h" #include "DocxFormat/ContentTypes/File.h" #include "DocxFormat/FileType.h" #include "DocxFormat/FileTypes.h" #include "DocxFormat/External/Hyperlink.h" #include "WrapperFile.h" #include <map> namespace PPTX { void FileContainer::read(const OOX::CPath& filename) { //not implement FileContainer.read } void FileContainer::read(const PPTX::Rels::File& rels, const OOX::CPath& path) { //not implement FileContainer.read } void FileContainer::read(const OOX::CPath& filename, FileMap& map, IPPTXEvent* Event) { PPTX::Rels::File rels(filename); OOX::CPath path = filename.GetDirectory(); read(rels, path, map, Event); } void FileContainer::read(const PPTX::Rels::File& rels, const OOX::CPath& path, FileMap& map, IPPTXEvent* Event) { bool bIsSlide = false; PPTX::File* pSrcFile = dynamic_cast<PPTX::File*>(this); if (NULL != pSrcFile) bIsSlide = (pSrcFile->type() == PPTX::FileTypes::Slide) ? true : false; size_t nCount = rels.Relations.m_items.size(); for (size_t i = 0; i < nCount; ++i) { const PPTX::Rels::RelationShip* pRelation = &(rels.Relations.m_items[i]); OOX::CPath normPath = path / pRelation->target(); CAtlMap<CString, smart_ptr<PPTX::File>>::CPair* pPair = map.find(normPath); if (bIsSlide && (pRelation->type() == PPTX::FileTypes::Slide)) { long percent = Event->GetPercent(); smart_ptr<PPTX::File> file = smart_ptr<PPTX::File>(new PPTX::HyperLink(pRelation->target())); bool res = Event->Progress(0, percent + m_lPercent); if (res) { m_bCancelled = true; break; } add(pRelation->rId(), file); } else { if (NULL != pPair) { add(pRelation->rId(), pPair->m_value); } else { long percent = Event->GetPercent(); smart_ptr<PPTX::File> file = PPTX::FileFactory::CreateFilePPTX(path, *pRelation, map); bool res = Event->Progress(0, percent + m_lPercent); if (res) { m_bCancelled = true; break; } map.add(normPath, file); add(pRelation->rId(), file); smart_ptr<FileContainer> pContainer = file.smart_dynamic_cast<FileContainer>(); if (pContainer.IsInit()) { pContainer->m_lPercent = m_lPercent; Event->AddPercent(m_lPercent); pContainer->read(normPath, map, Event); m_bCancelled = pContainer->m_bCancelled; } } } } } void FileContainer::write(const OOX::CPath& filename, const OOX::CPath& directory, PPTX::ContentTypes::File& content) const { PPTX::Rels::File rels; OOX::CPath current = filename.GetDirectory(); write(rels, current, directory, content); rels.write(filename); } void FileContainer::write(PPTX::Rels::File& rels, const OOX::CPath& curdir, const OOX::CPath& directory, PPTX::ContentTypes::File& content) const { std::map<CString, size_t> mNamePair; for (std::map<CString, smart_ptr<PPTX::File>>::const_iterator pPair = m_container.begin(); pPair != m_container.end(); ++pPair) { smart_ptr<PPTX::File> pFile = pPair->second; smart_ptr<PPTX::External> pExt = pFile.smart_dynamic_cast<PPTX::External>(); if ( !pExt.IsInit() ) { smart_ptr<PPTX::WrapperFile> file = pFile.smart_dynamic_cast<PPTX::WrapperFile>(); if (file.IsInit()) { if (file->GetWrittenStatus() == false) { OOX::CPath defdir = pFile->DefaultDirectory(); OOX::CPath name = pFile->DefaultFileName(); //name = name + max_name_index(curdir, name.string()); OOX::CSystemUtility::CreateDirectories(directory / defdir); pFile->write(directory / defdir / name, directory, content); rels.registration(pPair->first, pFile->type(), defdir / name); } else { OOX::CPath defdir = pFile->DefaultDirectory(); OOX::CPath name = file->GetWrittenFileName(); rels.registration(pPair->first, pFile->type(), defdir / name); } } else { OOX::CPath defdir = pFile->DefaultDirectory(); OOX::CPath name = pFile->DefaultFileName(); OOX::CSystemUtility::CreateDirectories(directory / defdir); pFile->write(directory / defdir / name, directory, content); rels.registration(pPair->first, pFile->type(), defdir / name); } } else { rels.registration(pPair->first, pExt); } } } void FileContainer::WrittenSetFalse() { for (std::map<CString, smart_ptr<PPTX::File>>::const_iterator pPair = m_container.begin(); pPair != m_container.end(); ++pPair) { smart_ptr<PPTX::File> pFile = pPair->second; smart_ptr<PPTX::WrapperFile> pWrapFile = pFile.smart_dynamic_cast<PPTX::WrapperFile>(); smart_ptr<PPTX::FileContainer> pWrapCont = pFile.smart_dynamic_cast<PPTX::FileContainer>(); if (pWrapFile.is_init() && !pWrapFile->GetWrittenStatus()) { pWrapFile->WrittenSetFalse(); if (pWrapCont.is_init()) { pWrapCont->WrittenSetFalse(); } } } } void CCommonRels::_read(const PPTX::Rels::File& rels, const OOX::CPath& path) { size_t nCount = rels.Relations.m_items.size(); for (size_t i = 0; i < nCount; ++i) { const PPTX::Rels::RelationShip* pRelation = &(rels.Relations.m_items[i]); smart_ptr<PPTX::File> _file = PPTX::FileFactory::CreateFilePPTX_OnlyMedia(path, *pRelation); add(pRelation->rId(), _file); } } void CCommonRels::_read(const OOX::CPath& filename) { PPTX::Rels::File rels(filename); OOX::CPath path = filename.GetDirectory(); _read(rels, path); } } // namespace PPTX<|endoftext|>
<commit_before>// Copyright 2017 Jacek Wozniak <[email protected]> #include "./k81x.h" #include <unistd.h> #include <cstring> #include <iostream> using std::cerr; using std::cout; using std::endl; void usage() { cout << "Usage: sudo k81x-fkeys [-d device_path] [-v] on|off" << endl; cout << "Controls the functions of Logitech K810/K811 Keyboard F-keys" << endl << endl; cout << "As seen above, this tool needs root privileges to operate. Options:" << endl; cout << "\t-d device_path\tDevice path of the Logitech keyboard, usually" << endl << "\t\t\t/dev/hidraw0. Autodetecion is peformed if this" << endl << "\t\t\tparameter is omitted." << endl; cout << "\t-v\t\tVerbose mode." << endl; cout << "\ton|off\t\t\"on\" causes the F-keys to act like standard" << endl << "\t\t\tF1-F12 keys, \"off\" enables the enhanced functions." << endl; } int main(int argc, char **argv) { bool verbose = false, switch_on; const char *device_path = NULL; // Fetch the command line arguments. int opt; while ((opt = getopt(argc, argv, "d:v")) != -1) { switch (opt) { case 'd': device_path = optarg; break; case 'v': verbose = true; break; } } if (optind >= argc) { // No on/off argument. usage(); return 1; } if (!strcmp("on", argv[optind])) { switch_on = true; } else if (!strcmp("off", argv[optind])) { switch_on = false; } else { cerr << "Invalid switch value, should be either \"on\" or \"off\"." << endl; usage(); return 1; } // Check the privileges. if (geteuid() != 0) { cerr << "Warning: Program not running as root. It will most likely fail." << endl; } // Initialize the device. K81x *k81x = NULL; if (device_path == NULL) { k81x = K81x::FromAutoFind(verbose); if (NULL == k81x) { cerr << "Error while looking for a Logitech K810/K811 keyboard." << endl; } } else { k81x = K81x::FromDevicePath(device_path, verbose); if (NULL == k81x) { cerr << "Device " << device_path << " cannot be recognized as a supported Logitech K810/K811 keyboard." << endl; } } int result = 0; if (k81x != NULL) { // Switch the Kn keys mode. if (!k81x->SetFnKeysMode(switch_on)) { cerr << "Error while setting the F-keys mode." << endl; result = 1; } delete k81x; } else { result = 1; } if (result && !verbose) { cerr << "Try running with -v parameter to get more details." << endl; } return result; } <commit_msg>Silent mode<commit_after>// Copyright 2017 Jacek Wozniak <[email protected]> #include "./k81x.h" #include <unistd.h> #include <cstring> #include <iostream> using std::cerr; using std::cout; using std::endl; void usage() { cout << "Usage: sudo k81x-fkeys [-d device_path] [-v] on|off" << endl; cout << "Controls the functions of Logitech K810/K811 Keyboard F-keys" << endl << endl; cout << "As seen above, this tool needs root privileges to operate. Options:" << endl; cout << "\t-d device_path\tDevice path of the Logitech keyboard, usually" << endl << "\t\t\t/dev/hidraw0. Autodetecion is peformed if this" << endl << "\t\t\tparameter is omitted." << endl; cout << "\t-v\t\tVerbose mode." << endl; cout << "\ton|off\t\t\"on\" causes the F-keys to act like standard" << endl << "\t\t\tF1-F12 keys, \"off\" enables the enhanced functions." << endl; } int main(int argc, char **argv) { bool verbose = false, switch_on, silent = false; int error_return = 1; const char *device_path = NULL; // Fetch the command line arguments. int opt; while ((opt = getopt(argc, argv, "d:vs")) != -1) { switch (opt) { case 'd': device_path = optarg; break; case 'v': verbose = true; break; case 's': silent = true; error_return = 0; break; } } if (optind >= argc) { // No on/off argument. usage(); return error_return; } if (!strcmp("on", argv[optind])) { switch_on = true; } else if (!strcmp("off", argv[optind])) { switch_on = false; } else { cerr << "Invalid switch value, should be either \"on\" or \"off\"." << endl; usage(); return error_return; } // Check the privileges. if (geteuid() != 0 && !silent) { cerr << "Warning: Program not running as root. It will most likely fail." << endl; } // Initialize the device. K81x *k81x = NULL; if (device_path == NULL) { k81x = K81x::FromAutoFind(verbose); if (NULL == k81x && !silent) { cerr << "Error while looking for a Logitech K810/K811 keyboard." << endl; } } else { k81x = K81x::FromDevicePath(device_path, verbose); if (NULL == k81x && !silent) { cerr << "Device " << device_path << " cannot be recognized as a supported Logitech K810/K811 keyboard." << endl; } } int result = 0; if (k81x != NULL) { // Switch the Kn keys mode. if (!k81x->SetFnKeysMode(switch_on) && !silent) { cerr << "Error while setting the F-keys mode." << endl; result = error_return; } delete k81x; } else { result = error_return; } if (result && !verbose && !silent) { cerr << "Try running with -v parameter to get more details." << endl; } return result; } <|endoftext|>
<commit_before>/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* enchant * Copyright (C) 2003 Dom Lachowicz, Raphael Finkel * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * In addition, as a special exception, Dom Lachowicz * gives permission to link the code of this program with * the non-LGPL Spelling Provider libraries (eg: a MSFT Office * spell checker backend) and distribute linked combinations including * the two. You must obey the GNU General Public License in all * respects for all of the code used other than said providers. If you modify * this file, you may extend this exception to your version of the * file, but you are not obligated to do so. If you do not wish to * do so, delete this exception statement from your version. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <glib.h> // #include <sys/file.h> // only needed if we use flock() below #include "enchant.h" #include "enchant-provider.h" #include <uspell/utf8convert.h> #include <uspell/uniprops.h> #include <uspell/uspell.h> static const size_t MAXALTERNATIVE = 20; // we won't return more than this number of suggestions typedef struct { char *personalName; // name of file containing personal dictionary uSpell *manager; // my uSpell instance } uspellData; static int uspell_dict_check (EnchantDict * me, const char *const word, size_t len) { uSpell *manager; wide_t *curBuf, *otherBuf, *tmpBuf; int length; manager = reinterpret_cast<uspellData *>(me->user_data)->manager; curBuf = reinterpret_cast<wide_t *>(calloc(len+1, sizeof(wide_t))); #ifdef DEBUG fprintf(stdout, "Checking [%s]\n", word); #endif length = utf8_wide(curBuf, reinterpret_cast<const utf8_t *>(word), len+1); if (manager->isSpelledRight(curBuf, length)) { free(curBuf); return 0; // correct the first time } otherBuf = reinterpret_cast<wide_t *>(calloc(len+1, sizeof(wide_t))); if (manager->theFlags & uSpell::upperLower) { toUpper(otherBuf, curBuf, length); if (manager->isSpelledRight(otherBuf, length)) { manager->acceptWord(reinterpret_cast<const utf8_t *>(word)); free(curBuf); free(otherBuf); return 0; // correct if converted to all upper case } tmpBuf = curBuf; curBuf = otherBuf; otherBuf = tmpBuf; } if (manager->theFlags & uSpell::hasComposition) { unPrecompose(otherBuf, &length, curBuf, length); if (manager->isSpelledRight(otherBuf, length)) { manager->acceptWord(reinterpret_cast<const utf8_t *>(word)); free(curBuf); free(otherBuf); return 0; // correct if precomposed characters expanded, all upper } tmpBuf = curBuf; curBuf = otherBuf; otherBuf = tmpBuf; } if (manager->theFlags & uSpell::hasCompounds) { if (manager->isSpelledRightMultiple(curBuf, length)) { manager->acceptWord(reinterpret_cast<const utf8_t *>(word)); free(curBuf); free(otherBuf); return 0; // correct as two words. Not right for all languages. } } free(curBuf); free(otherBuf); return 1; } static char ** uspell_dict_suggest (EnchantDict * me, const char *const word, size_t len, size_t * out_n_suggs) { uSpell *manager; char **sugg_arr = NULL; const utf8_t *sugg; wide_t *curBuf; int length, i; utf8_t **list; manager = reinterpret_cast<uspellData *>(me->user_data)->manager; list = reinterpret_cast<utf8_t **>( calloc(sizeof(char *), MAXALTERNATIVE)); curBuf = reinterpret_cast<wide_t *>(calloc(len+1, sizeof(wide_t))); length = utf8_wide(curBuf, reinterpret_cast<const utf8_t *>(word), len+1); *out_n_suggs = manager->showAlternatives(curBuf, length, list, MAXALTERNATIVE); if (*out_n_suggs) { sugg_arr = g_new0 (char *, *out_n_suggs + 1); for (i = 0; i < *out_n_suggs; i++) { sugg = list[i]; if (sugg) sugg_arr[i] = g_strdup (reinterpret_cast<const gchar *>(sugg)); free(list[i]); } } free(list); free(curBuf); return sugg_arr; } static void uspell_dict_add_to_personal (EnchantDict * me, const char *const word, size_t len) { uSpell *manager; FILE *personalFile; manager = reinterpret_cast<uspellData *>(me->user_data)->manager; manager->acceptWord(reinterpret_cast<const utf8_t *>(word)); if (!reinterpret_cast<uspellData *>(me->user_data)->personalName) return; // no personal file personalFile = fopen(reinterpret_cast<uspellData *>(me->user_data)->personalName, "a"); if (personalFile) { #if 0 // if we ever want to close the race condition, port flock to win32 flock(fileno(personalFile), LOCK_EX); fseek(personalFile, 0, SEEK_END); // in case someone else intervened #endif fprintf(personalFile, "%s\n", word); fclose(personalFile); } } static void uspell_dict_add_to_session (EnchantDict * me, const char *const word, size_t len) { uSpell *manager; manager = reinterpret_cast<uspellData *>(me->user_data)->manager; manager->acceptWord(reinterpret_cast<const utf8_t *>(word)); } static void uspell_dict_free_suggestions (EnchantDict * me, char **str_list) { g_strfreev (str_list); } typedef struct { char * language_tag; char * corresponding_uspell_file_name; int language_flags; } Mapping; static const Mapping mapping [] = { {"he", "hebrew", 0}, {"he_IL", "hebrew", 0}, {"yi", "yiddish", uSpell::hasCompounds | uSpell::hasComposition} }; static const size_t n_mappings = (sizeof(mapping)/sizeof(mapping[0])); static uspellData * uspell_request_dict (const char * base, const char * mapping, const int flags) { char *fileName, *transName, *filePart, *transPart, *personalPart, *home_dir, * personalName; uspellData * data; uSpell *manager; if (!base) return NULL; filePart = g_strconcat(mapping, ".uspell.dat", NULL); transPart = g_strconcat(mapping, ".uspell.trans", NULL); fileName = g_build_filename (base, filePart, NULL); transName = g_build_filename (base, transPart, NULL); g_free(filePart); g_free(transPart); try { manager = new uSpell(fileName, transName, flags); home_dir = enchant_get_user_home_dir (); if (home_dir) { char * private_dir = g_build_filename (home_dir, ".enchant", "uspell", NULL); personalPart = g_strconcat(mapping, ".uspell.personal", NULL); personalName = g_build_filename (private_dir, personalPart, NULL); g_free(personalPart); (void) manager->assimilateFile(personalName); } else { personalName = NULL; } } catch (...) { manager = NULL; } g_free (fileName); g_free (transName); data = g_new0(uspellData, 1); data->manager = manager; data->personalName = personalName; return data; } /* in preparation for using win32 registry keys, if necessary */ static char * uspell_checker_get_prefix (void) { #ifdef ENCHANT_USPELL_DICT_DIR return g_strdup (ENCHANT_USPELL_DICT_DIR); #else return NULL; #endif } static uspellData * uspell_request_manager (const char * private_dir, size_t mapIndex) { char * uspell_prefix; uspellData * manager = NULL; manager = uspell_request_dict (private_dir, mapping[mapIndex].corresponding_uspell_file_name, mapping[mapIndex].language_flags); if (!manager) { uspell_prefix = uspell_checker_get_prefix (); if (uspell_prefix) { manager = uspell_request_dict (uspell_prefix, mapping[mapIndex].corresponding_uspell_file_name, mapping[mapIndex].language_flags); g_free (uspell_prefix); } } return manager; } static EnchantDict * uspell_provider_request_dict (EnchantProvider * me, const char *const tag) { EnchantDict *dict = NULL; uspellData *manager = NULL; int mapIndex; char * private_dir = NULL, * home_dir; home_dir = enchant_get_user_home_dir (); if (home_dir) { private_dir = g_build_filename (home_dir, ".enchant", "uspell", NULL); g_free (home_dir); } for (mapIndex = 0; mapIndex < n_mappings; mapIndex++) { if (!strcmp(tag, mapping[mapIndex].language_tag)) break; } if (mapIndex < n_mappings) { manager = uspell_request_manager (private_dir, mapIndex); } if (!manager) { // try shortened form: he_IL => he std::string shortened_dict (tag); size_t uscore_pos; if ((uscore_pos = shortened_dict.rfind ('_')) != ((size_t)-1)) { shortened_dict = shortened_dict.substr(0, uscore_pos); for (mapIndex = 0; mapIndex < n_mappings; mapIndex++) { if (!strcmp(shortened_dict.c_str(), mapping[mapIndex].language_tag)) break; } if (mapIndex < n_mappings) { manager = uspell_request_manager (private_dir, mapIndex); } } } g_free (private_dir); if (!manager) return NULL; dict = g_new0 (EnchantDict, 1); dict->user_data = manager; dict->check = uspell_dict_check; dict->suggest = uspell_dict_suggest; dict->add_to_personal = uspell_dict_add_to_personal; dict->add_to_session = uspell_dict_add_to_session; dict->store_replacement = 0; dict->free_suggestions = uspell_dict_free_suggestions; return dict; } EnchantDictStatus uspell_provider_dictionary_status(struct str_enchant_provider * me, const char *const tag) { // TODO: a g_file_exists check on the dictionary associated with the tag g_warning ("uspell_provider_dictionary_status stub - unimplemented\n"); return(EDS_UNKNOWN); } static void uspell_provider_dispose_dict (EnchantProvider * me, EnchantDict * dict) { uSpell *manager; uspellData *myUspellData = reinterpret_cast<uspellData *>(dict->user_data); delete myUspellData->manager; if (myUspellData->personalName) g_free (myUspellData->personalName); g_free (dict->user_data); g_free (dict); } static void uspell_provider_dispose (EnchantProvider * me) { g_free (me); } static char * uspell_provider_identify (EnchantProvider * me) { return "uspell"; } static char * uspell_provider_describe (EnchantProvider * me) { return "Uspell Provider"; } extern "C" { ENCHANT_MODULE_EXPORT (EnchantProvider *) init_enchant_provider (void) { EnchantProvider *provider; provider = g_new0 (EnchantProvider, 1); provider->dispose = uspell_provider_dispose; provider->request_dict = uspell_provider_request_dict; provider->dispose_dict = uspell_provider_dispose_dict; provider->dictionary_status = uspell_provider_dictionary_status; provider->identify = uspell_provider_identify; provider->describe = uspell_provider_describe; return provider; } } <commit_msg>uspell now honors the size arguments<commit_after>/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* enchant * Copyright (C) 2003 Dom Lachowicz, Raphael Finkel * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * In addition, as a special exception, Dom Lachowicz * gives permission to link the code of this program with * the non-LGPL Spelling Provider libraries (eg: a MSFT Office * spell checker backend) and distribute linked combinations including * the two. You must obey the GNU General Public License in all * respects for all of the code used other than said providers. If you modify * this file, you may extend this exception to your version of the * file, but you are not obligated to do so. If you do not wish to * do so, delete this exception statement from your version. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <glib.h> // #include <sys/file.h> // only needed if we use flock() below #include "enchant.h" #include "enchant-provider.h" #include <uspell/utf8convert.h> #include <uspell/uniprops.h> #include <uspell/uspell.h> static const size_t MAXALTERNATIVE = 20; // we won't return more than this number of suggestions static const size_t MAXCHARS = 100; // maximum number of bytes of utf8 or chars of UCS4 in a word typedef struct { char *personalName; // name of file containing personal dictionary uSpell *manager; // my uSpell instance } uspellData; static int uspell_dict_check (EnchantDict * me, const char *const word, size_t len) { uSpell *manager; wide_t buf1[MAXCHARS], buf2[MAXCHARS], *curBuf, *otherBuf, *tmpBuf; utf8_t myWord[MAXCHARS]; int length; if (len >= MAXCHARS) return 1; // too long; can't be right memcpy(reinterpret_cast<char *>(myWord), word, len); myWord[len] = 0; curBuf = buf1; otherBuf = buf2; manager = reinterpret_cast<uspellData *>(me->user_data)->manager; #ifdef DEBUG fprintf(stdout, "Checking [%s]\n", word); #endif length = utf8_wide(curBuf, myWord, MAXCHARS); if (manager->isSpelledRight(curBuf, length)) { return 0; // correct the first time } if (manager->theFlags & uSpell::upperLower) { toUpper(otherBuf, curBuf, length); if (manager->isSpelledRight(otherBuf, length)) { manager->acceptWord(myWord); return 0; // correct if converted to all upper case } tmpBuf = curBuf; curBuf = otherBuf; otherBuf = tmpBuf; } if (manager->theFlags & uSpell::hasComposition) { unPrecompose(otherBuf, &length, curBuf, length); if (manager->isSpelledRight(otherBuf, length)) { manager->acceptWord(myWord); return 0; // correct if precomposed characters expanded, all upper } tmpBuf = curBuf; curBuf = otherBuf; otherBuf = tmpBuf; } if (manager->theFlags & uSpell::hasCompounds) { if (manager->isSpelledRightMultiple(curBuf, length)) { manager->acceptWord(myWord); return 0; // correct as two words. Not right for all languages. } } return 1; } static char ** uspell_dict_suggest (EnchantDict * me, const char *const word, size_t len, size_t * out_n_suggs) { uSpell *manager; utf8_t myWord[MAXCHARS]; char **sugg_arr = NULL; const utf8_t *sugg; wide_t buf[MAXCHARS]; int length, i; utf8_t **list; if (len >= MAXCHARS) // no suggestions; the word is outlandish return g_new0 (char *, 1); memcpy(reinterpret_cast<char *>(myWord), word, len); myWord[len] = 0; manager = reinterpret_cast<uspellData *>(me->user_data)->manager; list = reinterpret_cast<utf8_t **>( calloc(sizeof(char *), MAXALTERNATIVE)); length = utf8_wide(buf, myWord, MAXCHARS); *out_n_suggs = manager->showAlternatives(buf, length, list, MAXALTERNATIVE); if (*out_n_suggs) { sugg_arr = g_new0 (char *, *out_n_suggs + 1); for (i = 0; i < *out_n_suggs; i++) { sugg = list[i]; if (sugg) sugg_arr[i] = g_strdup (reinterpret_cast<const gchar *>(sugg)); free(list[i]); } } free(list); return sugg_arr; } static void uspell_dict_add_to_personal (EnchantDict * me, const char *const word, size_t len) { uSpell *manager; FILE *personalFile; utf8_t myWord[MAXCHARS]; if (len >= MAXCHARS) return; // too long; can't be right memcpy(reinterpret_cast<char *>(myWord), word, len); myWord[len] = 0; manager = reinterpret_cast<uspellData *>(me->user_data)->manager; manager->acceptWord(myWord); if (!reinterpret_cast<uspellData *>(me->user_data)->personalName) return; // no personal file personalFile = fopen(reinterpret_cast<uspellData *>(me->user_data)->personalName, "a"); if (personalFile) { #if 0 // if we ever want to close the race condition, port flock to win32 flock(fileno(personalFile), LOCK_EX); fseek(personalFile, 0, SEEK_END); // in case someone else intervened #endif fprintf(personalFile, "%s\n", myWord); fclose(personalFile); } } static void uspell_dict_add_to_session (EnchantDict * me, const char *const word, size_t len) { uSpell *manager; manager = reinterpret_cast<uspellData *>(me->user_data)->manager; manager->acceptWord(reinterpret_cast<const utf8_t *>(word)); } static void uspell_dict_free_suggestions (EnchantDict * me, char **str_list) { g_strfreev (str_list); } typedef struct { char * language_tag; char * corresponding_uspell_file_name; int language_flags; } Mapping; static const Mapping mapping [] = { {"he", "hebrew", 0}, {"he_IL", "hebrew", 0}, {"yi", "yiddish", uSpell::hasCompounds | uSpell::hasComposition} }; static const size_t n_mappings = (sizeof(mapping)/sizeof(mapping[0])); static uspellData * uspell_request_dict (const char * base, const char * mapping, const int flags) { char *fileName, *transName, *filePart, *transPart, *personalPart, *home_dir, * personalName; uspellData * data; uSpell *manager; if (!base) return NULL; filePart = g_strconcat(mapping, ".uspell.dat", NULL); transPart = g_strconcat(mapping, ".uspell.trans", NULL); fileName = g_build_filename (base, filePart, NULL); transName = g_build_filename (base, transPart, NULL); g_free(filePart); g_free(transPart); try { manager = new uSpell(fileName, transName, flags); home_dir = enchant_get_user_home_dir (); if (home_dir) { char * private_dir = g_build_filename (home_dir, ".enchant", "uspell", NULL); personalPart = g_strconcat(mapping, ".uspell.personal", NULL); personalName = g_build_filename (private_dir, personalPart, NULL); g_free(personalPart); (void) manager->assimilateFile(personalName); } else { personalName = NULL; } } catch (...) { manager = NULL; } g_free (fileName); g_free (transName); data = g_new0(uspellData, 1); data->manager = manager; data->personalName = personalName; return data; } /* in preparation for using win32 registry keys, if necessary */ static char * uspell_checker_get_prefix (void) { #ifdef ENCHANT_USPELL_DICT_DIR return g_strdup (ENCHANT_USPELL_DICT_DIR); #else return NULL; #endif } static uspellData * uspell_request_manager (const char * private_dir, size_t mapIndex) { char * uspell_prefix; uspellData * manager = NULL; manager = uspell_request_dict (private_dir, mapping[mapIndex].corresponding_uspell_file_name, mapping[mapIndex].language_flags); if (!manager) { uspell_prefix = uspell_checker_get_prefix (); if (uspell_prefix) { manager = uspell_request_dict (uspell_prefix, mapping[mapIndex].corresponding_uspell_file_name, mapping[mapIndex].language_flags); g_free (uspell_prefix); } } return manager; } static EnchantDict * uspell_provider_request_dict (EnchantProvider * me, const char *const tag) { EnchantDict *dict = NULL; uspellData *manager = NULL; int mapIndex; char * private_dir = NULL, * home_dir; home_dir = enchant_get_user_home_dir (); if (home_dir) { private_dir = g_build_filename (home_dir, ".enchant", "uspell", NULL); g_free (home_dir); } for (mapIndex = 0; mapIndex < n_mappings; mapIndex++) { if (!strcmp(tag, mapping[mapIndex].language_tag)) break; } if (mapIndex < n_mappings) { manager = uspell_request_manager (private_dir, mapIndex); } if (!manager) { // try shortened form: he_IL => he std::string shortened_dict (tag); size_t uscore_pos; if ((uscore_pos = shortened_dict.rfind ('_')) != ((size_t)-1)) { shortened_dict = shortened_dict.substr(0, uscore_pos); for (mapIndex = 0; mapIndex < n_mappings; mapIndex++) { if (!strcmp(shortened_dict.c_str(), mapping[mapIndex].language_tag)) break; } if (mapIndex < n_mappings) { manager = uspell_request_manager (private_dir, mapIndex); } } } g_free (private_dir); if (!manager) return NULL; dict = g_new0 (EnchantDict, 1); dict->user_data = manager; dict->check = uspell_dict_check; dict->suggest = uspell_dict_suggest; dict->add_to_personal = uspell_dict_add_to_personal; dict->add_to_session = uspell_dict_add_to_session; dict->store_replacement = 0; dict->free_suggestions = uspell_dict_free_suggestions; return dict; } EnchantDictStatus uspell_provider_dictionary_status(struct str_enchant_provider * me, const char *const tag) { // TODO: a g_file_exists check on the dictionary associated with the tag g_warning ("uspell_provider_dictionary_status stub - unimplemented\n"); return(EDS_UNKNOWN); } static void uspell_provider_dispose_dict (EnchantProvider * me, EnchantDict * dict) { uSpell *manager; uspellData *myUspellData = reinterpret_cast<uspellData *>(dict->user_data); delete myUspellData->manager; if (myUspellData->personalName) g_free (myUspellData->personalName); g_free (dict->user_data); g_free (dict); } static void uspell_provider_dispose (EnchantProvider * me) { g_free (me); } static char * uspell_provider_identify (EnchantProvider * me) { return "uspell"; } static char * uspell_provider_describe (EnchantProvider * me) { return "Uspell Provider"; } extern "C" { ENCHANT_MODULE_EXPORT (EnchantProvider *) init_enchant_provider (void) { EnchantProvider *provider; provider = g_new0 (EnchantProvider, 1); provider->dispose = uspell_provider_dispose; provider->request_dict = uspell_provider_request_dict; provider->dispose_dict = uspell_provider_dispose_dict; provider->dictionary_status = uspell_provider_dictionary_status; provider->identify = uspell_provider_identify; provider->describe = uspell_provider_describe; return provider; } } <|endoftext|>
<commit_before><commit_msg>saw at least one of these unused by eye, search for more<commit_after><|endoftext|>
<commit_before>#ifndef RENDERER_TRANSFORM_HPP #define RENDERER_TRANSFORM_HPP #include "base.hpp" namespace renderer { template<class V, const int M, const int N> class MxN { public: typedef V ValueType; static const int row = M; static const int col = N; V data[M * N]; public: MxN() { memset(data, 0, row * col * sizeof(V)); } MxN(std::initializer_list<V> values) { int idx = 0; for (auto& value : values) { data[idx++] = value; } } const V& operator [] (const int i) { return data[i]; } }; template<class T> class Matrix final { public: T * data; typedef typename T::ValueType V; typedef MxN<V, T::col, T::row> TransT; public: Matrix() { data = GetPool<T>()->newElement(T()); } Matrix(std::initializer_list<V> values) { data = GetPool<T>()->newElement(T(std::forward<std::initializer_list<V>>(values))); } Matrix(Matrix<T>&& m) { data = m.data; m.data = nullptr; } virtual ~Matrix() { if (!data) return; auto pool = GetPool<T>(); pool->deleteElement(data); } inline int row() { return T::row; } inline int col() { return T::col; } inline bool isSquare() { return row() == col(); } inline bool isSameOrder(Matrix<T>& m) { return row() == m.row() && col() == m.col(); } //access only inline const V& operator [] (const int i) { return static_cast<V>(*((V*)data + i)); } Matrix<T>& operator=(Matrix<T>& m) { memcpy(data, m.data, row() * col() * sizeof(V)); return *this; } Matrix<T> operator+(Matrix<T>& m) { return add(m); } Matrix<T> operator-(Matrix<T>& m) { return minus(m); } Matrix<T> operator*(V v) { return multiply(v); } Matrix<T> operator*(Matrix<T>& m) { return multiply(m); } Matrix<T> operator/(V v) { return divide(v); } //API Matrix<T> clone() { Matrix<T> result; memcpy(result.data, data, row() * col() * sizeof(V)); return result; } Matrix<TransT> transpose() { Matrix<TransT> result; int rowNum = row(), colNum = col(); V* dataOfResult = result.data->data; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { dataOfResult[j * rowNum + i] = (*this)[i * colNum + j]; } } return result; } Matrix<T> add(Matrix<T>& m) { Matrix<T> result; int rowNum = row(), colNum = col(); int idx; V* dataOfResult = result.data->data; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { idx = i * colNum + j; dataOfResult[idx] = (*this)[idx] + m[idx]; } } return result; } Matrix<T> minus(Matrix<T>& m) { Matrix<T> result; int rowNum = row(), colNum = col(); int idx; V* dataOfResult = result.data->data; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { idx = i * colNum + j; dataOfResult[idx] = (*this)[idx] - m[idx]; } } return result; } template<int M, int N> Matrix<T> multiply(Matrix<MxN<V, M, N>>& m) { Matrix<MxN<V, T::row, N>> result; int rowNum = row(), colNum = col(); int idx; V* dataOfResult = result.data->data; for (int i = 0; i < m.row(); i++) { for (int j = 0; j < m.col(); j++) { V total = 0; for (int k = 0; k < colNum; k++) { total += (*this)[i * colNum + k] * m[k * m.col() + j]; } dataOfResult[i * m.col() + j] = total; } } return result; } Matrix<T> multiply(V v) { Matrix<T> result; int rowNum = row(), colNum = col(); int idx; V* dataOfResult = result.data->data; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { idx = i * colNum + j; dataOfResult[idx] = (*this)[idx] *v; } } return result; } Matrix<T> divide(V v) { return multiply(V(1.0)/v); } Matrix<T> power(int pow) { Matrix<T> result = clone(); for (int i = 0; i < pow - 1; i++) { result = result.multiply(*this); } return result; } //debug void debug() { int rowNum = row(), colNum = col(); int idx; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { idx = i * colNum + j; printf("%.1f\t", (*this)[idx]); } printf("\n"); } printf("\n"); } }; typedef MxN<float, 4, 4> Matrix4x4Value; typedef Matrix<Matrix4x4Value> Matrix4x4; } #endif<commit_msg>no message<commit_after>#ifndef RENDERER_TRANSFORM_HPP #define RENDERER_TRANSFORM_HPP #include "base.hpp" namespace renderer { template<class V, const int M, const int N> class MxN { public: typedef V ValueType; static const int row = M; static const int col = N; V data[M * N]; public: MxN() { memset(data, 0, row * col * sizeof(V)); } MxN(std::initializer_list<V> values) { int idx = 0; for (auto& value : values) { data[idx++] = value; } } const V& operator [] (const int i) { return data[i]; } }; template<class T> class Matrix final { public: T * data; typedef typename T::ValueType V; typedef MxN<V, T::col, T::row> TransT; public: Matrix() { data = GetPool<T>()->newElement(T()); } Matrix(std::initializer_list<V> values) { data = GetPool<T>()->newElement(T(std::forward<std::initializer_list<V>>(values))); } Matrix(Matrix<T>& m) { data = GetPool<T>()->newElement(T()); *this = m; } Matrix(Matrix<T>&& m) { data = m.data; m.data = nullptr; } virtual ~Matrix() { if (!data) return; auto pool = GetPool<T>(); pool->deleteElement(data); } inline int row() { return T::row; } inline int col() { return T::col; } inline bool isSquare() { return row() == col(); } inline bool isSameOrder(Matrix<T>& m) { return row() == m.row() && col() == m.col(); } //access only inline const V& operator [] (const int i) { return static_cast<V>(*((V*)data + i)); } Matrix<T>& operator=(Matrix<T>& m) { memcpy(data, m.data, row() * col() * sizeof(V)); return *this; } Matrix<T> operator+(Matrix<T>& m) { return add(m); } Matrix<T> operator-(Matrix<T>& m) { return minus(m); } Matrix<T> operator*(V v) { return multiply(v); } Matrix<T> operator*(Matrix<T>& m) { return multiply(m); } Matrix<T> operator/(V v) { return divide(v); } //API Matrix<T> clone() { Matrix<T> result = *this; return result; } Matrix<TransT> transpose() { Matrix<TransT> result; int rowNum = row(), colNum = col(); V* dataOfResult = result.data->data; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { dataOfResult[j * rowNum + i] = (*this)[i * colNum + j]; } } return result; } Matrix<T> add(Matrix<T>& m) { Matrix<T> result; int rowNum = row(), colNum = col(); int idx; V* dataOfResult = result.data->data; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { idx = i * colNum + j; dataOfResult[idx] = (*this)[idx] + m[idx]; } } return result; } Matrix<T> minus(Matrix<T>& m) { Matrix<T> result; int rowNum = row(), colNum = col(); int idx; V* dataOfResult = result.data->data; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { idx = i * colNum + j; dataOfResult[idx] = (*this)[idx] - m[idx]; } } return result; } template<int M, int N> Matrix<T> multiply(Matrix<MxN<V, M, N>>& m) { Matrix<MxN<V, T::row, N>> result; int rowNum = row(), colNum = col(); int idx; V* dataOfResult = result.data->data; for (int i = 0; i < m.row(); i++) { for (int j = 0; j < m.col(); j++) { V total = 0; for (int k = 0; k < colNum; k++) { total += (*this)[i * colNum + k] * m[k * m.col() + j]; } dataOfResult[i * m.col() + j] = total; } } return result; } Matrix<T> multiply(V v) { Matrix<T> result; int rowNum = row(), colNum = col(); int idx; V* dataOfResult = result.data->data; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { idx = i * colNum + j; dataOfResult[idx] = (*this)[idx] *v; } } return result; } Matrix<T> divide(V v) { return multiply(V(1.0)/v); } Matrix<T> power(int pow) { Matrix<T> result = clone(); for (int i = 0; i < pow - 1; i++) { result = result.multiply(*this); } return result; } //debug void debug() { int rowNum = row(), colNum = col(); int idx; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { idx = i * colNum + j; printf("%.1f\t", (*this)[idx]); } printf("\n"); } printf("\n"); } }; typedef MxN<float, 4, 4> Matrix4x4Value; typedef Matrix<Matrix4x4Value> Matrix4x4; } #endif<|endoftext|>
<commit_before>#ifndef UTIL_TASK_HPP #define UTIL_TASK_HPP #include <atomic> #include <deque> namespace Util { struct task { /** Initializes any resources deferred from constructor * @param alive Shared status; false signals shutdown */ virtual void init(std::atomic_bool& alive) =0; /** Polls for changes * @param alive Shared status; false signals shutdown */ virtual void poll(std::atomic_bool &alive) =0; /** Runs a given task * @param alive Shared status; false signals shutdown */ virtual void run(std::atomic_bool& alive) =0; virtual ~task(void) {} /** Initializes any resources deferred from constructor * @param alive Shared status; false signals shutdown * @param t The task to initialize */ static void init(std::atomic_bool &alive, task *t) { t -> init(alive); } static void poll(std::atomic_bool &alive, task *t) { t -> poll(alive); } /** Runs a given task * @param alive Shared status; false signals shutdown * @param t The task to run */ static void run(std::atomic_bool &alive, task *t) { t -> run(alive); } }; struct supertask : public virtual task { std::deque<task*> tasks; void init(std::atomic_bool& alive) { for(auto t : tasks) { t -> init(alive); } } void poll(std::atomic_bool& alive) { for(auto t : tasks) { t -> poll(alive); } } void run(std::atomic_bool& alive) { for(auto t : tasks) { t -> run(alive); } } virtual ~supertask(void) {} }; struct worker : public virtual task { std::function<void (std::atomic_bool &)> m_init, m_poll, m_run; //void (*m_run)(std::atomic_bool &); void init(std::atomic_bool &alive) { m_init(alive); } void poll(std::atomic_bool &alive) { m_poll(alive); } void run(std::atomic_bool &alive) { m_run(alive); } worker(std::function<void (std::atomic_bool &)> m_init, std::function<void (std::atomic_bool &)> m_poll, std::function<void (std::atomic_bool &)> m_run): m_init(m_init), m_poll(m_poll), m_run(m_run) {} virtual ~worker(void) {} }; } #endif <commit_msg>Added documentation<commit_after>#ifndef UTIL_TASK_HPP #define UTIL_TASK_HPP #include <atomic> #include <deque> namespace Util { struct task { /** Initializes any resources deferred from constructor * @param alive Shared status; false signals shutdown */ virtual void init(std::atomic_bool& alive) =0; /** Polls for changes since init or last poll * @param alive Shared status; false signals shutdown */ virtual void poll(std::atomic_bool &alive) =0; /** Runs a given task * @param alive Shared status; false signals shutdown */ virtual void run(std::atomic_bool& alive) =0; virtual ~task(void) {} /** Initializes any resources deferred from constructor * @param alive Shared status; false signals shutdown * @param t The task to initialize */ static void init(std::atomic_bool &alive, task *t) { t -> init(alive); } /** Polls for changes since init or last poll * @param alive Shared status; false signals shutdown * @param t The task to poll */ static void poll(std::atomic_bool &alive, task *t) { t -> poll(alive); } /** Runs a given task * @param alive Shared status; false signals shutdown * @param t The task to run */ static void run(std::atomic_bool &alive, task *t) { t -> run(alive); } }; struct supertask : public virtual task { std::deque<task*> tasks; void init(std::atomic_bool& alive) { for(auto t : tasks) { t -> init(alive); } } void poll(std::atomic_bool& alive) { for(auto t : tasks) { t -> poll(alive); } } void run(std::atomic_bool& alive) { for(auto t : tasks) { t -> run(alive); } } virtual ~supertask(void) {} }; struct worker : public virtual task { std::function<void (std::atomic_bool &)> m_init, m_poll, m_run; //void (*m_run)(std::atomic_bool &); void init(std::atomic_bool &alive) { m_init(alive); } void poll(std::atomic_bool &alive) { m_poll(alive); } void run(std::atomic_bool &alive) { m_run(alive); } worker(std::function<void (std::atomic_bool &)> m_init, std::function<void (std::atomic_bool &)> m_poll, std::function<void (std::atomic_bool &)> m_run): m_init(m_init), m_poll(m_poll), m_run(m_run) {} virtual ~worker(void) {} }; } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 author 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 "libtorrent/magnet_uri.hpp" #include "libtorrent/session.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/escape_string.hpp" #include "libtorrent/error_code.hpp" #include <string> namespace libtorrent { std::string make_magnet_uri(torrent_handle const& handle) { if (!handle.is_valid()) return ""; char ret[1024]; sha1_hash const& ih = handle.info_hash(); int num_chars = snprintf(ret, sizeof(ret), "magnet:?xt=urn:btih:%s" , base32encode(std::string((char const*)&ih[0], 20)).c_str()); std::string name = handle.name(); if (!name.empty()) num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&dn=%s" , escape_string(name.c_str(), name.length()).c_str()); std::string tracker; torrent_status st = handle.status(); if (!st.current_tracker.empty()) { tracker = st.current_tracker; } else { std::vector<announce_entry> const& tr = handle.trackers(); if (!tr.empty()) tracker = tr[0].url; } if (!tracker.empty()) num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&tr=%s" , escape_string(tracker.c_str(), tracker.size()).c_str()); return ret; } std::string make_magnet_uri(torrent_info const& info) { char ret[1024]; sha1_hash const& ih = info.info_hash(); int num_chars = snprintf(ret, sizeof(ret), "magnet:?xt=urn:btih:%s" , base32encode(std::string((char*)&ih[0], 20)).c_str()); std::string const& name = info.name(); if (!name.empty()) num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&dn=%s" , escape_string(name.c_str(), name.length()).c_str()); std::vector<announce_entry> const& tr = info.trackers(); if (!tr.empty()) { num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&tr=%s" , escape_string(tr[0].url.c_str(), tr[0].url.length()).c_str()); } return ret; } #ifndef TORRENT_NO_DEPRECATE #ifndef BOOST_NO_EXCEPTIONS torrent_handle add_magnet_uri(session& ses, std::string const& uri , std::string const& save_path , storage_mode_t storage_mode , bool paused , storage_constructor_type sc , void* userdata) { std::string name; std::string tracker; error_code ec; std::string display_name = url_has_argument(uri, "dn"); if (!display_name.empty()) name = unescape_string(display_name.c_str(), ec); std::string tracker_string = url_has_argument(uri, "tr"); if (!tracker_string.empty()) tracker = unescape_string(tracker_string.c_str(), ec); std::string btih = url_has_argument(uri, "xt"); if (btih.empty()) return torrent_handle(); if (btih.compare(0, 9, "urn:btih:") != 0) return torrent_handle(); sha1_hash info_hash; if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]); else info_hash.assign(base32decode(btih.substr(9))); return ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash , name.empty() ? 0 : name.c_str(), save_path, entry() , storage_mode, paused, sc, userdata); } torrent_handle add_magnet_uri(session& ses, std::string const& uri , add_torrent_params p) { error_code ec; torrent_handle ret = add_magnet_uri(ses, uri, p, ec); if (ec) throw libtorrent_exception(ec); return ret; } #endif // BOOST_NO_EXCEPTIONS torrent_handle add_magnet_uri(session& ses, std::string const& uri , add_torrent_params p, error_code& ec) { parse_magnet_uri(uri, p, ec); if (ec) return torrent_handle(); return ses.add_torrent(p, ec); } #endif // TORRENT_NO_DEPRECATE void parse_magnet_uri(std::string const& uri, add_torrent_params& p, error_code& ec) { std::string name; std::string tracker; error_code e; std::string display_name = url_has_argument(uri, "dn"); if (!display_name.empty()) name = unescape_string(display_name.c_str(), e); // parse trackers out of the magnet link std::string::size_type pos = std::string::npos; std::string url = url_has_argument(uri, "tr", &pos); while (pos != std::string::npos) { error_code e; url = unescape_string(url, e); if (e) continue; p.trackers.push_back(url); pos = uri.find("&tr=", pos); if (pos == std::string::npos) break; pos += 4; url = uri.substr(pos, uri.find('&', pos) - pos); } std::string btih = url_has_argument(uri, "xt"); if (btih.empty()) { ec = errors::missing_info_hash_in_uri; return; } if (btih.compare(0, 9, "urn:btih:") != 0) { ec = errors::missing_info_hash_in_uri; return; } #ifndef TORRENT_DISABLE_DHT std::string::size_type node_pos = std::string::npos; std::string node = url_has_argument(uri, "dht", &node_pos); while (!node.empty()) { std::string::size_type divider = node.find_last_of(':'); if (divider != std::string::npos) { int port = atoi(node.c_str()+divider+1); if (port != 0) p.dht_nodes.push_back(std::make_pair(node.substr(0, divider), port)); } node_pos = uri.find("&dht=", node_pos); if (node_pos == std::string::npos) break; node_pos += 5; node = uri.substr(node_pos, uri.find('&', node_pos) - node_pos); } #endif sha1_hash info_hash; if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]); else info_hash.assign(base32decode(btih.substr(9))); p.info_hash = info_hash; if (!name.empty()) p.name = name; } } <commit_msg>include all trackers in magnet links<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 author 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 "libtorrent/magnet_uri.hpp" #include "libtorrent/session.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/escape_string.hpp" #include "libtorrent/error_code.hpp" #include <string> namespace libtorrent { std::string make_magnet_uri(torrent_handle const& handle) { if (!handle.is_valid()) return ""; char ret[1024]; sha1_hash const& ih = handle.info_hash(); int num_chars = snprintf(ret, sizeof(ret), "magnet:?xt=urn:btih:%s" , base32encode(std::string((char const*)&ih[0], 20)).c_str()); std::string name = handle.name(); if (!name.empty()) num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&dn=%s" , escape_string(name.c_str(), name.length()).c_str()); std::vector<announce_entry> const& tr = handle.trackers(); for (std::vector<announce_entry>::const_iterator i = tr.begin(), end(tr.end()); i != end; ++i) { num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&tr=%s" , escape_string(i->url.c_str(), i->url.length()).c_str()); } return ret; } std::string make_magnet_uri(torrent_info const& info) { char ret[1024]; sha1_hash const& ih = info.info_hash(); int num_chars = snprintf(ret, sizeof(ret), "magnet:?xt=urn:btih:%s" , base32encode(std::string((char*)&ih[0], 20)).c_str()); std::string const& name = info.name(); if (!name.empty()) num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&dn=%s" , escape_string(name.c_str(), name.length()).c_str()); std::vector<announce_entry> const& tr = info.trackers(); for (std::vector<announce_entry>::const_iterator i = tr.begin(), end(tr.end()); i != end; ++i) { num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&tr=%s" , escape_string(i->url.c_str(), i->url.length()).c_str()); } return ret; } #ifndef TORRENT_NO_DEPRECATE #ifndef BOOST_NO_EXCEPTIONS torrent_handle add_magnet_uri(session& ses, std::string const& uri , std::string const& save_path , storage_mode_t storage_mode , bool paused , storage_constructor_type sc , void* userdata) { std::string name; std::string tracker; error_code ec; std::string display_name = url_has_argument(uri, "dn"); if (!display_name.empty()) name = unescape_string(display_name.c_str(), ec); std::string tracker_string = url_has_argument(uri, "tr"); if (!tracker_string.empty()) tracker = unescape_string(tracker_string.c_str(), ec); std::string btih = url_has_argument(uri, "xt"); if (btih.empty()) return torrent_handle(); if (btih.compare(0, 9, "urn:btih:") != 0) return torrent_handle(); sha1_hash info_hash; if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]); else info_hash.assign(base32decode(btih.substr(9))); return ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash , name.empty() ? 0 : name.c_str(), save_path, entry() , storage_mode, paused, sc, userdata); } torrent_handle add_magnet_uri(session& ses, std::string const& uri , add_torrent_params p) { error_code ec; torrent_handle ret = add_magnet_uri(ses, uri, p, ec); if (ec) throw libtorrent_exception(ec); return ret; } #endif // BOOST_NO_EXCEPTIONS torrent_handle add_magnet_uri(session& ses, std::string const& uri , add_torrent_params p, error_code& ec) { parse_magnet_uri(uri, p, ec); if (ec) return torrent_handle(); return ses.add_torrent(p, ec); } #endif // TORRENT_NO_DEPRECATE void parse_magnet_uri(std::string const& uri, add_torrent_params& p, error_code& ec) { std::string name; std::string tracker; error_code e; std::string display_name = url_has_argument(uri, "dn"); if (!display_name.empty()) name = unescape_string(display_name.c_str(), e); // parse trackers out of the magnet link std::string::size_type pos = std::string::npos; std::string url = url_has_argument(uri, "tr", &pos); while (pos != std::string::npos) { error_code e; url = unescape_string(url, e); if (e) continue; p.trackers.push_back(url); pos = uri.find("&tr=", pos); if (pos == std::string::npos) break; pos += 4; url = uri.substr(pos, uri.find('&', pos) - pos); } std::string btih = url_has_argument(uri, "xt"); if (btih.empty()) { ec = errors::missing_info_hash_in_uri; return; } if (btih.compare(0, 9, "urn:btih:") != 0) { ec = errors::missing_info_hash_in_uri; return; } #ifndef TORRENT_DISABLE_DHT std::string::size_type node_pos = std::string::npos; std::string node = url_has_argument(uri, "dht", &node_pos); while (!node.empty()) { std::string::size_type divider = node.find_last_of(':'); if (divider != std::string::npos) { int port = atoi(node.c_str()+divider+1); if (port != 0) p.dht_nodes.push_back(std::make_pair(node.substr(0, divider), port)); } node_pos = uri.find("&dht=", node_pos); if (node_pos == std::string::npos) break; node_pos += 5; node = uri.substr(node_pos, uri.find('&', node_pos) - node_pos); } #endif sha1_hash info_hash; if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]); else info_hash.assign(base32decode(btih.substr(9))); p.info_hash = info_hash; if (!name.empty()) p.name = name; } } <|endoftext|>
<commit_before>#include "main/spine.hpp" Spine::Spine() { this->__info.name = "Spine"; this->__info.author = "mainline"; std::cout << "[Spine] Spine Open" << std::endl; } Spine::~Spine() { int position = 0; std::string closeMessage; for (auto& modName : this->loadedModules) { closeMessage = modName + " close"; this->sendMessage(SocketType::PUB, closeMessage); this->threads.at(position)->join(); delete this->threads[position]; position += 1; } this->closeSockets(); std::cout << "[Spine] Closed" << std::endl; } std::string Spine::name() { return this->__info.name; } std::vector<std::string> Spine::listModules(std::string directory) { std::vector<std::string> moduleFiles; try { boost::filesystem::directory_iterator startd(directory), endd; auto files = boost::make_iterator_range(startd, endd); for(boost::filesystem::path p : files){ if (p.extension() == this->moduleFileExtension) { moduleFiles.push_back(p.string()); } } } catch(boost::filesystem::filesystem_error e) { std::cerr << "[Spine] WARNING! Could not load modules!" << std::endl; std::cerr << " - " << e.what() << std::endl; } return moduleFiles; } int Spine::openModuleFile(std::string moduleFile, SpineModule& spineModule) { spineModule.module_so = dlopen(moduleFile.c_str(), RTLD_NOW | RTLD_GLOBAL); if (!spineModule.module_so) { std::cerr << dlerror() << std::endl; return 1; } return 0; } int Spine::resolveModuleFunctions(SpineModule& spineModule) { spineModule.loadModule = (Module_loader*)dlsym(spineModule.module_so, "loadModule"); if (!spineModule.loadModule) { return 1; } spineModule.unloadModule = (Module_unloader*)dlsym(spineModule.module_so, "unloadModule"); if (!spineModule.unloadModule) { return 2; } return 0; } bool Spine::loadModules(std::string directory) { std::vector<std::string> moduleFiles = this->listModules(directory); for (auto filename : moduleFiles) { std::thread* moduleThread = new std::thread([this, filename]() { int failure = 0; SpineModule spineModule; failure = this->openModuleFile(filename, spineModule); if (failure != 0) { exit(EXIT_FAILURE); } failure = this->resolveModuleFunctions(spineModule); if (failure != 0) { exit(EXIT_FAILURE); } spineModule.module = spineModule.loadModule(); std::string moduleName = spineModule.module->name(); spineModule.module->setSocketContext(this->inp_context); spineModule.module->openSockets(); spineModule.module->subscribe(moduleName); spineModule.module->notify(SocketType::PUB, "Spine"); spineModule.module->notify(SocketType::MGM_OUT, "Spine"); std::string regMessage = "register " + moduleName; spineModule.module->sendMessage(SocketType::MGM_OUT, regMessage); std::string moduleLoaded = spineModule.module->recvMessage(SocketType::MGM_OUT, [&](const std::string& regReply) -> std::string { return regReply; }, 3000); if (moduleLoaded == "success") { spineModule.module->run(); } spineModule.unloadModule(spineModule.module); if (dlclose(spineModule.module_so) != 0) { exit(EXIT_FAILURE); } }); if (this->registerModule()) { this->threads.push_back(moduleThread); } else { moduleThread->join(); std::cerr << "[Spine] Failed to register module: " << filename << std::endl; } } return true; } bool Spine::registerModule() { std::string regMessage = this->recvMessage(SocketType::MGM_IN, [&](const std::string& regReply) -> std::string { return regReply; }); if (regMessage != "__NULL_RECV_FAILED__") { std::vector<std::string> tokens; boost::split(tokens, regMessage, boost::is_any_of(" ")); if (tokens.at(0) == "register") { if (tokens.at(1) != "") { this->loadedModules.push_back(tokens.at(1)); this->notify(SocketType::PUB, tokens.at(1)); this->sendMessage(SocketType::MGM_IN, "success"); return true; } } } return false; } void Spine::run() { for (int count = 0;count<3;count++) { std::cout << "Sleeping..." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(2)); } // Dummy close to make sure our subscription is correct this->sendMessage(SocketType::PUB, "Module close"); std::this_thread::sleep_for(std::chrono::seconds(1)); } <commit_msg>Moved some logic inside callbacks as we have no fear of tailcalling.<commit_after>#include "main/spine.hpp" Spine::Spine() { this->__info.name = "Spine"; this->__info.author = "mainline"; std::cout << "[Spine] Spine Open" << std::endl; } Spine::~Spine() { int position = 0; std::string closeMessage; // Here the Spine sends a message out on it's publish socket // Each message directs a 'close' message to a module registered // in the Spine as 'loaded' // It then waits for the module to join. It relies on the module closing // cleanly else it will lock up waiting. for (auto& modName : this->loadedModules) { closeMessage = modName + " close"; this->sendMessage(SocketType::PUB, closeMessage); this->threads.at(position)->join(); delete this->threads[position]; position += 1; } // After all modules are closed we don't need our sockets // so we should close them before exit, to be nice this->closeSockets(); std::cout << "[Spine] Closed" << std::endl; } std::string Spine::name() { return this->__info.name; } std::vector<std::string> Spine::listModules(std::string directory) { std::vector<std::string> moduleFiles; // Here we list a directory and built a vector of files that match // our platform specific dynamic lib extension (e.g., .so) try { boost::filesystem::directory_iterator startd(directory), endd; auto files = boost::make_iterator_range(startd, endd); for(boost::filesystem::path p : files){ if (p.extension() == this->moduleFileExtension) { moduleFiles.push_back(p.string()); } } } catch(boost::filesystem::filesystem_error e) { std::cerr << "[Spine] WARNING! Could not load modules!" << std::endl; std::cerr << " - " << e.what() << std::endl; } return moduleFiles; } int Spine::openModuleFile(std::string moduleFile, SpineModule& spineModule) { // Here we use dlopen to load the dynamic library (that is, a compiled module) spineModule.module_so = dlopen(moduleFile.c_str(), RTLD_NOW | RTLD_GLOBAL); if (!spineModule.module_so) { std::cerr << dlerror() << std::endl; return 1; } return 0; } int Spine::resolveModuleFunctions(SpineModule& spineModule) { spineModule.loadModule = (Module_loader*)dlsym(spineModule.module_so, "loadModule"); if (!spineModule.loadModule) { return 1; } spineModule.unloadModule = (Module_unloader*)dlsym(spineModule.module_so, "unloadModule"); if (!spineModule.unloadModule) { return 2; } return 0; } bool Spine::loadModules(std::string directory) { std::vector<std::string> moduleFiles = this->listModules(directory); for (auto filename : moduleFiles) { std::thread* moduleThread = new std::thread([this, filename]() { int failure = 0; SpineModule spineModule; failure = this->openModuleFile(filename, spineModule); if (failure != 0) { exit(EXIT_FAILURE); } failure = this->resolveModuleFunctions(spineModule); if (failure != 0) { exit(EXIT_FAILURE); } spineModule.module = spineModule.loadModule(); std::string moduleName = spineModule.module->name(); spineModule.module->setSocketContext(this->inp_context); spineModule.module->openSockets(); spineModule.module->subscribe(moduleName); spineModule.module->notify(SocketType::PUB, "Spine"); spineModule.module->notify(SocketType::MGM_OUT, "Spine"); std::string regMessage = "register " + moduleName; spineModule.module->sendMessage(SocketType::MGM_OUT, regMessage); std::string moduleRun = spineModule.module->recvMessage(SocketType::MGM_OUT, [&](const std::string& regReply) -> std::string { if (regReply == "success") { spineModule.module->run(); } return regReply; }, 3000); spineModule.unloadModule(spineModule.module); if (dlclose(spineModule.module_so) != 0) { exit(EXIT_FAILURE); } }); if (this->registerModule()) { this->threads.push_back(moduleThread); } else { moduleThread->join(); std::cerr << "[Spine] Failed to register module: " << filename << std::endl; } } return true; } bool Spine::registerModule() { std::string regReturn = this->recvMessage(SocketType::MGM_IN, [&](const std::string& regReply) -> std::string { if (regReply != "__NULL_RECV_FAILED__") { std::vector<std::string> tokens; boost::split(tokens, regReply, boost::is_any_of(" ")); if (tokens.at(0) == "register") { if (tokens.at(1) != "") { this->loadedModules.push_back(tokens.at(1)); this->notify(SocketType::PUB, tokens.at(1)); this->sendMessage(SocketType::MGM_IN, "success"); return "true"; } } } return "false"; }); return (regReturn == "true") ? true : false; } void Spine::run() { for (int count = 0;count<3;count++) { std::cout << "Sleeping..." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(2)); } // Dummy close to make sure our subscription is correct this->sendMessage(SocketType::PUB, "Module close"); std::this_thread::sleep_for(std::chrono::seconds(1)); } <|endoftext|>
<commit_before>#include "window.h" #include "map_window.h" #include "inspection_window.h" #include "equipment_window.h" #include "gameengine.h" #include "event.h" void MapWindow::gainFocus () { std::string l_mapName (""); getEngine()->loadMap(l_mapName); setTitle ("Map"); m_mapXOffset = 1; m_mapYOffset = 9; m_mapStartX = 0; m_mapStartY = 0; m_mapWidth = 20; m_mapHeight = 25; m_sidebarWidth = 20; m_sidebarXOffset = getWidth() - m_sidebarWidth; m_action = 'm'; } void MapWindow::redraw() { drawSeparators(); drawMap(); drawMessages(); drawSidebar(); } void MapWindow::resize() { setDimensions (0, 0, getEngine()->getGraphics()->getScreenWidth(), getEngine()->getGraphics()->getScreenHeight()); m_sidebarXOffset = getWidth() - m_sidebarWidth - 1; m_mapWidth = getWidth() - m_mapXOffset - m_sidebarWidth - 1; m_mapHeight = getHeight() - m_mapYOffset - 1; } void MapWindow::keyDown (unsigned char key) { Window::keyDown (key); if (key == 'w' || key == 'a' || key == 's' || key == 'd') { DIRECTION l_dir = Direction::None; switch (key) { case 'w': l_dir = Direction::North; break; case 'a': l_dir = Direction::West; break; case 's': l_dir = Direction::South; break; case 'd': l_dir = Direction::East; break; } if (m_action == 'm') { MoveEntityEvent* l_event = new MoveEntityEvent; l_event->entity = getEngine()->getEntities()->getPlayer(); l_event->direction = l_dir; getEngine()->raiseEvent (l_event); } if (m_action == 'k') { AttackEntityEvent* l_event = new AttackEntityEvent; l_event->entity = getEngine()->getEntities()->getPlayer(); l_event->direction = l_dir; getEngine()->raiseEvent (l_event); } if (m_action == 'i') { std::vector<EntityId> l_entities = getEngine()->getEntities()->findEntitiesToThe(l_dir, getEngine()->getEntities()->getPlayer()); if (l_entities.size() > 0) { EntityId* l_target = new EntityId(l_entities[0]); InspectionWindow* l_win = new InspectionWindow(); l_win->initialise(getEngine(), l_target); getEngine()->getWindows()->pushWindow (l_win); } } if (m_action != 'i') getEngine()->swapTurn(); m_action = 'm'; } if (key == 27) { getEngine()->quit(); } if (key == 'm' || key == 'k' || key == 'i') { m_action = key; } if (key == '.') { getEngine()->swapTurn(); } if (key == 'p') { LocationComponent* l_playerLoc = getEngine()->getEntities()->getLocations()->get (getEngine()->getEntities()->getPlayer()); std::vector<EntityId> l_entities = getEngine()->getEntities()->findEntitiesAt (l_playerLoc->x, l_playerLoc->y); bool foundSomethingAlready = false; for (size_t ii = 0; ii < l_entities.size(); ii++) { DroppableComponent* droppable = getEngine()->getEntities()->getDroppables()->get(l_entities[ii]); if (droppable) { if (!foundSomethingAlready) { PickupEquipmentEvent* event = new PickupEquipmentEvent(); event->entity = getEngine()->getEntities()->getPlayer(); event->item = l_entities[ii]; getEngine()->raiseEvent (event); foundSomethingAlready = true; } else { getEngine()->addMessage(INFO, "There's something else here..."); break; } } } } if (key == 'E') { EquipmentWindow* l_win = new EquipmentWindow(); l_win->initialise(getEngine()); getEngine()->getWindows()->pushWindow (l_win); } } void MapWindow::drawSeparators() { getEngine()->getGraphics()->drawBorder (m_mapYOffset-1, m_mapXOffset-1, m_mapHeight, m_mapWidth); getEngine()->getGraphics()->drawBorder (0, m_sidebarXOffset, getHeight()-2, m_sidebarWidth-1); } void MapWindow::drawMap() { std::map<EntityId, SpriteComponent>& l_sprites = getEngine()->getEntities()->getSprites()->getAll(); std::map<EntityId, SpriteComponent>::iterator it = l_sprites.begin(); LocationComponent* l_player = getEngine()->getEntities()->getLocations()->get (getEngine()->getEntities()->getPlayer()); if (l_player) { m_mapStartX = l_player->x - (m_mapWidth/2); m_mapStartY = l_player->y - (m_mapHeight/2); } for (; it != l_sprites.end(); it++) { SpriteComponent& l_sprite = it->second; LocationComponent* l_location = getEngine()->getEntities()->getLocations()->get (it->first); int x = l_location->x; int y = l_location->y; int xWidth = m_mapStartX + m_mapWidth; int yWidth = m_mapStartY + m_mapHeight; if (x >= m_mapStartX && x < xWidth && y >= m_mapStartY && y < yWidth && l_location->z == getEngine()->getLevel()) { drawTile ( l_location->y + m_mapYOffset - m_mapStartY, l_location->x + m_mapXOffset - m_mapStartX, l_sprite.sprite, l_sprite.fgColor, l_sprite.bgColor); } } } void MapWindow::drawMessages() { std::vector<Message>& l_messages = getEngine()->getMessages(); size_t ii = l_messages.size(); size_t hh = m_mapYOffset-2; for (; ii > 0 && hh > 0; hh--, ii--) { Color fg; switch (l_messages[ii-1].severity) { case INFO: fg = Color (WHITE); break; case WARN: fg = Color (RED); break; case GOOD: fg = Color (GREEN); break; case CRIT: fg = Color (BLUE); break; } drawString (hh, 1, l_messages[ii-1].message.c_str(), fg); } } void MapWindow::drawSidebar () { // Current health drawString (2, m_sidebarXOffset+2, "Health:"); EntityId player = getEngine()->getEntities()->getPlayer(); HealthComponent* l_health = getEngine()->getEntities()->getHealths()->get(player); if (l_health) { drawProgressBar (m_sidebarXOffset+10, 2, l_health->health); } // Actions to take drawString (getHeight()-7, m_sidebarXOffset+2, "move (wasd)"); drawString (getHeight()-7, m_sidebarXOffset+2, "m", Color (GREEN)); if (m_action == 'm') drawString (getHeight()-7, m_sidebarXOffset+1, ">", Color (RED)); drawString (getHeight()-6, m_sidebarXOffset+2, "attack (wasd)"); drawString (getHeight()-6, m_sidebarXOffset+7, "k", Color (GREEN)); if (m_action == 'k') drawString (getHeight()-6, m_sidebarXOffset+1, ">", Color (RED)); drawString (getHeight()-5, m_sidebarXOffset+2, "inspect (wasd)"); drawString (getHeight()-5, m_sidebarXOffset+2, "i", Color (GREEN)); if (m_action == 'i') drawString (getHeight()-5, m_sidebarXOffset+1, ">", Color (RED)); drawString (getHeight()-4, m_sidebarXOffset+2, "skip turn (.)"); drawString (getHeight()-4, m_sidebarXOffset+13, ".", Color (GREEN)); drawString (getHeight()-2, m_sidebarXOffset+2, "View Equipment"); drawString (getHeight()-2, m_sidebarXOffset+7, "E", Color (GREEN)); } void MapWindow::drawProgressBar (int x, int y, int value) { float l_value = (float) value; Color l_color ((1.0f-(l_value/10.0f)), l_value/10.0f, 0); for (int xx = 0; xx < value; xx++) { drawTile (y, x+xx, 178, l_color, Color(BLACK)); } } <commit_msg>Added command to sidebar and message if nothing is found to be picked up<commit_after>#include "window.h" #include "map_window.h" #include "inspection_window.h" #include "equipment_window.h" #include "gameengine.h" #include "event.h" void MapWindow::gainFocus () { std::string l_mapName (""); getEngine()->loadMap(l_mapName); setTitle ("Map"); m_mapXOffset = 1; m_mapYOffset = 9; m_mapStartX = 0; m_mapStartY = 0; m_mapWidth = 20; m_mapHeight = 25; m_sidebarWidth = 20; m_sidebarXOffset = getWidth() - m_sidebarWidth; m_action = 'm'; } void MapWindow::redraw() { drawSeparators(); drawMap(); drawMessages(); drawSidebar(); } void MapWindow::resize() { setDimensions (0, 0, getEngine()->getGraphics()->getScreenWidth(), getEngine()->getGraphics()->getScreenHeight()); m_sidebarXOffset = getWidth() - m_sidebarWidth - 1; m_mapWidth = getWidth() - m_mapXOffset - m_sidebarWidth - 1; m_mapHeight = getHeight() - m_mapYOffset - 1; } void MapWindow::keyDown (unsigned char key) { Window::keyDown (key); if (key == 'w' || key == 'a' || key == 's' || key == 'd') { DIRECTION l_dir = Direction::None; switch (key) { case 'w': l_dir = Direction::North; break; case 'a': l_dir = Direction::West; break; case 's': l_dir = Direction::South; break; case 'd': l_dir = Direction::East; break; } if (m_action == 'm') { MoveEntityEvent* l_event = new MoveEntityEvent; l_event->entity = getEngine()->getEntities()->getPlayer(); l_event->direction = l_dir; getEngine()->raiseEvent (l_event); } if (m_action == 'k') { AttackEntityEvent* l_event = new AttackEntityEvent; l_event->entity = getEngine()->getEntities()->getPlayer(); l_event->direction = l_dir; getEngine()->raiseEvent (l_event); } if (m_action == 'i') { std::vector<EntityId> l_entities = getEngine()->getEntities()->findEntitiesToThe(l_dir, getEngine()->getEntities()->getPlayer()); if (l_entities.size() > 0) { EntityId* l_target = new EntityId(l_entities[0]); InspectionWindow* l_win = new InspectionWindow(); l_win->initialise(getEngine(), l_target); getEngine()->getWindows()->pushWindow (l_win); } } if (m_action != 'i') getEngine()->swapTurn(); m_action = 'm'; } if (key == 27) { getEngine()->quit(); } if (key == 'm' || key == 'k' || key == 'i') { m_action = key; } if (key == '.') { getEngine()->swapTurn(); } if (key == 'p') { LocationComponent* l_playerLoc = getEngine()->getEntities()->getLocations()->get (getEngine()->getEntities()->getPlayer()); std::vector<EntityId> l_entities = getEngine()->getEntities()->findEntitiesAt (l_playerLoc->x, l_playerLoc->y); bool foundSomethingAlready = false; for (size_t ii = 0; ii < l_entities.size(); ii++) { DroppableComponent* droppable = getEngine()->getEntities()->getDroppables()->get(l_entities[ii]); if (droppable) { if (!foundSomethingAlready) { PickupEquipmentEvent* event = new PickupEquipmentEvent(); event->entity = getEngine()->getEntities()->getPlayer(); event->item = l_entities[ii]; getEngine()->raiseEvent (event); foundSomethingAlready = true; } else { getEngine()->addMessage(INFO, "There's something else here..."); break; } } } if (!foundSomethingAlready) { getEngine()->addMessage(INFO, "There's nothing here..."); } } if (key == 'E') { EquipmentWindow* l_win = new EquipmentWindow(); l_win->initialise(getEngine()); getEngine()->getWindows()->pushWindow (l_win); } } void MapWindow::drawSeparators() { getEngine()->getGraphics()->drawBorder (m_mapYOffset-1, m_mapXOffset-1, m_mapHeight, m_mapWidth); getEngine()->getGraphics()->drawBorder (0, m_sidebarXOffset, getHeight()-2, m_sidebarWidth-1); } void MapWindow::drawMap() { std::map<EntityId, SpriteComponent>& l_sprites = getEngine()->getEntities()->getSprites()->getAll(); std::map<EntityId, SpriteComponent>::iterator it = l_sprites.begin(); LocationComponent* l_player = getEngine()->getEntities()->getLocations()->get (getEngine()->getEntities()->getPlayer()); if (l_player) { m_mapStartX = l_player->x - (m_mapWidth/2); m_mapStartY = l_player->y - (m_mapHeight/2); } for (; it != l_sprites.end(); it++) { SpriteComponent& l_sprite = it->second; LocationComponent* l_location = getEngine()->getEntities()->getLocations()->get (it->first); int x = l_location->x; int y = l_location->y; int xWidth = m_mapStartX + m_mapWidth; int yWidth = m_mapStartY + m_mapHeight; if (x >= m_mapStartX && x < xWidth && y >= m_mapStartY && y < yWidth && l_location->z == getEngine()->getLevel()) { drawTile ( l_location->y + m_mapYOffset - m_mapStartY, l_location->x + m_mapXOffset - m_mapStartX, l_sprite.sprite, l_sprite.fgColor, l_sprite.bgColor); } } } void MapWindow::drawMessages() { std::vector<Message>& l_messages = getEngine()->getMessages(); size_t ii = l_messages.size(); size_t hh = m_mapYOffset-2; for (; ii > 0 && hh > 0; hh--, ii--) { Color fg; switch (l_messages[ii-1].severity) { case INFO: fg = Color (WHITE); break; case WARN: fg = Color (RED); break; case GOOD: fg = Color (GREEN); break; case CRIT: fg = Color (BLUE); break; } drawString (hh, 1, l_messages[ii-1].message.c_str(), fg); } } void MapWindow::drawSidebar () { // Current health drawString (2, m_sidebarXOffset+2, "Health:"); EntityId player = getEngine()->getEntities()->getPlayer(); HealthComponent* l_health = getEngine()->getEntities()->getHealths()->get(player); if (l_health) { drawProgressBar (m_sidebarXOffset+10, 2, l_health->health); } // Actions to take drawString (getHeight()-8, m_sidebarXOffset+2, "pickup Items"); drawString (getHeight()-8, m_sidebarXOffset+2, "p", Color (GREEN)); drawString (getHeight()-7, m_sidebarXOffset+2, "move (wasd)"); drawString (getHeight()-7, m_sidebarXOffset+2, "m", Color (GREEN)); if (m_action == 'm') drawString (getHeight()-7, m_sidebarXOffset+1, ">", Color (RED)); drawString (getHeight()-6, m_sidebarXOffset+2, "attack (wasd)"); drawString (getHeight()-6, m_sidebarXOffset+7, "k", Color (GREEN)); if (m_action == 'k') drawString (getHeight()-6, m_sidebarXOffset+1, ">", Color (RED)); drawString (getHeight()-5, m_sidebarXOffset+2, "inspect (wasd)"); drawString (getHeight()-5, m_sidebarXOffset+2, "i", Color (GREEN)); if (m_action == 'i') drawString (getHeight()-5, m_sidebarXOffset+1, ">", Color (RED)); drawString (getHeight()-4, m_sidebarXOffset+2, "skip turn (.)"); drawString (getHeight()-4, m_sidebarXOffset+13, ".", Color (GREEN)); drawString (getHeight()-2, m_sidebarXOffset+2, "View Equipment"); drawString (getHeight()-2, m_sidebarXOffset+7, "E", Color (GREEN)); } void MapWindow::drawProgressBar (int x, int y, int value) { float l_value = (float) value; Color l_color ((1.0f-(l_value/10.0f)), l_value/10.0f, 0); for (int xx = 0; xx < value; xx++) { drawTile (y, x+xx, 178, l_color, Color(BLACK)); } } <|endoftext|>
<commit_before>// http://lgecodejam.com // lge code jam June, 2014 // problem.3 // [email protected] #if defined _EXTERNAL_DEBUGGER && defined _DEBUG #include <trace/trace.h> #include <intrin.h> #else #define trace printf #endif #include <iostream> #include <cstdio> #include <cstring> #include <set> #include <functional> #include <algorithm> using namespace std; enum { X = 0, Y, }; // for indexing typedef unsigned int uint32; class Point { public: Point() : x(0), y(0) {} Point(int x_, int y_) : x(x_), y(y_) {} ~Point() {} bool operator <(const Point& p) const { return x == p.x ? y < p.y : x < p.x; } bool operator >(const Point& p) const { return x == p.x ? y > p.y : x > p.x; } int x, y; }; typedef multiset<Point> MinSet; typedef multiset<Point, greater<Point> > MaxSet; int n; MinSet min_xy, min_yx; MaxSet max_xy, max_yx; template<typename T> void remove(T &s, const Point p) { typename T::iterator i = s.begin(); for (; i != s.end(); i++) { if (i->x == p.x && i->y == p.y) { s.erase(i); return; } } } int simulation(int left, int right, int top, int bottom) { MinSet min_xy_(min_xy); MinSet min_yx_(min_yx); MaxSet max_xy_(max_xy); MaxSet max_yx_(max_yx); int i; for (i = 0; i < left; i++) { Point p = *min_xy_.begin(); Point q(p.y, p.x); remove<MinSet>(min_yx_, q); remove<MaxSet>(max_yx_, q); min_xy_.erase(min_xy_.begin()); } for (i = 0; i < right; i++) { Point p = *max_xy_.begin(); Point q(p.y, p.x); remove<MinSet>(min_yx_, q); remove<MaxSet>(max_yx_, q); max_xy_.erase(max_xy_.begin()); } for (i = 0; i < bottom; i++) { Point p = *min_yx_.begin(); Point q(p.y, p.x); remove<MinSet>(min_xy_, q); remove<MaxSet>(max_xy_, q); min_yx_.erase(min_yx_.begin()); } for (i = 0; i < top; i++) { Point p = *max_yx_.begin(); Point q(p.y, p.x); remove<MinSet>(min_xy_, q); remove<MaxSet>(max_xy_, q); max_yx_.erase(max_yx_.begin()); } return max(max_xy_.begin()->x - min_xy_.begin()->x, max_yx_.begin()->x - min_yx_.begin()->x); } void solve() { min_xy.clear(); min_yx.clear(); max_xy.clear(); max_yx.clear(); scanf("%d", &n); int i, x, y; for (i = 0; i < 4; i++) { scanf("%d %d", &x, &y); min_xy.insert(Point(x, y)); max_xy.insert(Point(x, y)); min_yx.insert(Point(y, x)); max_yx.insert(Point(y, x)); } for (; i < n; i++) { scanf("%d %d", &x, &y); min_xy.insert(Point(x, y)); max_xy.insert(Point(x, y)); min_yx.insert(Point(y, x)); max_yx.insert(Point(y, x)); min_xy.erase(--min_xy.rbegin().base()); min_yx.erase(--min_yx.rbegin().base()); max_xy.erase(--max_xy.rbegin().base()); max_yx.erase(--max_yx.rbegin().base()); } // for all cases int solution = 0x7FFFFFFF; int direct[4]; // left, right, top, bottom for (int a = 1; a <= 8; a <<= 1) { for (int b = 1; b <= 8; b <<= 1) { for (int c = 1; c <= 8; c <<= 1) { memset(direct, 0, sizeof(int) * 4); #ifdef WIN32 unsigned long res; _BitScanForward(&res, a); direct[res]++; _BitScanForward(&res, b); direct[res]++; _BitScanForward(&res, c); direct[res]++; #else // __linux__ direct[__builtin_ctz(a)]++; direct[__builtin_ctz(b)]++; direct[__builtin_ctz(c)]++; #endif //static int k = 1; //trace("%d) %d %d %d %d (%d)\n", k++, direct[0], direct[1], direct[2], direct[3], direct[0] + direct[1] + direct[2] + direct[3]); solution = min(solution, simulation(direct[0], direct[1], direct[2], direct[3])); } } } trace("%d\n", solution); } int main(int, char*[]) { int num; scanf("%d", &num); for (int i = 0; i < num; i++) {solve();} return 0; } <commit_msg>removed duplication in loop<commit_after>// http://lgecodejam.com // lge code jam June, 2014 // problem.3 // [email protected] #if defined _EXTERNAL_DEBUGGER && defined _DEBUG #include <trace/trace.h> #include <intrin.h> #else #define trace printf #endif #include <iostream> #include <cstdio> #include <cstring> #include <set> #include <functional> #include <algorithm> using namespace std; enum { X = 0, Y, }; // for indexing typedef unsigned int uint32; class Point { public: Point() : x(0), y(0) {} Point(int x_, int y_) : x(x_), y(y_) {} ~Point() {} bool operator <(const Point& p) const { return x == p.x ? y < p.y : x < p.x; } bool operator >(const Point& p) const { return x == p.x ? y > p.y : x > p.x; } int x, y; }; typedef multiset<Point> MinSet; typedef multiset<Point, greater<Point> > MaxSet; int n; MinSet min_xy, min_yx; MaxSet max_xy, max_yx; template<typename T> void remove(T &s, const Point p) { typename T::iterator i = s.begin(); for (; i != s.end(); i++) { if (i->x == p.x && i->y == p.y) { s.erase(i); return; } } } int simulation(int left, int right, int top, int bottom) { MinSet min_xy_(min_xy); MinSet min_yx_(min_yx); MaxSet max_xy_(max_xy); MaxSet max_yx_(max_yx); int i; for (i = 0; i < left; i++) { Point p = *min_xy_.begin(); Point q(p.y, p.x); remove<MinSet>(min_yx_, q); remove<MaxSet>(max_yx_, q); min_xy_.erase(min_xy_.begin()); } for (i = 0; i < right; i++) { Point p = *max_xy_.begin(); Point q(p.y, p.x); remove<MinSet>(min_yx_, q); remove<MaxSet>(max_yx_, q); max_xy_.erase(max_xy_.begin()); } for (i = 0; i < bottom; i++) { Point p = *min_yx_.begin(); Point q(p.y, p.x); remove<MinSet>(min_xy_, q); remove<MaxSet>(max_xy_, q); min_yx_.erase(min_yx_.begin()); } for (i = 0; i < top; i++) { Point p = *max_yx_.begin(); Point q(p.y, p.x); remove<MinSet>(min_xy_, q); remove<MaxSet>(max_xy_, q); max_yx_.erase(max_yx_.begin()); } return max(max_xy_.begin()->x - min_xy_.begin()->x, max_yx_.begin()->x - min_yx_.begin()->x); } void solve() { min_xy.clear(); min_yx.clear(); max_xy.clear(); max_yx.clear(); scanf("%d", &n); int i, x, y; for (i = 0; i < 4; i++) { scanf("%d %d", &x, &y); min_xy.insert(Point(x, y)); max_xy.insert(Point(x, y)); min_yx.insert(Point(y, x)); max_yx.insert(Point(y, x)); } for (; i < n; i++) { scanf("%d %d", &x, &y); min_xy.insert(Point(x, y)); max_xy.insert(Point(x, y)); min_yx.insert(Point(y, x)); max_yx.insert(Point(y, x)); min_xy.erase(--min_xy.rbegin().base()); min_yx.erase(--min_yx.rbegin().base()); max_xy.erase(--max_xy.rbegin().base()); max_yx.erase(--max_yx.rbegin().base()); } // for all cases int solution = 0x7FFFFFFF; int direct[4]; // left, right, top, bottom for (i = 0; i < 4; i++) { memset(direct, 0, sizeof(int) * 4); direct[i] = 3; solution = min(solution, simulation(direct[0], direct[1], direct[2], direct[3])); direct[0] = direct[1] = direct[2] = direct[3] = 1; direct[i] = 0; solution = min(solution, simulation(direct[0], direct[1], direct[2], direct[3])); } for (i = 0; i < 4; i++) { memset(direct, 0, sizeof(int) * 4); direct[i] = 2; for (int j = 0; j < 3; j++) { direct[(i+j+1)%4] = 1; solution = min(solution, simulation(direct[0], direct[1], direct[2], direct[3])); direct[(i+j+1)%4] = 0; } } trace("%d\n", solution); } int main(int, char*[]) { int num; scanf("%d", &num); for (int i = 0; i < num; i++) {solve();} return 0; } <|endoftext|>
<commit_before>// balb_assertiontrackersingleton.t.cpp -*-C++-*- #include <balb_assertiontrackersingleton.h> #include <balb_assertiontracker.h> #include <bdlf_bind.h> #include <bdlf_placeholder.h> #include <bslim_testutil.h> #include <bslma_defaultallocatorguard.h> #include <bslma_testallocator.h> #include <bsl_cstdlib.h> #include <bsl_iostream.h> #include <bsl_sstream.h> #include <bsl_utility.h> using namespace BloombergLP; using namespace bsl; // automatically added by script // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // Test this thing. // ---------------------------------------------------------------------------- // CLASS METHODS // CREATORS // MANIPULATORS // ACCESSORS // ---------------------------------------------------------------------------- // [ 1] void failTracker(const char *, const char *, int); // [ 1] TRACKER *singleton(bslma::Allocator * = 0); // [ 2] USAGE EXAMPLE // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // GLOBAL TYPES, CONSTANTS, AND VARIABLES FOR TESTING // ---------------------------------------------------------------------------- typedef balb::AssertionTrackerSingleton<balb::AssertionTracker> Obj; int id(int i) // Return the specified 'i'. { return i; } void trigger1() // Invoke assertion type 1. { BSLS_ASSERT_ASSERT(0 && "assert 1"); } void trigger2() // Invoke assertion type 2. { BSLS_ASSERT_ASSERT(0 && "assert 2"); } void trigger3() // Report assertion type 3. { Obj::failTracker("0 && \"assert 3\"", __FILE__, __LINE__); } // Try to scotch inlining and loop unrolling int (*volatile id_p)(int) = id; void (*volatile trigger1_p)() = trigger1; void (*volatile trigger2_p)() = trigger2; void (*volatile trigger3_p)() = trigger3; ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Count Number of Assertions Triggered ///- - - - - - - - - - - - - - - - - - - - - - - - // We wish to count how many times assertions trigger, doing no other handling // and allowing the program to continue running (note that this is normally // forbidden in production). We can use 'AssertionTrackerSingleton' to set up // an assertion handler to do this. // // First, we create a class to do the counting. //.. class AssertionCounter { // PRIVATE DATA int d_assertion_counter; // Number of assertions seen. public: // PUBLIC CREATORS explicit AssertionCounter(bsls::Assert::Handler = 0, void * = 0); // Create an 'AssertionCounter' object. We ignore the fallback // handler and optional allocator parameters. // PUBLIC MANIPULATORS void operator()(const char *, const char *, int); // Function called when assertion failure occurs. We ignore the // text, file, and line parameters. // PUBLIC ACCESSORS int getAssertionCount() const; // Return the number of assertions we have seen. }; //.. // Then, we implement the member functions of the 'AssertionCounter' class. //.. AssertionCounter::AssertionCounter(bsls::Assert::Handler, void *) : d_assertion_counter(0) { } void AssertionCounter::operator()(const char *, const char *, int) { ++d_assertion_counter; } int AssertionCounter::getAssertionCount() const { return d_assertion_counter; } //.. // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = (argc > 1) ? atoi(argv[1]) : 1; bool verbose = (argc > 2); (void)verbose; bool veryVerbose = (argc > 3); (void)veryVerbose; bool veryVeryVerbose = (argc > 4); (void)veryVeryVerbose; bool veryVeryVeryVerbose = (argc > 5); (void)veryVeryVeryVerbose; cout << "TEST " << __FILE__ << " CASE " << test << endl; switch (test) { case 0: case 2: { // -------------------------------------------------------------------- // USAGE EXAMPLE // Extracted from component header file. // // Concerns: //: 1 The usage example provided in the component header file compiles, //: links, and runs as shown. // // Plan: //: 1 Incorporate usage example from header into test driver, remove //: leading comment characters, and replace 'assert' with 'ASSERT'. //: (C-1) // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << "\nUSAGE EXAMPLE" "\n=============\n"; // Next, we set up an instance of this class to be the installed assertion // using 'AssertionTrackerSingleton'. Note that this needs to be done early in // 'main()' before any other handlers are installed. If another handler has // already been installed, a null pointer will be returned, and we assert that // this does not happen. //.. AssertionCounter *ac_p = balb::AssertionTrackerSingleton<AssertionCounter>::singleton(); ASSERT(ac_p); //.. // Finally, we will trigger some assertions and verify that we are counting // them correctly. //.. BSLS_ASSERT_ASSERT(0 && "assertion 1"); BSLS_ASSERT_ASSERT(0 && "assertion 2"); ASSERT(ac_p->getAssertionCount() == 2); //.. } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // This case exercises (but does not fully test) basic functionality. // // Concerns: //: 1 The class is sufficiently functional to install an assertion //: handler and process assertions. // // Plan: //: 1 Create a singleton 'AssertionTracker' object, trigger some //: assertions, and verify that they are noticed by having the //: assertion handler write them to a string stream and then //: examining the contents of the stream. // // Testing: // void failTracker(const char *, const char *, int); // TRACKER *singleton(bslma::Allocator * = 0); // -------------------------------------------------------------------- if (verbose) cout << "BREATHING TEST\n" "==============\n"; { bsl::ostringstream os; balb::AssertionTracker *at_p = Obj::singleton(); ASSERT(at_p); at_p->setReportingCallback( bdlf::BindUtil::bind(&balb::AssertionTracker::reportAssertion, &os, bdlf::PlaceHolders::_1, bdlf::PlaceHolders::_2, bdlf::PlaceHolders::_3, bdlf::PlaceHolders::_4, bdlf::PlaceHolders::_5)); os << "\n"; volatile int i, j; i = id_p(0); do { if (veryVeryVerbose) { P_(i) Q("assert 1") } trigger1_p(); j = id_p(0); do { if (veryVeryVerbose) { P_(i) P_(j) Q("assert 2") } trigger2_p(); j = id_p(j) + id_p(1); } while (id_p(j) < id_p(10)); i = id_p(i) + id_p(1); } while (id_p(i) < id_p(10)); i = id_p(0); do { if (veryVeryVerbose) { P_(i) Q("assert 3") } trigger3_p(); i = id_p(i) + id_p(1); } while (id_p(i) < id_p(2)); bsl::string s = os.str(); ASSERTV(s, s.npos != s.find(__FILE__)); ASSERTV(s, s.npos != s.find(":1:0 && \"assert 1\":")) ASSERTV(s, s.npos != s.find(":1:0 && \"assert 2\":")) ASSERTV(s, s.npos != s.find(":1:0 && \"assert 3\":")) os.str(""); at_p->reportAllStackTraces(); s = os.str(); #ifdef BSLS_PLATFORM_OS_WINDOWS // In some Windows builds the stack traces appear to be split, with // a each assertion appearing twice with different stack traces. I // have seen this with cl-18, while cl-19 seems to work properly. // For now, just test that the assertions show up at all. ASSERTV(s, s.npos != s.find(":0 && \"assert 1\":")) ASSERTV(s, s.npos != s.find(":0 && \"assert 2\":")) ASSERTV(s, s.npos != s.find(":0 && \"assert 3\":")) #else ASSERTV(s, s.npos != s.find(":10:0 && \"assert 1\":")) ASSERTV(s, s.npos != s.find(":100:0 && \"assert 2\":")) ASSERTV(s, s.npos != s.find(":2:0 && \"assert 3\":")) #endif } } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2017 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>Undo the volatile stuff which didn't help with Windows<commit_after>// balb_assertiontrackersingleton.t.cpp -*-C++-*- #include <balb_assertiontrackersingleton.h> #include <balb_assertiontracker.h> #include <bdlf_bind.h> #include <bdlf_placeholder.h> #include <bslim_testutil.h> #include <bslma_defaultallocatorguard.h> #include <bslma_testallocator.h> #include <bsl_cstdlib.h> #include <bsl_iostream.h> #include <bsl_sstream.h> #include <bsl_utility.h> using namespace BloombergLP; using namespace bsl; // automatically added by script // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // Test this thing. // ---------------------------------------------------------------------------- // CLASS METHODS // CREATORS // MANIPULATORS // ACCESSORS // ---------------------------------------------------------------------------- // [ 1] void failTracker(const char *, const char *, int); // [ 1] TRACKER *singleton(bslma::Allocator * = 0); // [ 2] USAGE EXAMPLE // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // GLOBAL TYPES, CONSTANTS, AND VARIABLES FOR TESTING // ---------------------------------------------------------------------------- typedef balb::AssertionTrackerSingleton<balb::AssertionTracker> Obj; ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Count Number of Assertions Triggered ///- - - - - - - - - - - - - - - - - - - - - - - - // We wish to count how many times assertions trigger, doing no other handling // and allowing the program to continue running (note that this is normally // forbidden in production). We can use 'AssertionTrackerSingleton' to set up // an assertion handler to do this. // // First, we create a class to do the counting. //.. class AssertionCounter { // PRIVATE DATA int d_assertion_counter; // Number of assertions seen. public: // PUBLIC CREATORS explicit AssertionCounter(bsls::Assert::Handler = 0, void * = 0); // Create an 'AssertionCounter' object. We ignore the fallback // handler and optional allocator parameters. // PUBLIC MANIPULATORS void operator()(const char *, const char *, int); // Function called when assertion failure occurs. We ignore the // text, file, and line parameters. // PUBLIC ACCESSORS int getAssertionCount() const; // Return the number of assertions we have seen. }; //.. // Then, we implement the member functions of the 'AssertionCounter' class. //.. AssertionCounter::AssertionCounter(bsls::Assert::Handler, void *) : d_assertion_counter(0) { } void AssertionCounter::operator()(const char *, const char *, int) { ++d_assertion_counter; } int AssertionCounter::getAssertionCount() const { return d_assertion_counter; } //.. // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = (argc > 1) ? atoi(argv[1]) : 1; bool verbose = (argc > 2); (void)verbose; bool veryVerbose = (argc > 3); (void)veryVerbose; bool veryVeryVerbose = (argc > 4); (void)veryVeryVerbose; bool veryVeryVeryVerbose = (argc > 5); (void)veryVeryVeryVerbose; cout << "TEST " << __FILE__ << " CASE " << test << endl; switch (test) { case 0: case 2: { // -------------------------------------------------------------------- // USAGE EXAMPLE // Extracted from component header file. // // Concerns: //: 1 The usage example provided in the component header file compiles, //: links, and runs as shown. // // Plan: //: 1 Incorporate usage example from header into test driver, remove //: leading comment characters, and replace 'assert' with 'ASSERT'. //: (C-1) // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << "\nUSAGE EXAMPLE" "\n=============\n"; // Next, we set up an instance of this class to be the installed assertion // using 'AssertionTrackerSingleton'. Note that this needs to be done early in // 'main()' before any other handlers are installed. If another handler has // already been installed, a null pointer will be returned, and we assert that // this does not happen. //.. AssertionCounter *ac_p = balb::AssertionTrackerSingleton<AssertionCounter>::singleton(); ASSERT(ac_p); //.. // Finally, we will trigger some assertions and verify that we are counting // them correctly. //.. BSLS_ASSERT_ASSERT(0 && "assertion 1"); BSLS_ASSERT_ASSERT(0 && "assertion 2"); ASSERT(ac_p->getAssertionCount() == 2); //.. } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // This case exercises (but does not fully test) basic functionality. // // Concerns: //: 1 The class is sufficiently functional to install an assertion //: handler and process assertions. // // Plan: //: 1 Create a singleton 'AssertionTracker' object, trigger some //: assertions, and verify that they are noticed by having the //: assertion handler write them to a string stream and then //: examining the contents of the stream. // // Testing: // void failTracker(const char *, const char *, int); // TRACKER *singleton(bslma::Allocator * = 0); // -------------------------------------------------------------------- if (verbose) cout << "BREATHING TEST\n" "==============\n"; { bsl::ostringstream os; balb::AssertionTracker *at_p = Obj::singleton(); ASSERT(at_p); at_p->setReportingCallback( bdlf::BindUtil::bind(&balb::AssertionTracker::reportAssertion, &os, bdlf::PlaceHolders::_1, bdlf::PlaceHolders::_2, bdlf::PlaceHolders::_3, bdlf::PlaceHolders::_4, bdlf::PlaceHolders::_5)); for (int i = 0; i < 10; ++i) { if (veryVeryVerbose) { P_(i) Q("assert 1") } BSLS_ASSERT_ASSERT(0 && "assert 1"); for (int j = 0; j < 10; ++j) { if (veryVeryVerbose) { P_(i) P_(j) Q("assert 2") } BSLS_ASSERT_ASSERT(0 && "assert 2"); } } for (int i = 0; i < 2; ++i) { if (veryVeryVerbose) { P_(i) Q("assert 3") } Obj::failTracker("0 && \"assert 3\"", __FILE__, __LINE__); } bsl::string s = os.str(); ASSERTV(s, s.npos != s.find(__FILE__)); ASSERTV(s, s.npos != s.find(":1:0 && \"assert 1\":")) ASSERTV(s, s.npos != s.find(":1:0 && \"assert 2\":")) ASSERTV(s, s.npos != s.find(":1:0 && \"assert 3\":")) os.str(""); at_p->reportAllStackTraces(); s = os.str(); #ifdef BSLS_PLATFORM_OS_WINDOWS // In some Windows builds the stack traces appear to be split, with // a each assertion appearing twice with different stack traces. I // have seen this with cl-18, while cl-19 seems to work properly. // For now, just test that the assertions show up at all. ASSERTV(s, s.npos != s.find(":0 && \"assert 1\":")) ASSERTV(s, s.npos != s.find(":0 && \"assert 2\":")) ASSERTV(s, s.npos != s.find(":0 && \"assert 3\":")) #else ASSERTV(s, s.npos != s.find(":10:0 && \"assert 1\":")) ASSERTV(s, s.npos != s.find(":100:0 && \"assert 2\":")) ASSERTV(s, s.npos != s.find(":2:0 && \"assert 3\":")) #endif } } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2017 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>//===--- NameBinding.cpp - Name Binding -----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements name binding for Swift. // //===----------------------------------------------------------------------===// #include "swift/Subsystems.h" #include "swift/AST/AST.h" #include "swift/AST/Component.h" #include "swift/AST/Diagnostics.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/system_error.h" #include "llvm/Support/Path.h" using namespace swift; //===----------------------------------------------------------------------===// // NameBinder //===----------------------------------------------------------------------===// typedef TranslationUnit::ImportedModule ImportedModule; typedef llvm::PointerUnion<const ImportedModule*, OneOfType*> BoundScope; namespace { class NameBinder { llvm::error_code findModule(StringRef Module, SourceLoc ImportLoc, llvm::OwningPtr<llvm::MemoryBuffer> &Buffer); public: TranslationUnit *TU; ASTContext &Context; NameBinder(TranslationUnit *TU) : TU(TU), Context(TU->Ctx) { } ~NameBinder() { } template<typename ...ArgTypes> InFlightDiagnostic diagnose(ArgTypes... Args) { return Context.Diags.diagnose(Args...); } void addImport(ImportDecl *ID, SmallVectorImpl<ImportedModule> &Result); BoundScope bindScopeName(TypeAliasDecl *TypeFromScope, Identifier Name, SourceLoc NameLoc); private: /// getModule - Load a module referenced by an import statement, /// emitting an error at the specified location and returning null on /// failure. Module *getModule(std::pair<Identifier,SourceLoc> ModuleID); }; } llvm::error_code NameBinder::findModule(StringRef Module, SourceLoc ImportLoc, llvm::OwningPtr<llvm::MemoryBuffer> &Buffer) { std::string ModuleFilename = Module.str() + std::string(".swift"); llvm::SmallString<128> InputFilename; // First, search in the directory corresponding to the import location. // FIXME: This screams for a proper FileManager abstraction. llvm::SourceMgr &SourceMgr = Context.SourceMgr; int CurrentBufferID = SourceMgr.FindBufferContainingLoc(ImportLoc.Value); if (CurrentBufferID >= 0) { const llvm::MemoryBuffer *ImportingBuffer = SourceMgr.getBufferInfo(CurrentBufferID).Buffer; StringRef CurrentDirectory = llvm::sys::path::parent_path(ImportingBuffer->getBufferIdentifier()); if (!CurrentDirectory.empty()) { InputFilename = CurrentDirectory; llvm::sys::path::append(InputFilename, ModuleFilename); llvm::error_code Err = llvm::MemoryBuffer::getFile(InputFilename, Buffer); if (!Err) return Err; } } // Second, search in the current directory. llvm::error_code Err = llvm::MemoryBuffer::getFile(ModuleFilename, Buffer); if (!Err) return Err; // If we fail, search each import search path. for (auto Path : Context.ImportSearchPaths) { InputFilename = Path; llvm::sys::path::append(InputFilename, ModuleFilename); Err = llvm::MemoryBuffer::getFile(InputFilename, Buffer); if (!Err) return Err; } return Err; } Module *NameBinder::getModule(std::pair<Identifier, SourceLoc> ModuleID) { // TODO: We currently just recursively parse referenced modules. This works // fine for now since they are each a single file. Ultimately we'll want a // compiled form of AST's like clang's that support lazy deserialization. // Open the input file. llvm::OwningPtr<llvm::MemoryBuffer> InputFile; if (llvm::error_code Err = findModule(ModuleID.first.str(), ModuleID.second, InputFile)) { diagnose(ModuleID.second, diag::sema_opening_import, ModuleID.first.str(), Err.message()); return 0; } unsigned BufferID = Context.SourceMgr.AddNewSourceBuffer(InputFile.take(), ModuleID.second.Value); // For now, treat all separate modules as unique components. Component *Comp = new (Context.Allocate<Component>(1)) Component(); // Parse the translation unit, but don't do name binding or type checking. // This can produce new errors etc if the input is erroneous. TranslationUnit *TU = parseTranslationUnit(BufferID, Comp, Context); if (TU == 0) return 0; // We have to do name binding on it to ensure that types are fully resolved. // This should eventually be eliminated by having actual fully resolved binary // dumps of the code instead of reparsing though. performNameBinding(TU); return TU; } void NameBinder::addImport(ImportDecl *ID, SmallVectorImpl<ImportedModule> &Result) { ArrayRef<ImportDecl::AccessPathElement> Path = ID->getAccessPath(); Module *M = getModule(Path[0]); if (M == 0) return; // FIXME: Validate the access path against the module. Reject things like // import swift.aslkdfja if (Path.size() > 2) { diagnose(Path[2].second, diag::invalid_declaration_imported); return; } Result.push_back(std::make_pair(Path.slice(1), M)); } /// Try to bind an unqualified name into something usable as a scope. BoundScope NameBinder::bindScopeName(TypeAliasDecl *TypeFromScope, Identifier Name, SourceLoc NameLoc) { // Check whether the "optimistic" type from scope is still // undefined. If not, use that as the actual type; otherwise we'll // need to do a lookup from the imports. TypeAliasDecl *Type; if (TypeFromScope->hasUnderlyingType()) { Type = TypeFromScope; } else { Type = TU->lookupGlobalType(Name, NLKind::UnqualifiedLookup); } // If that failed, look for a module name. if (!Type) { for (const ImportedModule &ImpEntry : TU->ImportedModules) if (ImpEntry.second->Name == Name) return &ImpEntry; diagnose(NameLoc, diag::no_module_or_type); return BoundScope(); } // Otherwise, at least cache the type we found. assert(Type->hasUnderlyingType()); if (!TypeFromScope->hasUnderlyingType()) { TypeFromScope->setUnderlyingType(Type->getUnderlyingType()); } // Try to convert that to a type scope. TypeBase *Ty = Type->getUnderlyingType()->getCanonicalType(); // Silently fail if we have an error type. if (isa<ErrorType>(Ty)) return BoundScope(); // Reject things like int::x. OneOfType *DT = dyn_cast<OneOfType>(Ty); if (DT == 0) { diagnose(NameLoc, diag::invalid_type_scoped_access, Name); return BoundScope(); } if (DT->Elements.empty()) { diagnose(NameLoc, diag::incomplete_or_empty_oneof, Name); return BoundScope(); } return DT; } //===----------------------------------------------------------------------===// // performNameBinding //===----------------------------------------------------------------------===// static Expr *BindNames(Expr *E, WalkOrder Order, NameBinder &Binder) { // Ignore the preorder walk. if (Order == WalkOrder::PreOrder) return E; Identifier Name; SourceLoc Loc; SmallVector<ValueDecl*, 4> Decls; // Process UnresolvedDeclRefExpr by doing an unqualified lookup. if (UnresolvedDeclRefExpr *UDRE = dyn_cast<UnresolvedDeclRefExpr>(E)) { Name = UDRE->getName(); Loc = UDRE->getLoc(); Binder.TU->lookupGlobalValue(Name, NLKind::UnqualifiedLookup, Decls); // Process UnresolvedScopedIdentifierExpr by doing a qualified lookup. } else if (UnresolvedScopedIdentifierExpr *USIE = dyn_cast<UnresolvedScopedIdentifierExpr>(E)) { Name = USIE->getName(); Loc = USIE->getNameLoc(); Identifier BaseName = USIE->getBaseName(); SourceLoc BaseNameLoc = USIE->getBaseNameLoc(); BoundScope Scope = Binder.bindScopeName(USIE->getBaseTypeFromScope(), BaseName, BaseNameLoc); if (!Scope) return nullptr; auto Module = Scope.get<const ImportedModule*>(); Module->second->lookupValue(Module->first, Name, NLKind::QualifiedLookup, Decls); // Otherwise, not something that needs name binding. } else { return E; } if (Decls.empty()) { Binder.diagnose(Loc, diag::use_unresolved_identifier, Name); return 0; } if (Decls.size() == 1) return new (Binder.Context) DeclRefExpr(Decls[0], Loc); // Copy the overload set into ASTContext memory. ArrayRef<ValueDecl*> DeclList = Binder.Context.AllocateCopy(Decls); return new (Binder.Context) OverloadSetRefExpr(DeclList, Loc); } static void bindNamesInDecl(Decl *D, WalkExprType ^BinderBlock) { if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { if (VD->getInit()) VD->setInit(VD->getInit()->walk(BinderBlock)); } else if (ExtensionDecl *ED = dyn_cast<ExtensionDecl>(D)) { for (Decl *Member : ED->getMembers()) { bindNamesInDecl(Member, BinderBlock); } } } /// performNameBinding - Once parsing is complete, this walks the AST to /// resolve names and do other top-level validation. /// /// At this parsing has been performed, but we still have UnresolvedDeclRefExpr /// nodes for unresolved value names, and we may have unresolved type names as /// well. This handles import directives and forward references. void swift::performNameBinding(TranslationUnit *TU) { NameBinder Binder(TU); SmallVector<ImportedModule, 8> ImportedModules; // Import the builtin library as an implicit import. // FIXME: This should only happen for translation units in the standard // library. ImportedModules.push_back(std::make_pair(Module::AccessPathTy(), TU->Ctx.TheBuiltinModule)); // FIXME: For translation units not in the standard library, we should import // swift.swift implicitly. We need a way for swift.swift itself to not // recursively import itself though. // Do a prepass over the declarations to find and load the imported modules. for (auto Elt : TU->Body->getElements()) if (Decl *D = Elt.dyn_cast<Decl*>()) { if (ImportDecl *ID = dyn_cast<ImportDecl>(D)) Binder.addImport(ID, ImportedModules); } TU->setImportedModules(TU->Ctx.AllocateCopy(ImportedModules)); // Type binding. Loop over all of the unresolved types in the translation // unit, resolving them with imports. for (TypeAliasDecl *TA : TU->getUnresolvedTypes()) { if (TypeAliasDecl *Result = Binder.TU->lookupGlobalType(TA->getName(), NLKind::UnqualifiedLookup)) { assert(!TA->hasUnderlyingType() && "Not an unresolved type"); // Update the decl we already have to be the correct type. TA->setTypeAliasLoc(Result->getTypeAliasLoc()); TA->setUnderlyingType(Result->getUnderlyingType()); continue; } Binder.diagnose(TA->getLocStart(), diag::use_undeclared_type, TA->getName()); TA->setUnderlyingType(ErrorType::get(TU->Ctx)); } // Loop over all the unresolved scoped types in the translation // unit, resolving them if possible. for (auto BaseAndType : TU->getUnresolvedScopedTypes()) { BoundScope Scope = Binder.bindScopeName(BaseAndType.first, BaseAndType.first->getName(), BaseAndType.first->getTypeAliasLoc()); if (!Scope) continue; Identifier Name = BaseAndType.second->getName(); SourceLoc NameLoc = BaseAndType.second->getTypeAliasLoc(); TypeAliasDecl *Alias = nullptr; if (auto Module = Scope.dyn_cast<const ImportedModule*>()) Alias = Module->second->lookupType(Module->first, Name, NLKind::QualifiedLookup); if (Alias) { BaseAndType.second->setUnderlyingType(Alias->getAliasType()); } else { Binder.diagnose(NameLoc, diag::invalid_member_type, Name, BaseAndType.first->getName()); BaseAndType.second->setUnderlyingType(Binder.Context.TheErrorType); } } NameBinder *NBPtr = &Binder; auto BinderBlock = ^(Expr *E, WalkOrder Order, WalkContext const&) { return BindNames(E, Order, *NBPtr); }; // Now that we know the top-level value names, go through and resolve any // UnresolvedDeclRefExprs that exist. for (unsigned i = 0, e = TU->Body->getNumElements(); i != e; ++i) { BraceStmt::ExprStmtOrDecl Elt = TU->Body->getElement(i); if (Decl *D = Elt.dyn_cast<Decl*>()) { bindNamesInDecl(D, BinderBlock); } else if (Stmt *S = Elt.dyn_cast<Stmt*>()) { Elt = S->walk(BinderBlock); } else { Elt = Elt.get<Expr*>()->walk(BinderBlock); } // Fill in null results with a dummy expression. if (Elt.isNull()) Elt = new (TU->Ctx) TupleExpr(SourceLoc(), 0, 0, 0, SourceLoc(), TypeJudgement(TupleType::getEmpty(TU->Ctx), ValueKind::RValue)); TU->Body->setElement(i, Elt); } TU->ASTStage = TranslationUnit::NameBound; verify(TU); } <commit_msg>implement support for normal lookup to find module names, and build a ModuleExpr of the right type to represent it. Not tested yet, because nothing can handle module exprs.<commit_after>//===--- NameBinding.cpp - Name Binding -----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements name binding for Swift. // //===----------------------------------------------------------------------===// #include "swift/Subsystems.h" #include "swift/AST/AST.h" #include "swift/AST/Component.h" #include "swift/AST/Diagnostics.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/system_error.h" #include "llvm/Support/Path.h" using namespace swift; //===----------------------------------------------------------------------===// // NameBinder //===----------------------------------------------------------------------===// typedef TranslationUnit::ImportedModule ImportedModule; typedef llvm::PointerUnion<const ImportedModule*, OneOfType*> BoundScope; namespace { class NameBinder { llvm::error_code findModule(StringRef Module, SourceLoc ImportLoc, llvm::OwningPtr<llvm::MemoryBuffer> &Buffer); public: TranslationUnit *TU; ASTContext &Context; NameBinder(TranslationUnit *TU) : TU(TU), Context(TU->Ctx) { } ~NameBinder() { } template<typename ...ArgTypes> InFlightDiagnostic diagnose(ArgTypes... Args) { return Context.Diags.diagnose(Args...); } void addImport(ImportDecl *ID, SmallVectorImpl<ImportedModule> &Result); BoundScope bindScopeName(TypeAliasDecl *TypeFromScope, Identifier Name, SourceLoc NameLoc); private: /// getModule - Load a module referenced by an import statement, /// emitting an error at the specified location and returning null on /// failure. Module *getModule(std::pair<Identifier,SourceLoc> ModuleID); }; } llvm::error_code NameBinder::findModule(StringRef Module, SourceLoc ImportLoc, llvm::OwningPtr<llvm::MemoryBuffer> &Buffer) { std::string ModuleFilename = Module.str() + std::string(".swift"); llvm::SmallString<128> InputFilename; // First, search in the directory corresponding to the import location. // FIXME: This screams for a proper FileManager abstraction. llvm::SourceMgr &SourceMgr = Context.SourceMgr; int CurrentBufferID = SourceMgr.FindBufferContainingLoc(ImportLoc.Value); if (CurrentBufferID >= 0) { const llvm::MemoryBuffer *ImportingBuffer = SourceMgr.getBufferInfo(CurrentBufferID).Buffer; StringRef CurrentDirectory = llvm::sys::path::parent_path(ImportingBuffer->getBufferIdentifier()); if (!CurrentDirectory.empty()) { InputFilename = CurrentDirectory; llvm::sys::path::append(InputFilename, ModuleFilename); llvm::error_code Err = llvm::MemoryBuffer::getFile(InputFilename, Buffer); if (!Err) return Err; } } // Second, search in the current directory. llvm::error_code Err = llvm::MemoryBuffer::getFile(ModuleFilename, Buffer); if (!Err) return Err; // If we fail, search each import search path. for (auto Path : Context.ImportSearchPaths) { InputFilename = Path; llvm::sys::path::append(InputFilename, ModuleFilename); Err = llvm::MemoryBuffer::getFile(InputFilename, Buffer); if (!Err) return Err; } return Err; } Module *NameBinder::getModule(std::pair<Identifier, SourceLoc> ModuleID) { // TODO: We currently just recursively parse referenced modules. This works // fine for now since they are each a single file. Ultimately we'll want a // compiled form of AST's like clang's that support lazy deserialization. // Open the input file. llvm::OwningPtr<llvm::MemoryBuffer> InputFile; if (llvm::error_code Err = findModule(ModuleID.first.str(), ModuleID.second, InputFile)) { diagnose(ModuleID.second, diag::sema_opening_import, ModuleID.first.str(), Err.message()); return 0; } unsigned BufferID = Context.SourceMgr.AddNewSourceBuffer(InputFile.take(), ModuleID.second.Value); // For now, treat all separate modules as unique components. Component *Comp = new (Context.Allocate<Component>(1)) Component(); // Parse the translation unit, but don't do name binding or type checking. // This can produce new errors etc if the input is erroneous. TranslationUnit *TU = parseTranslationUnit(BufferID, Comp, Context); if (TU == 0) return 0; // We have to do name binding on it to ensure that types are fully resolved. // This should eventually be eliminated by having actual fully resolved binary // dumps of the code instead of reparsing though. performNameBinding(TU); return TU; } void NameBinder::addImport(ImportDecl *ID, SmallVectorImpl<ImportedModule> &Result) { ArrayRef<ImportDecl::AccessPathElement> Path = ID->getAccessPath(); Module *M = getModule(Path[0]); if (M == 0) return; // FIXME: Validate the access path against the module. Reject things like // import swift.aslkdfja if (Path.size() > 2) { diagnose(Path[2].second, diag::invalid_declaration_imported); return; } Result.push_back(std::make_pair(Path.slice(1), M)); } /// Try to bind an unqualified name into something usable as a scope. BoundScope NameBinder::bindScopeName(TypeAliasDecl *TypeFromScope, Identifier Name, SourceLoc NameLoc) { // Check whether the "optimistic" type from scope is still // undefined. If not, use that as the actual type; otherwise we'll // need to do a lookup from the imports. TypeAliasDecl *Type; if (TypeFromScope->hasUnderlyingType()) { Type = TypeFromScope; } else { Type = TU->lookupGlobalType(Name, NLKind::UnqualifiedLookup); } // If that failed, look for a module name. if (!Type) { for (const ImportedModule &ImpEntry : TU->ImportedModules) if (ImpEntry.second->Name == Name) return &ImpEntry; diagnose(NameLoc, diag::no_module_or_type); return BoundScope(); } // Otherwise, at least cache the type we found. assert(Type->hasUnderlyingType()); if (!TypeFromScope->hasUnderlyingType()) { TypeFromScope->setUnderlyingType(Type->getUnderlyingType()); } // Try to convert that to a type scope. TypeBase *Ty = Type->getUnderlyingType()->getCanonicalType(); // Silently fail if we have an error type. if (isa<ErrorType>(Ty)) return BoundScope(); // Reject things like int::x. OneOfType *DT = dyn_cast<OneOfType>(Ty); if (DT == 0) { diagnose(NameLoc, diag::invalid_type_scoped_access, Name); return BoundScope(); } if (DT->Elements.empty()) { diagnose(NameLoc, diag::incomplete_or_empty_oneof, Name); return BoundScope(); } return DT; } //===----------------------------------------------------------------------===// // performNameBinding //===----------------------------------------------------------------------===// static Expr *BindNames(Expr *E, WalkOrder Order, NameBinder &Binder) { // Ignore the preorder walk. if (Order == WalkOrder::PreOrder) return E; Identifier Name; SourceLoc Loc; SmallVector<ValueDecl*, 4> Decls; // Process UnresolvedDeclRefExpr by doing an unqualified lookup. if (UnresolvedDeclRefExpr *UDRE = dyn_cast<UnresolvedDeclRefExpr>(E)) { Name = UDRE->getName(); Loc = UDRE->getLoc(); // Perform standard value name lookup. Binder.TU->lookupGlobalValue(Name, NLKind::UnqualifiedLookup, Decls); // If that fails, this may be the name of a module, try looking that up. if (Decls.empty()) { for (const ImportedModule &ImpEntry : Binder.TU->ImportedModules) if (ImpEntry.second->Name == Name) { ModuleType *MT = ModuleType::get(ImpEntry.second); return new (Binder.Context) ModuleExpr(Loc, TypeJudgement(MT, ValueKind::RValue)); } } // Process UnresolvedScopedIdentifierExpr by doing a qualified lookup. } else if (UnresolvedScopedIdentifierExpr *USIE = dyn_cast<UnresolvedScopedIdentifierExpr>(E)) { Name = USIE->getName(); Loc = USIE->getNameLoc(); Identifier BaseName = USIE->getBaseName(); SourceLoc BaseNameLoc = USIE->getBaseNameLoc(); BoundScope Scope = Binder.bindScopeName(USIE->getBaseTypeFromScope(), BaseName, BaseNameLoc); if (!Scope) return nullptr; auto Module = Scope.get<const ImportedModule*>(); Module->second->lookupValue(Module->first, Name, NLKind::QualifiedLookup, Decls); // Otherwise, not something that needs name binding. } else { return E; } if (Decls.empty()) { Binder.diagnose(Loc, diag::use_unresolved_identifier, Name); return 0; } if (Decls.size() == 1) return new (Binder.Context) DeclRefExpr(Decls[0], Loc); // Copy the overload set into ASTContext memory. ArrayRef<ValueDecl*> DeclList = Binder.Context.AllocateCopy(Decls); return new (Binder.Context) OverloadSetRefExpr(DeclList, Loc); } static void bindNamesInDecl(Decl *D, WalkExprType ^BinderBlock) { if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { if (VD->getInit()) VD->setInit(VD->getInit()->walk(BinderBlock)); } else if (ExtensionDecl *ED = dyn_cast<ExtensionDecl>(D)) { for (Decl *Member : ED->getMembers()) { bindNamesInDecl(Member, BinderBlock); } } } /// performNameBinding - Once parsing is complete, this walks the AST to /// resolve names and do other top-level validation. /// /// At this parsing has been performed, but we still have UnresolvedDeclRefExpr /// nodes for unresolved value names, and we may have unresolved type names as /// well. This handles import directives and forward references. void swift::performNameBinding(TranslationUnit *TU) { NameBinder Binder(TU); SmallVector<ImportedModule, 8> ImportedModules; // Import the builtin library as an implicit import. // FIXME: This should only happen for translation units in the standard // library. ImportedModules.push_back(std::make_pair(Module::AccessPathTy(), TU->Ctx.TheBuiltinModule)); // FIXME: For translation units not in the standard library, we should import // swift.swift implicitly. We need a way for swift.swift itself to not // recursively import itself though. // Do a prepass over the declarations to find and load the imported modules. for (auto Elt : TU->Body->getElements()) if (Decl *D = Elt.dyn_cast<Decl*>()) { if (ImportDecl *ID = dyn_cast<ImportDecl>(D)) Binder.addImport(ID, ImportedModules); } TU->setImportedModules(TU->Ctx.AllocateCopy(ImportedModules)); // Type binding. Loop over all of the unresolved types in the translation // unit, resolving them with imports. for (TypeAliasDecl *TA : TU->getUnresolvedTypes()) { if (TypeAliasDecl *Result = Binder.TU->lookupGlobalType(TA->getName(), NLKind::UnqualifiedLookup)) { assert(!TA->hasUnderlyingType() && "Not an unresolved type"); // Update the decl we already have to be the correct type. TA->setTypeAliasLoc(Result->getTypeAliasLoc()); TA->setUnderlyingType(Result->getUnderlyingType()); continue; } Binder.diagnose(TA->getLocStart(), diag::use_undeclared_type, TA->getName()); TA->setUnderlyingType(ErrorType::get(TU->Ctx)); } // Loop over all the unresolved scoped types in the translation // unit, resolving them if possible. for (auto BaseAndType : TU->getUnresolvedScopedTypes()) { BoundScope Scope = Binder.bindScopeName(BaseAndType.first, BaseAndType.first->getName(), BaseAndType.first->getTypeAliasLoc()); if (!Scope) continue; Identifier Name = BaseAndType.second->getName(); SourceLoc NameLoc = BaseAndType.second->getTypeAliasLoc(); TypeAliasDecl *Alias = nullptr; if (auto Module = Scope.dyn_cast<const ImportedModule*>()) Alias = Module->second->lookupType(Module->first, Name, NLKind::QualifiedLookup); if (Alias) { BaseAndType.second->setUnderlyingType(Alias->getAliasType()); } else { Binder.diagnose(NameLoc, diag::invalid_member_type, Name, BaseAndType.first->getName()); BaseAndType.second->setUnderlyingType(Binder.Context.TheErrorType); } } NameBinder *NBPtr = &Binder; auto BinderBlock = ^(Expr *E, WalkOrder Order, WalkContext const&) { return BindNames(E, Order, *NBPtr); }; // Now that we know the top-level value names, go through and resolve any // UnresolvedDeclRefExprs that exist. for (unsigned i = 0, e = TU->Body->getNumElements(); i != e; ++i) { BraceStmt::ExprStmtOrDecl Elt = TU->Body->getElement(i); if (Decl *D = Elt.dyn_cast<Decl*>()) { bindNamesInDecl(D, BinderBlock); } else if (Stmt *S = Elt.dyn_cast<Stmt*>()) { Elt = S->walk(BinderBlock); } else { Elt = Elt.get<Expr*>()->walk(BinderBlock); } // Fill in null results with a dummy expression. if (Elt.isNull()) Elt = new (TU->Ctx) TupleExpr(SourceLoc(), 0, 0, 0, SourceLoc(), TypeJudgement(TupleType::getEmpty(TU->Ctx), ValueKind::RValue)); TU->Body->setElement(i, Elt); } TU->ASTStage = TranslationUnit::NameBound; verify(TU); } <|endoftext|>
<commit_before>// // $Id$ // #include "AVGImage.h" #include "IAVGDisplayEngine.h" #include "AVGPlayer.h" #include "AVGLogger.h" #include "IAVGSurface.h" #include <paintlib/plbitmap.h> #include <paintlib/planybmp.h> #include <paintlib/plpngenc.h> #include <paintlib/planydec.h> #include <paintlib/Filter/plfilterresizebilinear.h> #include <paintlib/Filter/plfilterfliprgb.h> #include <paintlib/Filter/plfilterfill.h> #include <nsMemory.h> #include <xpcom/nsComponentManagerUtils.h> #include <iostream> #include <sstream> using namespace std; NS_IMPL_ISUPPORTS1_CI(AVGImage, IAVGNode); AVGImage * AVGImage::create() { return createNode<AVGImage>("@c-base.org/avgimage;1"); } AVGImage::AVGImage () : m_pSurface(0) { NS_INIT_ISUPPORTS(); } AVGImage::~AVGImage () { if (m_pSurface) { delete m_pSurface; } } NS_IMETHODIMP AVGImage::GetType(PRInt32 *_retval) { *_retval = NT_IMAGE; return NS_OK; } void AVGImage::init (const std::string& id, const std::string& filename, int bpp, IAVGDisplayEngine * pEngine, AVGContainer * pParent, AVGPlayer * pPlayer) { AVGNode::init(id, pEngine, pParent, pPlayer); m_Filename = filename; AVG_TRACE(AVGPlayer::DEBUG_PROFILE, "Loading " << m_Filename); m_pSurface = getEngine()->createSurface(); PLAnyPicDecoder decoder; PLAnyBmp TempBmp; // TODO: Decode directly to surface using PLPicDec::GetImage(); decoder.MakeBmpFromFile(m_Filename.c_str(), &TempBmp, 32); if (!pEngine->hasRGBOrdering()) { TempBmp.ApplyFilter(PLFilterFlipRGB()); } int DestBPP = bpp; if (!pEngine->supportsBpp(bpp)) { DestBPP = 32; } m_pSurface->create(TempBmp.GetWidth(), TempBmp.GetHeight(), DestBPP, TempBmp.HasAlpha()); PLPixel32** ppSrcLines = TempBmp.GetLineArray32(); PLBmpBase * pDestBmp = m_pSurface->getBmp(); PLPixel32** ppDestLines = pDestBmp->GetLineArray32(); for (int y=0; y<TempBmp.GetHeight(); y++) { memcpy (ppDestLines[y], ppSrcLines[y], TempBmp.GetWidth()*4); } getEngine()->surfaceChanged(m_pSurface); } void AVGImage::render (const AVGDRect& Rect) { getEngine()->blt32(m_pSurface, &getAbsViewport(), getEffectiveOpacity(), getAngle(), getPivot()); } bool AVGImage::obscures (const AVGDRect& Rect, int z) { return (getEffectiveOpacity() > 0.999 && !m_pSurface->getBmp()->HasAlpha() && getZ() > z && getVisibleRect().Contains(Rect)); } string AVGImage::getTypeStr () { return "AVGImage"; } AVGDPoint AVGImage::getPreferredMediaSize() { return AVGDPoint(m_pSurface->getBmp()->GetSize()); } <commit_msg>Refactored to use CopyPixels()<commit_after>// // $Id$ // #include "AVGImage.h" #include "IAVGDisplayEngine.h" #include "AVGPlayer.h" #include "AVGLogger.h" #include "IAVGSurface.h" #include <paintlib/plbitmap.h> #include <paintlib/planybmp.h> #include <paintlib/plpngenc.h> #include <paintlib/planydec.h> #include <paintlib/Filter/plfilterresizebilinear.h> #include <paintlib/Filter/plfilterfliprgb.h> #include <paintlib/Filter/plfilterfill.h> #include <nsMemory.h> #include <xpcom/nsComponentManagerUtils.h> #include <iostream> #include <sstream> using namespace std; NS_IMPL_ISUPPORTS1_CI(AVGImage, IAVGNode); AVGImage * AVGImage::create() { return createNode<AVGImage>("@c-base.org/avgimage;1"); } AVGImage::AVGImage () : m_pSurface(0) { NS_INIT_ISUPPORTS(); } AVGImage::~AVGImage () { if (m_pSurface) { delete m_pSurface; } } NS_IMETHODIMP AVGImage::GetType(PRInt32 *_retval) { *_retval = NT_IMAGE; return NS_OK; } void AVGImage::init (const std::string& id, const std::string& filename, int bpp, IAVGDisplayEngine * pEngine, AVGContainer * pParent, AVGPlayer * pPlayer) { AVGNode::init(id, pEngine, pParent, pPlayer); m_Filename = filename; AVG_TRACE(AVGPlayer::DEBUG_PROFILE, "Loading " << m_Filename); m_pSurface = getEngine()->createSurface(); PLAnyPicDecoder decoder; PLAnyBmp TempBmp; decoder.MakeBmpFromFile(m_Filename.c_str(), &TempBmp, 32); if (!pEngine->hasRGBOrdering()) { TempBmp.ApplyFilter(PLFilterFlipRGB()); } int DestBPP = bpp; if (!pEngine->supportsBpp(bpp)) { DestBPP = 32; } m_pSurface->create(TempBmp.GetWidth(), TempBmp.GetHeight(), DestBPP, TempBmp.HasAlpha()); m_pSurface->getBmp()->CopyPixels(TempBmp); getEngine()->surfaceChanged(m_pSurface); } void AVGImage::render (const AVGDRect& Rect) { getEngine()->blt32(m_pSurface, &getAbsViewport(), getEffectiveOpacity(), getAngle(), getPivot()); } bool AVGImage::obscures (const AVGDRect& Rect, int z) { return (getEffectiveOpacity() > 0.999 && !m_pSurface->getBmp()->HasAlpha() && getZ() > z && getVisibleRect().Contains(Rect)); } string AVGImage::getTypeStr () { return "AVGImage"; } AVGDPoint AVGImage::getPreferredMediaSize() { return AVGDPoint(m_pSurface->getBmp()->GetSize()); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 SeNDA * * 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 NeighbourTable.cpp * AUTHOR Blackcatn13 * DATE Jun 29, 2015 * VERSION 1 * This file contains the implementation of the Neighbour class. */ #include "Node/Neighbour/NeighbourTable.h" #include <string> #include <cstdint> #include <map> #include <mutex> #include "Node/Neighbour/Neighbour.h" NeighbourTable *NeighbourTable::m_instance = 0; NeighbourTable::NeighbourTable() { } NeighbourTable::~NeighbourTable() { } NeighbourTable* NeighbourTable::getInstance() { if (m_instance == 0) { m_instance = new NeighbourTable(); } return m_instance; } void NeighbourTable::update(const std::string &nodeId, const std::string &nodeAddress, const uint16_t &nodePort) { mutex.lock(); std::map<std::string, std::shared_ptr<Neighbour>>::iterator it = m_neighbours .find(nodeId); if (it != m_neighbours.end()) { if (m_neighbours[nodeId]->m_nodeAddress != nodeAddress) m_neighbours[nodeId]->m_nodeAddress = nodeAddress; if (m_neighbours[nodeId]->m_nodePort != nodePort) m_neighbours[nodeId]->m_nodePort = nodePort; } else { m_neighbours[nodeId] = std::make_shared<Neighbour>(nodeId, nodeAddress, nodePort); } mutex.unlock(); } void NeighbourTable::cleanNeighbours(int expirationTime) { mutex.lock(); for (std::map<std::string, std::shared_ptr<Neighbour>>::iterator it = m_neighbours.begin(); it != m_neighbours.end(); ++it) { if ((*it).second->getElapsedActivityTime() >= expirationTime) { m_neighbours.erase(it); } } mutex.unlock(); } void NeighbourTable::getNeighbours( std::map<std::string, std::shared_ptr<Neighbour>> *map) { mutex.lock(); (*map).insert(m_neighbours.begin(), m_neighbours.end()); mutex.unlock(); } <commit_msg>Fixes not updating neighbour activity time.<commit_after>/* * Copyright (c) 2015 SeNDA * * 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 NeighbourTable.cpp * AUTHOR Blackcatn13 * DATE Jun 29, 2015 * VERSION 1 * This file contains the implementation of the Neighbour class. */ #include "Node/Neighbour/NeighbourTable.h" #include <string> #include <cstdint> #include <map> #include <mutex> #include "Node/Neighbour/Neighbour.h" NeighbourTable *NeighbourTable::m_instance = 0; NeighbourTable::NeighbourTable() { } NeighbourTable::~NeighbourTable() { } NeighbourTable* NeighbourTable::getInstance() { if (m_instance == 0) { m_instance = new NeighbourTable(); } return m_instance; } void NeighbourTable::update(const std::string &nodeId, const std::string &nodeAddress, const uint16_t &nodePort) { mutex.lock(); std::map<std::string, std::shared_ptr<Neighbour>>::iterator it = m_neighbours .find(nodeId); if (it != m_neighbours.end()) { if (m_neighbours[nodeId]->m_nodeAddress != nodeAddress) m_neighbours[nodeId]->m_nodeAddress = nodeAddress; if (m_neighbours[nodeId]->m_nodePort != nodePort) m_neighbours[nodeId]->m_nodePort = nodePort; m_neighbours[nodeId]->Update(); } else { m_neighbours[nodeId] = std::make_shared<Neighbour>(nodeId, nodeAddress, nodePort); } mutex.unlock(); } void NeighbourTable::cleanNeighbours(int expirationTime) { mutex.lock(); for (std::map<std::string, std::shared_ptr<Neighbour>>::iterator it = m_neighbours.begin(); it != m_neighbours.end(); ++it) { if ((*it).second->getElapsedActivityTime() >= expirationTime) { m_neighbours.erase(it); } } mutex.unlock(); } void NeighbourTable::getNeighbours( std::map<std::string, std::shared_ptr<Neighbour>> *map) { mutex.lock(); (*map).insert(m_neighbours.begin(), m_neighbours.end()); mutex.unlock(); } <|endoftext|>
<commit_before>// Time: O(nlogn) // Space: O(n) // BIT solution. (281ms) class Solution { public: /** * @param A: An integer array * @return: Count the number of element before this element 'ai' is * smaller than it and return count number array */ vector<int> countOfSmallerNumberII(vector<int> &A) { vector<int> sorted_A(A), orderings(A.size()); sort(sorted_A.begin(), sorted_A.end()); for (int i = 0; i < A.size(); ++i) { orderings[i] = lower_bound(sorted_A.begin(), sorted_A.end(), A[i]) - sorted_A.begin(); } vector<int> bit(A.size() + 1), ans(A.size()); for (int i = 0; i < A.size(); ++i) { ans[i] = query(bit, orderings[i]); add(bit, orderings[i] + 1, 1); } return ans; } private: void add(vector<int>& bit, int i, int val) { for (; i < bit.size(); i += lower_bit(i)) { bit[i] += val; } } int query(const vector<int>& bit, int i) { int sum = 0; for (; i > 0; i -= lower_bit(i)) { sum += bit[i]; } return sum; } int lower_bit(int i) { return i & -i; } }; // Time: O(nlogn) // Space: O(n) // BST solution. (743ms) class Solution2 { public: class BSTreeNode { public: int val, count; BSTreeNode *left, *right; BSTreeNode(int val, int count) { this->val = val; this->count = count; this->left = this->right = nullptr; } }; /** * @param A: An integer array * @return: Count the number of element before this element 'ai' is * smaller than it and return count number array */ vector<int> countOfSmallerNumberII(vector<int> &A) { vector<int> res; BSTreeNode *root = nullptr; // Insert into BST and get left count. for (int i = 0; i < A.size(); ++i) { int count = 0; BSTreeNode *node = new BSTreeNode(A[i], 0); root = insertNode(root, node); count = query(root, A[i]); res.emplace_back(count); } return res; } // Insert node into BST. BSTreeNode* insertNode(BSTreeNode* root, BSTreeNode* node) { if (root == nullptr) { return node; } BSTreeNode* curr = root; while (curr) { // Insert left if smaller. if (node->val < curr->val) { ++curr->count; // Increase the number of left children. if (curr->left != nullptr) { curr = curr->left; } else { curr->left = node; break; } } else { // Insert right if larger or equal. if (curr->right != nullptr) { curr = curr->right; } else { curr->right = node; break; } } } return root; } // Query the smaller count of the value. int query(BSTreeNode* root, int val) { if (root == nullptr) { return 0; } int count = 0; BSTreeNode* curr = root; while (curr) { // Insert left. if (val < curr->val) { curr = curr->left; } else if (val > curr->val) { count += 1 + curr->count; // Count the number of the smaller nodes. curr = curr->right; } else { // Equal. return count + curr->count; } } return 0; } }; <commit_msg>Update count-of-smaller-number-before-itself.cpp<commit_after>// Time: O(nlogn) // Space: O(n) // BIT solution. (281ms) class Solution { public: /** * @param A: An integer array * @return: Count the number of element before this element 'ai' is * smaller than it and return count number array */ vector<int> countOfSmallerNumberII(vector<int> &A) { // Get the place (position in the ascending order) of each number. vector<int> sorted_A(A), places(A.size()); sort(sorted_A.begin(), sorted_A.end()); for (int i = 0; i < A.size(); ++i) { places[i] = lower_bound(sorted_A.begin(), sorted_A.end(), A[i]) - sorted_A.begin(); } // Count the smaller elements before the number. vector<int> bit(A.size() + 1), ans(A.size()); for (int i = 0; i < A.size(); ++i) { ans[i] = query(bit, places[i]); add(bit, places[i] + 1, 1); } return ans; } private: void add(vector<int>& bit, int i, int val) { for (; i < bit.size(); i += lower_bit(i)) { bit[i] += val; } } int query(const vector<int>& bit, int i) { int sum = 0; for (; i > 0; i -= lower_bit(i)) { sum += bit[i]; } return sum; } int lower_bit(int i) { return i & -i; } }; // Time: O(nlogn) // Space: O(n) // BST solution. (743ms) class Solution2 { public: class BSTreeNode { public: int val, count; BSTreeNode *left, *right; BSTreeNode(int val, int count) { this->val = val; this->count = count; this->left = this->right = nullptr; } }; /** * @param A: An integer array * @return: Count the number of element before this element 'ai' is * smaller than it and return count number array */ vector<int> countOfSmallerNumberII(vector<int> &A) { vector<int> res; BSTreeNode *root = nullptr; // Insert into BST and get left count. for (int i = 0; i < A.size(); ++i) { int count = 0; BSTreeNode *node = new BSTreeNode(A[i], 0); root = insertNode(root, node); count = query(root, A[i]); res.emplace_back(count); } return res; } // Insert node into BST. BSTreeNode* insertNode(BSTreeNode* root, BSTreeNode* node) { if (root == nullptr) { return node; } BSTreeNode* curr = root; while (curr) { // Insert left if smaller. if (node->val < curr->val) { ++curr->count; // Increase the number of left children. if (curr->left != nullptr) { curr = curr->left; } else { curr->left = node; break; } } else { // Insert right if larger or equal. if (curr->right != nullptr) { curr = curr->right; } else { curr->right = node; break; } } } return root; } // Query the smaller count of the value. int query(BSTreeNode* root, int val) { if (root == nullptr) { return 0; } int count = 0; BSTreeNode* curr = root; while (curr) { // Insert left. if (val < curr->val) { curr = curr->left; } else if (val > curr->val) { count += 1 + curr->count; // Count the number of the smaller nodes. curr = curr->right; } else { // Equal. return count + curr->count; } } return 0; } }; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textconversion_zh.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: kz $ $Date: 2006-11-06 14:41:02 $ * * 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_i18npool.hxx" #include <assert.h> #include <textconversion.hxx> #include <com/sun/star/i18n/TextConversionType.hpp> #include <com/sun/star/i18n/TextConversionOption.hpp> #include <com/sun/star/linguistic2/ConversionDirection.hpp> #include <com/sun/star/linguistic2/ConversionDictionaryType.hpp> #include <i18nutil/x_rtl_ustring.h> using namespace com::sun::star::lang; using namespace com::sun::star::i18n; using namespace com::sun::star::linguistic2; using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { TextConversion_zh::TextConversion_zh( const Reference < XMultiServiceFactory >& xMSF ) { Reference < XInterface > xI; xI = xMSF->createInstance( OUString::createFromAscii( "com.sun.star.linguistic2.ConversionDictionaryList" )); if ( xI.is() ) xI->queryInterface( getCppuType((const Reference< XConversionDictionaryList>*)0) ) >>= xCDL; implementationName = "com.sun.star.i18n.TextConversion_zh"; } sal_Unicode SAL_CALL getOneCharConversion(sal_Unicode ch, const sal_Unicode* Data, const sal_uInt16* Index) { if (Data && Index) { sal_Unicode address = Index[ch>>8]; if (address != 0xFFFF) address = Data[address + (ch & 0xFF)]; return (address != 0xFFFF) ? address : ch; } else { return ch; } } OUString SAL_CALL TextConversion_zh::getCharConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions) { const sal_Unicode *Data; const sal_uInt16 *Index; if (toSChinese) { Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_T2S"))(); Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_T2S"))(); } else if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) { Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2V"))(); Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2V"))(); } else { Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2T"))(); Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2T"))(); } rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength ); // defined in x_rtl_ustring.h for (sal_Int32 i = 0; i < nLength; i++) newStr->buffer[i] = getOneCharConversion(aText[nStartPos+i], Data, Index); return OUString( newStr->buffer, nLength); } OUString SAL_CALL TextConversion_zh::getWordConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset) { sal_Int32 dictLen = 0; sal_Int32 maxLen = 0; const sal_uInt16 *index; const sal_uInt16 *entry; const sal_Unicode *charData; const sal_uInt16 *charIndex; sal_Bool one2one=sal_True; const sal_Unicode *wordData = ((const sal_Unicode* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordData"))(dictLen); if (toSChinese) { index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_T2S"))(maxLen); entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_T2S"))(); charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_T2S"))(); charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_T2S"))(); } else { index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_S2T"))(maxLen); entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_S2T"))(); if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) { charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2V"))(); charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2V"))(); } else { charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2T"))(); charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2T"))(); } } if ((!wordData || !index || !entry) && !xCDL.is()) // no word mapping defined, do char2char conversion. return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions); rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength * 2 ); // defined in x_rtl_ustring.h sal_Int32 currPos = 0, count = 0; while (currPos < nLength) { sal_Int32 len = nLength - currPos; sal_Bool found = sal_False; if (len > maxLen) len = maxLen; for (; len > 0 && ! found; len--) { OUString word = aText.copy(nStartPos + currPos, len); sal_Int32 current = 0; // user dictionary if (xCDL.is()) { Sequence < OUString > conversions; try { conversions = xCDL->queryConversions(word, 0, len, aLocale, ConversionDictionaryType::SCHINESE_TCHINESE, /*toSChinese ?*/ ConversionDirection_FROM_LEFT /*: ConversionDirection_FROM_RIGHT*/, nConversionOptions); } catch ( NoSupportException & ) { // clear reference (when there is no user dictionary) in order // to not always have to catch this exception again // in further calls. (save time) xCDL = 0; } catch (...) { // catch all other exceptions to allow // querying the system dictionary in the next line } if (conversions.getLength() > 0) { if (offset.getLength() > 0) { if (word.getLength() != conversions[0].getLength()) one2one=sal_False; while (current < conversions[0].getLength()) { offset[count] = nStartPos + currPos + (current * word.getLength() / conversions[0].getLength()); newStr->buffer[count++] = conversions[0][current++]; } // offset[count-1] = nStartPos + currPos + word.getLength() - 1; } else { while (current < conversions[0].getLength()) newStr->buffer[count++] = conversions[0][current++]; } currPos += word.getLength(); found = sal_True; } } if (!found && index[len+1] - index[len] > 0) { sal_Int32 bottom = (sal_Int32) index[len]; sal_Int32 top = (sal_Int32) index[len+1] - 1; while (bottom <= top && !found) { current = (top + bottom) / 2; const sal_Int32 result = word.compareTo(wordData + entry[current]); if (result < 0) top = current - 1; else if (result > 0) bottom = current + 1; else { if (toSChinese) // Traditionary/Simplified conversion, for (current = entry[current]-1; current > 0 && wordData[current-1]; current--); else // Simplified/Traditionary conversion, forwards search for next word current = entry[current] + word.getLength() + 1; sal_Int32 start=current; if (offset.getLength() > 0) { if (word.getLength() != OUString(&wordData[current]).getLength()) one2one=sal_False; sal_Int32 convertedLength=OUString(&wordData[current]).getLength(); while (wordData[current]) { offset[count]=nStartPos + currPos + ((current-start) * word.getLength() / convertedLength); newStr->buffer[count++] = wordData[current++]; } // offset[count-1]=nStartPos + currPos + word.getLength() - 1; } else { while (wordData[current]) newStr->buffer[count++] = wordData[current++]; } currPos += word.getLength(); found = sal_True; } } } } if (!found) { if (offset.getLength() > 0) offset[count]=nStartPos+currPos; newStr->buffer[count++] = getOneCharConversion(aText[nStartPos+currPos], charData, charIndex); currPos++; } } if (offset.getLength() > 0) offset.realloc(one2one ? 0 : count); return OUString( newStr->buffer, count); } TextConversionResult SAL_CALL TextConversion_zh::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions) throw( RuntimeException, IllegalArgumentException, NoSupportException ) { TextConversionResult result; result.Candidates.realloc(1); result.Candidates[0] = getConversion( aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions); result.Boundary.startPos = nStartPos; result.Boundary.endPos = nStartPos + nLength; return result; } OUString SAL_CALL TextConversion_zh::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions) throw( RuntimeException, IllegalArgumentException, NoSupportException ) { if (rLocale.Language.equalsAscii("zh") && ( nConversionType == TextConversionType::TO_SCHINESE || nConversionType == TextConversionType::TO_TCHINESE) ) { aLocale=rLocale; sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE; if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) // char to char dictionary return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions); else { Sequence <sal_Int32> offset; // word to word dictionary return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset); } } else throw NoSupportException(); // Conversion type is not supported in this service. } OUString SAL_CALL TextConversion_zh::getConversionWithOffset( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset) throw( RuntimeException, IllegalArgumentException, NoSupportException ) { if (rLocale.Language.equalsAscii("zh") && ( nConversionType == TextConversionType::TO_SCHINESE || nConversionType == TextConversionType::TO_TCHINESE) ) { aLocale=rLocale; sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE; if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) { offset.realloc(0); // char to char dictionary return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions); } else { if (offset.getLength() < 2*nLength) offset.realloc(2*nLength); // word to word dictionary return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset); } } else throw NoSupportException(); // Conversion type is not supported in this service. } sal_Bool SAL_CALL TextConversion_zh::interactiveConversion( const Locale& /*rLocale*/, sal_Int16 /*nTextConversionType*/, sal_Int32 /*nTextConversionOptions*/ ) throw( RuntimeException, IllegalArgumentException, NoSupportException ) { return sal_False; } } } } } <commit_msg>INTEGRATION: CWS changefileheader (1.10.112); FILE MERGED 2008/03/31 16:01:30 rt 1.10.112.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: textconversion_zh.cxx,v $ * $Revision: 1.11 $ * * 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_i18npool.hxx" #include <assert.h> #include <textconversion.hxx> #include <com/sun/star/i18n/TextConversionType.hpp> #include <com/sun/star/i18n/TextConversionOption.hpp> #include <com/sun/star/linguistic2/ConversionDirection.hpp> #include <com/sun/star/linguistic2/ConversionDictionaryType.hpp> #include <i18nutil/x_rtl_ustring.h> using namespace com::sun::star::lang; using namespace com::sun::star::i18n; using namespace com::sun::star::linguistic2; using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { TextConversion_zh::TextConversion_zh( const Reference < XMultiServiceFactory >& xMSF ) { Reference < XInterface > xI; xI = xMSF->createInstance( OUString::createFromAscii( "com.sun.star.linguistic2.ConversionDictionaryList" )); if ( xI.is() ) xI->queryInterface( getCppuType((const Reference< XConversionDictionaryList>*)0) ) >>= xCDL; implementationName = "com.sun.star.i18n.TextConversion_zh"; } sal_Unicode SAL_CALL getOneCharConversion(sal_Unicode ch, const sal_Unicode* Data, const sal_uInt16* Index) { if (Data && Index) { sal_Unicode address = Index[ch>>8]; if (address != 0xFFFF) address = Data[address + (ch & 0xFF)]; return (address != 0xFFFF) ? address : ch; } else { return ch; } } OUString SAL_CALL TextConversion_zh::getCharConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions) { const sal_Unicode *Data; const sal_uInt16 *Index; if (toSChinese) { Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_T2S"))(); Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_T2S"))(); } else if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) { Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2V"))(); Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2V"))(); } else { Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2T"))(); Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2T"))(); } rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength ); // defined in x_rtl_ustring.h for (sal_Int32 i = 0; i < nLength; i++) newStr->buffer[i] = getOneCharConversion(aText[nStartPos+i], Data, Index); return OUString( newStr->buffer, nLength); } OUString SAL_CALL TextConversion_zh::getWordConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset) { sal_Int32 dictLen = 0; sal_Int32 maxLen = 0; const sal_uInt16 *index; const sal_uInt16 *entry; const sal_Unicode *charData; const sal_uInt16 *charIndex; sal_Bool one2one=sal_True; const sal_Unicode *wordData = ((const sal_Unicode* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordData"))(dictLen); if (toSChinese) { index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_T2S"))(maxLen); entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_T2S"))(); charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_T2S"))(); charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_T2S"))(); } else { index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_S2T"))(maxLen); entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_S2T"))(); if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) { charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2V"))(); charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2V"))(); } else { charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2T"))(); charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2T"))(); } } if ((!wordData || !index || !entry) && !xCDL.is()) // no word mapping defined, do char2char conversion. return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions); rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength * 2 ); // defined in x_rtl_ustring.h sal_Int32 currPos = 0, count = 0; while (currPos < nLength) { sal_Int32 len = nLength - currPos; sal_Bool found = sal_False; if (len > maxLen) len = maxLen; for (; len > 0 && ! found; len--) { OUString word = aText.copy(nStartPos + currPos, len); sal_Int32 current = 0; // user dictionary if (xCDL.is()) { Sequence < OUString > conversions; try { conversions = xCDL->queryConversions(word, 0, len, aLocale, ConversionDictionaryType::SCHINESE_TCHINESE, /*toSChinese ?*/ ConversionDirection_FROM_LEFT /*: ConversionDirection_FROM_RIGHT*/, nConversionOptions); } catch ( NoSupportException & ) { // clear reference (when there is no user dictionary) in order // to not always have to catch this exception again // in further calls. (save time) xCDL = 0; } catch (...) { // catch all other exceptions to allow // querying the system dictionary in the next line } if (conversions.getLength() > 0) { if (offset.getLength() > 0) { if (word.getLength() != conversions[0].getLength()) one2one=sal_False; while (current < conversions[0].getLength()) { offset[count] = nStartPos + currPos + (current * word.getLength() / conversions[0].getLength()); newStr->buffer[count++] = conversions[0][current++]; } // offset[count-1] = nStartPos + currPos + word.getLength() - 1; } else { while (current < conversions[0].getLength()) newStr->buffer[count++] = conversions[0][current++]; } currPos += word.getLength(); found = sal_True; } } if (!found && index[len+1] - index[len] > 0) { sal_Int32 bottom = (sal_Int32) index[len]; sal_Int32 top = (sal_Int32) index[len+1] - 1; while (bottom <= top && !found) { current = (top + bottom) / 2; const sal_Int32 result = word.compareTo(wordData + entry[current]); if (result < 0) top = current - 1; else if (result > 0) bottom = current + 1; else { if (toSChinese) // Traditionary/Simplified conversion, for (current = entry[current]-1; current > 0 && wordData[current-1]; current--); else // Simplified/Traditionary conversion, forwards search for next word current = entry[current] + word.getLength() + 1; sal_Int32 start=current; if (offset.getLength() > 0) { if (word.getLength() != OUString(&wordData[current]).getLength()) one2one=sal_False; sal_Int32 convertedLength=OUString(&wordData[current]).getLength(); while (wordData[current]) { offset[count]=nStartPos + currPos + ((current-start) * word.getLength() / convertedLength); newStr->buffer[count++] = wordData[current++]; } // offset[count-1]=nStartPos + currPos + word.getLength() - 1; } else { while (wordData[current]) newStr->buffer[count++] = wordData[current++]; } currPos += word.getLength(); found = sal_True; } } } } if (!found) { if (offset.getLength() > 0) offset[count]=nStartPos+currPos; newStr->buffer[count++] = getOneCharConversion(aText[nStartPos+currPos], charData, charIndex); currPos++; } } if (offset.getLength() > 0) offset.realloc(one2one ? 0 : count); return OUString( newStr->buffer, count); } TextConversionResult SAL_CALL TextConversion_zh::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions) throw( RuntimeException, IllegalArgumentException, NoSupportException ) { TextConversionResult result; result.Candidates.realloc(1); result.Candidates[0] = getConversion( aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions); result.Boundary.startPos = nStartPos; result.Boundary.endPos = nStartPos + nLength; return result; } OUString SAL_CALL TextConversion_zh::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions) throw( RuntimeException, IllegalArgumentException, NoSupportException ) { if (rLocale.Language.equalsAscii("zh") && ( nConversionType == TextConversionType::TO_SCHINESE || nConversionType == TextConversionType::TO_TCHINESE) ) { aLocale=rLocale; sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE; if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) // char to char dictionary return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions); else { Sequence <sal_Int32> offset; // word to word dictionary return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset); } } else throw NoSupportException(); // Conversion type is not supported in this service. } OUString SAL_CALL TextConversion_zh::getConversionWithOffset( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset) throw( RuntimeException, IllegalArgumentException, NoSupportException ) { if (rLocale.Language.equalsAscii("zh") && ( nConversionType == TextConversionType::TO_SCHINESE || nConversionType == TextConversionType::TO_TCHINESE) ) { aLocale=rLocale; sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE; if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) { offset.realloc(0); // char to char dictionary return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions); } else { if (offset.getLength() < 2*nLength) offset.realloc(2*nLength); // word to word dictionary return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset); } } else throw NoSupportException(); // Conversion type is not supported in this service. } sal_Bool SAL_CALL TextConversion_zh::interactiveConversion( const Locale& /*rLocale*/, sal_Int16 /*nTextConversionType*/, sal_Int32 /*nTextConversionOptions*/ ) throw( RuntimeException, IllegalArgumentException, NoSupportException ) { return sal_False; } } } } } <|endoftext|>
<commit_before>#include "../tests.h" // Random number generation using cl::sycl::float1; using cl::sycl::uint1; using cl::sycl::uint2; // http://stackoverflow.com/a/16077942 template <class Float, class Uint1, class Uint2> Float getRandom(Uint2& seed) { static const Float invMaxInt = 1.0f / 4294967296.0f; Uint1 x = seed.x() * 17 + seed.y() * 13123; seed.x() = (x << 13) ^ x; seed.y() ^= x << 7; return (Float)(x * (x * x * 15731 + 74323) + 871483) * invMaxInt; } float1 deviceRandom(uint2& seed) { using namespace cl::sycl; return getRandom<float1, uint1>(seed); } float hostRandom(cl_uint2& seed) { return getRandom<float, cl::sycl::cl_uint>(seed); } bool test11() { using namespace cl::sycl; using namespace std; queue myQueue; const int size = 4096; buffer<float> numbers(size); // TODO: Should not be zero uint32_t startSeed_x = 24325; uint32_t startSeed_y = 32536; myQueue.submit([&](handler& cgh) { auto n = numbers.get_access<access::mode::discard_write>(cgh); cgh.single_task<class generate>([=]() { uint2 seed(startSeed_x, startSeed_y); SYCL_FOR(int1 i = 0, i < size, ++i) { n[i] = deviceRandom(seed); } SYCL_END }); }); float eps = 1e-3f; // Don't need very high accuracy auto n = numbers.get_access<access::mode::read, access::target::host_buffer>(); ::cl_uint2 seed = { startSeed_x, startSeed_y }; // TODO: Better automatic testing for(auto i = 0; i < size; ++i) { auto hostRnd = hostRandom(seed); auto deviceRnd = n[i]; if(deviceRnd < hostRnd - eps || deviceRnd > hostRnd + eps) { cout << i << " -> expected " << hostRnd << ", got " << deviceRnd << endl; return false; } } return true; } <commit_msg>tests - fixed CL type usage in test11<commit_after>#include "../tests.h" // Random number generation using cl::sycl::float1; using cl::sycl::uint1; using cl::sycl::uint2; // http://stackoverflow.com/a/16077942 template <class Float, class Uint1, class Uint2> Float getRandom(Uint2& seed) { static const Float invMaxInt = 1.0f / 4294967296.0f; Uint1 x = seed.x() * 17 + seed.y() * 13123; seed.x() = (x << 13) ^ x; seed.y() ^= x << 7; return (Float)(x * (x * x * 15731 + 74323) + 871483) * invMaxInt; } float1 deviceRandom(uint2& seed) { using namespace cl::sycl; return getRandom<float1, uint1>(seed); } float hostRandom(cl::sycl::cl_uint2& seed) { return getRandom<float, cl::sycl::cl_uint>(seed); } bool test11() { using namespace cl::sycl; using namespace std; queue myQueue; const int size = 4096; buffer<float> numbers(size); // TODO: Should not be zero ::cl_uint2 startSeed = { 24325, 32536 }; myQueue.submit([&](handler& cgh) { auto n = numbers.get_access<access::mode::discard_write>(cgh); cgh.single_task<class generate>([=]() { uint2 seed(startSeed.x, startSeed.y); SYCL_FOR(int1 i = 0, i < size, ++i) { n[i] = deviceRandom(seed); } SYCL_END }); }); float eps = 1e-3f; // Don't need very high accuracy auto n = numbers.get_access<access::mode::read, access::target::host_buffer>(); cl::sycl::cl_uint2 seed = startSeed; // TODO: Better automatic testing for(auto i = 0; i < size; ++i) { auto hostRnd = hostRandom(seed); auto deviceRnd = n[i]; if(deviceRnd < hostRnd - eps || deviceRnd > hostRnd + eps) { cout << i << " -> expected " << hostRnd << ", got " << deviceRnd << endl; return false; } } return true; } <|endoftext|>
<commit_before>#include <QSettings> #include <QTranslator> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/project.h> #include <projectexplorer/target.h> #include <projectexplorer/task.h> #include <projectexplorer/buildconfiguration.h> #include <projectexplorer/buildsteplist.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/buildmanager.h> #include <coreplugin/icore.h> #include <QtPlugin> #include "QtcPaneEncodePlugin.h" #include "OptionsPage.h" #include "Utils.h" #include "Constants.h" using namespace QtcPaneEncode::Internal; using namespace QtcPaneEncode::Constants; using namespace Core; using namespace ProjectExplorer; using namespace ExtensionSystem; namespace { const QString appOutputPaneClassName = QLatin1String("ProjectExplorer::Internal::AppOutputPane"); } QtcPaneEncodePlugin::QtcPaneEncodePlugin(): IPlugin() { // Create your members } QtcPaneEncodePlugin::~QtcPaneEncodePlugin() { // Unregister objects from the plugin manager's object pool // Delete members } bool QtcPaneEncodePlugin::initialize(const QStringList &arguments, QString *errorString) { // Register objects in the plugin manager's object pool // Load settings // Add actions to menus // Connect to other plugins' signals // In the initialize function, a plugin can be sure that the plugins it // depends on have initialized their members. Q_UNUSED(arguments) Q_UNUSED(errorString) initLanguage(); updateSettings(); OptionsPage *optionsPage = new OptionsPage; connect(optionsPage, SIGNAL(settingsChanged()), SLOT(updateSettings())); addAutoReleasedObject(optionsPage); return true; } void QtcPaneEncodePlugin::initLanguage() { const QString& language = Core::ICore::userInterfaceLanguage(); if (!language.isEmpty()) { QStringList paths; paths << ICore::resourcePath () << ICore::userResourcePath(); const QString& trFile = QLatin1String ("QtcPaneEncode_") + language; QTranslator* translator = new QTranslator (this); foreach (const QString& path, paths) { if (translator->load (trFile, path + QLatin1String ("/translations"))) { qApp->installTranslator (translator); break; } } } } void QtcPaneEncodePlugin::updateSettings() { Q_ASSERT(Core::ICore::settings() != NULL); QSettings& settings = *(Core::ICore::settings()); settings.beginGroup(SETTINGS_GROUP); if(settings.value(SETTINGS_BUILD_ENABLED, false).toBool()) { buildEncoding_ = settings.value(SETTINGS_BUILD_ENCODING, AUTO_ENCODING).toByteArray(); } else { buildEncoding_.clear(); } if(settings.value(SETTINGS_APP_ENABLED, false).toBool()) { appEncoding_ = settings.value(SETTINGS_APP_ENCODING, AUTO_ENCODING).toByteArray(); } else { appEncoding_.clear(); } settings.endGroup(); } void QtcPaneEncodePlugin::extensionsInitialized() { // Retrieve objects from the plugin manager's object pool // In the extensionsInitialized function, a plugin can be sure that all // plugins that depend on it are completely initialized. // Compiler output connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)), this, SLOT(handleBuild(ProjectExplorer::Project*))); connect(this, SIGNAL(newOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), BuildManager::instance(), SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting))); connect(this, SIGNAL(newTask(ProjectExplorer::Task, int, int)), BuildManager::instance(), SLOT(addToTaskWindow(ProjectExplorer::Task, int, int))); // Run control output QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName); if(appOutputPane != NULL) { connect(ProjectExplorerPlugin::instance(), SIGNAL(runControlStarted(ProjectExplorer::RunControl *)), this, SLOT(handleRunStart(ProjectExplorer::RunControl *))); connect(this, SIGNAL(newMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat))); } else { qCritical() << "Failed to find appOutputPane"; } } ExtensionSystem::IPlugin::ShutdownFlag QtcPaneEncodePlugin::aboutToShutdown() { // Save settings // Disconnect from signals that are not needed during shutdown // Hide UI(if you add UI that is not in the main window directly) this->disconnect(); return SynchronousShutdown; } void QtcPaneEncodePlugin::handleBuild(ProjectExplorer::Project *project) { if(!BuildManager::isBuilding()) { return; } const Target *buildingTarget = NULL; foreach(Target* target, project->targets ()) { if (BuildManager::isBuilding (target)) { buildingTarget = target; break; } } if(buildingTarget == NULL) { return; } BuildConfiguration* buildingConfiguration = NULL; foreach(BuildConfiguration* config, buildingTarget->buildConfigurations ()) { if (BuildManager::isBuilding (config)) { buildingConfiguration = config; break; } } if(buildingConfiguration == NULL) { return; } QList<Core::Id> stepsIds = buildingConfiguration->knownStepLists(); foreach(const Core::Id &id, stepsIds) { BuildStepList *steps = buildingConfiguration->stepList(id); if(steps == NULL) { continue; } for(int i = 0, end = steps->count(); i < end; ++i) { BuildStep *step = steps->at(i); connect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), this, SLOT(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), Qt::UniqueConnection); disconnect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), BuildManager::instance(), SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting))); connect(step, SIGNAL(addTask(ProjectExplorer::Task, int, int)), this, SLOT(addTask(ProjectExplorer::Task, int, int)), Qt::UniqueConnection); disconnect(step, SIGNAL(addTask(ProjectExplorer::Task, int, int)), BuildManager::instance(), SLOT(addToTaskWindow(ProjectExplorer::Task, int, int))); } } } void QtcPaneEncodePlugin::addTask(const Task &task, int linkedOutputLines, int skipLines) { if (buildEncoding_.isEmpty ()) { emit newTask(task, linkedOutputLines, skipLines); return; } Task convertedTask = task; // Unknown charset will be handled like auto-detection request convertedTask.description = reencode(task.description, QTextCodec::codecForName(buildEncoding_)); emit newTask(convertedTask, linkedOutputLines, skipLines); } void QtcPaneEncodePlugin::addOutput(const QString &string, BuildStep::OutputFormat format, BuildStep::OutputNewlineSetting newlineSetting) { if (buildEncoding_.isEmpty ()) { emit newOutput(string, format, newlineSetting); return; } QString convertedString = reencode(string, QTextCodec::codecForName(buildEncoding_)); emit newOutput(convertedString, format, newlineSetting); } void QtcPaneEncodePlugin::handleRunStart(RunControl *runControl) { QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName); if(appOutputPane != NULL) { connect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), Qt::UniqueConnection); disconnect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat))); } } void QtcPaneEncodePlugin::appendMessage(RunControl *rc, const QString &out, Utils::OutputFormat format) { if (appEncoding_.isEmpty ()) { emit newMessage(rc, out, format); return; } QString convertedOut = reencode(out, QTextCodec::codecForName(appEncoding_)); emit newMessage(rc, convertedOut, format); } <commit_msg>Qtc 4.0.2 "fix". Requires to make QtcPaneEncodePlugin friend to BuildManager (change qtc source). Also disconnects all slots from BuildStep::addOutput/Task instead of only required ones. Acceptable for now (there is only 1 connection) but may break something in future.<commit_after>#include <QSettings> #include <QTranslator> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/project.h> #include <projectexplorer/target.h> #include <projectexplorer/task.h> #include <projectexplorer/buildconfiguration.h> #include <projectexplorer/buildsteplist.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/buildmanager.h> #include <coreplugin/icore.h> #include <QtPlugin> #include "QtcPaneEncodePlugin.h" #include "OptionsPage.h" #include "Utils.h" #include "Constants.h" using namespace QtcPaneEncode::Internal; using namespace QtcPaneEncode::Constants; using namespace Core; using namespace ProjectExplorer; using namespace ExtensionSystem; namespace { const QString appOutputPaneClassName = QLatin1String("ProjectExplorer::Internal::AppOutputPane"); } QtcPaneEncodePlugin::QtcPaneEncodePlugin(): IPlugin() { // Create your members } QtcPaneEncodePlugin::~QtcPaneEncodePlugin() { // Unregister objects from the plugin manager's object pool // Delete members } bool QtcPaneEncodePlugin::initialize(const QStringList &arguments, QString *errorString) { // Register objects in the plugin manager's object pool // Load settings // Add actions to menus // Connect to other plugins' signals // In the initialize function, a plugin can be sure that the plugins it // depends on have initialized their members. Q_UNUSED(arguments) Q_UNUSED(errorString) initLanguage(); updateSettings(); OptionsPage *optionsPage = new OptionsPage; connect(optionsPage, SIGNAL(settingsChanged()), SLOT(updateSettings())); addAutoReleasedObject(optionsPage); return true; } void QtcPaneEncodePlugin::initLanguage() { const QString& language = Core::ICore::userInterfaceLanguage(); if (!language.isEmpty()) { QStringList paths; paths << ICore::resourcePath () << ICore::userResourcePath(); const QString& trFile = QLatin1String ("QtcPaneEncode_") + language; QTranslator* translator = new QTranslator (this); foreach (const QString& path, paths) { if (translator->load (trFile, path + QLatin1String ("/translations"))) { qApp->installTranslator (translator); break; } } } } void QtcPaneEncodePlugin::updateSettings() { Q_ASSERT(Core::ICore::settings() != NULL); QSettings& settings = *(Core::ICore::settings()); settings.beginGroup(SETTINGS_GROUP); if(settings.value(SETTINGS_BUILD_ENABLED, false).toBool()) { buildEncoding_ = settings.value(SETTINGS_BUILD_ENCODING, AUTO_ENCODING).toByteArray(); } else { buildEncoding_.clear(); } if(settings.value(SETTINGS_APP_ENABLED, false).toBool()) { appEncoding_ = settings.value(SETTINGS_APP_ENCODING, AUTO_ENCODING).toByteArray(); } else { appEncoding_.clear(); } settings.endGroup(); } void QtcPaneEncodePlugin::extensionsInitialized() { // Retrieve objects from the plugin manager's object pool // In the extensionsInitialized function, a plugin can be sure that all // plugins that depend on it are completely initialized. // Compiler output connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)), this, SLOT(handleBuild(ProjectExplorer::Project*))); connect(this, &QtcPaneEncodePlugin::newOutput, BuildManager::instance(), &BuildManager::addToOutputWindow); connect(this, &QtcPaneEncodePlugin::newTask, BuildManager::instance(), &BuildManager::addToTaskWindow); // Run control output QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName); if(appOutputPane != NULL) { connect(ProjectExplorerPlugin::instance(), SIGNAL(runControlStarted(ProjectExplorer::RunControl *)), this, SLOT(handleRunStart(ProjectExplorer::RunControl *))); connect(this, SIGNAL(newMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat))); } else { qCritical() << "Failed to find appOutputPane"; } } ExtensionSystem::IPlugin::ShutdownFlag QtcPaneEncodePlugin::aboutToShutdown() { // Save settings // Disconnect from signals that are not needed during shutdown // Hide UI(if you add UI that is not in the main window directly) this->disconnect(); return SynchronousShutdown; } void QtcPaneEncodePlugin::handleBuild(ProjectExplorer::Project *project) { if(!BuildManager::isBuilding()) { return; } const Target *buildingTarget = NULL; foreach(Target* target, project->targets ()) { if (BuildManager::isBuilding (target)) { buildingTarget = target; break; } } if(buildingTarget == NULL) { return; } BuildConfiguration* buildingConfiguration = NULL; foreach(BuildConfiguration* config, buildingTarget->buildConfigurations ()) { if (BuildManager::isBuilding (config)) { buildingConfiguration = config; break; } } if(buildingConfiguration == NULL) { return; } QList<Core::Id> stepsIds = buildingConfiguration->knownStepLists(); foreach(const Core::Id &id, stepsIds) { BuildStepList *steps = buildingConfiguration->stepList(id); if(steps == NULL) { continue; } for(int i = 0, end = steps->count(); i < end; ++i) { BuildStep *step = steps->at(i); disconnect(step, &BuildStep::addOutput, 0, 0); connect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), this, SLOT(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), Qt::UniqueConnection); disconnect(step, &BuildStep::addTask, 0, 0); connect(step, SIGNAL(addTask(ProjectExplorer::Task, int, int)), this, SLOT(addTask(ProjectExplorer::Task, int, int)), Qt::UniqueConnection); } } } void QtcPaneEncodePlugin::addTask(const Task &task, int linkedOutputLines, int skipLines) { if (buildEncoding_.isEmpty ()) { emit newTask(task, linkedOutputLines, skipLines); return; } Task convertedTask = task; // Unknown charset will be handled like auto-detection request convertedTask.description = reencode(task.description, QTextCodec::codecForName(buildEncoding_)); emit newTask(convertedTask, linkedOutputLines, skipLines); } void QtcPaneEncodePlugin::addOutput(const QString &string, BuildStep::OutputFormat format, BuildStep::OutputNewlineSetting newlineSetting) { if (buildEncoding_.isEmpty ()) { emit newOutput(string, format, newlineSetting); return; } QString convertedString = reencode(string, QTextCodec::codecForName(buildEncoding_)); emit newOutput(convertedString, format, newlineSetting); } void QtcPaneEncodePlugin::handleRunStart(RunControl *runControl) { QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName); if(appOutputPane != NULL) { connect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), Qt::UniqueConnection); disconnect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat))); } } void QtcPaneEncodePlugin::appendMessage(RunControl *rc, const QString &out, Utils::OutputFormat format) { if (appEncoding_.isEmpty ()) { emit newMessage(rc, out, format); return; } QString convertedOut = reencode(out, QTextCodec::codecForName(appEncoding_)); emit newMessage(rc, convertedOut, format); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkReviewHeaderTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include <cstdlib> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkBinaryMorphologicalClosingImageFilter.txx" #include "itkBinaryMorphologicalOpeningImageFilter.txx" #include "itkConformalFlatteningMeshFilter.txx" #include "itkContourExtractor2DImageFilter.txx" #include "itkFlatStructuringElement.txx" #include "itkGeometricalQuadEdge.txx" #include "itkImageToPathFilter.txx" #include "itkLabelOverlayFunctor.h" #include "itkLabelOverlayImageFilter.txx" #include "itkLabelToRGBFunctor.h" #include "itkLabelToRGBImageFilter.txx" #include "itkMatlabTransformIO.h" #include "itkMatlabTransformIOFactory.h" #include "itkMorphologicalWatershedFromMarkersImageFilter.txx" #include "itkMorphologicalWatershedImageFilter.txx" #include "itkNeuralNetworkFileReader.txx" #include "itkNeuralNetworkFileWriter.txx" #include "itkQuadEdge.h" #include "itkQuadEdgeCellTraitsInfo.h" #include "itkQuadEdgeMesh.txx" #include "itkQuadEdgeMeshBaseIterator.h" #include "itkQuadEdgeMeshBoundaryEdgesMeshFunction.txx" #include "itkQuadEdgeMeshEulerOperatorCreateCenterVertexFunction.txx" #include "itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.txx" #include "itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.txx" #include "itkQuadEdgeMeshEulerOperatorJoinFacetFunction.txx" #include "itkQuadEdgeMeshEulerOperatorJoinVertexFunction.txx" #include "itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h" #include "itkQuadEdgeMeshEulerOperatorSplitFacetFunction.txx" #include "itkQuadEdgeMeshEulerOperatorSplitVertexFunction.txx" #include "itkQuadEdgeMeshFrontIterator.txx" #include "itkQuadEdgeMeshFunctionBase.h" #include "itkQuadEdgeMeshLineCell.txx" #include "itkQuadEdgeMeshMacro.h" #include "itkQuadEdgeMeshPoint.txx" #include "itkQuadEdgeMeshPolygonCell.txx" #include "itkQuadEdgeMeshToQuadEdgeMeshFilter.txx" #include "itkQuadEdgeMeshTopologyChecker.txx" #include "itkQuadEdgeMeshTraits.h" #include "itkQuadEdgeMeshZipMeshFunction.txx" #include "itkRegionalMaximaImageFilter.txx" #include "itkRegionalMinimaImageFilter.txx" #include "itkTransformFileReaderWithFactory.h" #include "itkTransformFileWriterWithFactory.h" #include "itkTransformIOBase.h" #include "itkTransformIOFactory.h" #include "itkTxtTransformIO.h" #include "itkTxtTransformIOFactory.h" #include "itkVTKPolyDataReader.txx" #include "itkVTKPolyDataWriter.txx" #include "itkValuedRegionalExtremaImageFilter.txx" #include "itkValuedRegionalMaximaImageFilter.h" #include "itkValuedRegionalMinimaImageFilter.h" #include "itkBoxImageFilter.h" #include "itkKernelImageFilter.h" #include "itkMovingHistogramImageFilterBase.h" #include "itkMovingHistogramImageFilter.h" #include "itkMovingHistogramMorphologyImageFilter.h" #include "itkMovingHistogramDilateImageFilter.h" #include "itkMovingHistogramErodeImageFilter.h" #include "itkMovingHistogramMorphologicalGradientImageFilter.h" #include "itkBasicDilateImageFilter.h" #include "itkBasicErodeImageFilter.h" #include "itkAnchorCloseImageFilter.h" #include "itkAnchorDilateImageFilter.h" #include "itkAnchorErodeDilateImageFilter.h" #include "itkAnchorErodeDilateImageFilter.txx" #include "itkAnchorErodeDilateLine.h" #include "itkAnchorErodeDilateLine.txx" #include "itkAnchorErodeImageFilter.h" #include "itkAnchorHistogram.h" #include "itkAnchorOpenCloseImageFilter.h" #include "itkAnchorOpenCloseImageFilter.txx" #include "itkAnchorOpenCloseLine.h" #include "itkAnchorOpenCloseLine.txx" #include "itkAnchorOpenImageFilter.h" #include "itkAnchorUtilities.h" #include "itkAnchorUtilities.txx" #include "itkBresenhamLine.h" #include "itkBresenhamLine.txx" #include "itkSharedMorphologyUtilities.h" #include "itkSharedMorphologyUtilities.txx" #include "itkVanHerkGilWermanDilateImageFilter.h" #include "itkVanHerkGilWermanErodeDilateImageFilter.h" #include "itkVanHerkGilWermanErodeDilateImageFilter.txx" #include "itkVanHerkGilWermanErodeImageFilter.h" #include "itkVanHerkGilWermanUtilities.h" #include "itkVanHerkGilWermanUtilities.txx" #include "itkBoxUtilities.h" #include "itkBoxMeanImageFilter.h" #include "itkBoxMeanImageFilter.txx" #include "itkBoxSigmaImageFilter.h" #include "itkBoxSigmaImageFilter.txx" #include "itkRankHistogram.h" #include "itkRankImageFilter.h" #include "itkRankImageFilter.txx" #include "itkMaskedRankHistogram.h" #include "itkMaskedRankImageFilter.h" #include "itkMaskedRankImageFilter.txx" #include "itkMiniPipelineSeparableImageFilter.h" #include "itkMiniPipelineSeparableImageFilter.txx" #include "itkFastApproximateRankImageFilter.h" #include "itkBinaryContourImageFilter.h" #include "itkLabelContourImageFilter.h" #include "itkFFTShiftImageFilter.h" #include "itkConvolutionImageFilter.h" #include "itkHessianToObjectnessMeasureImageFilter.h" #include "itkMultiScaleHessianBasedMeasureImageFilterTest.h" int main ( int , char * [] ) { return EXIT_SUCCESS; } <commit_msg>BUG: incorrect header file included<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkReviewHeaderTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include <cstdlib> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkBinaryMorphologicalClosingImageFilter.txx" #include "itkBinaryMorphologicalOpeningImageFilter.txx" #include "itkConformalFlatteningMeshFilter.txx" #include "itkContourExtractor2DImageFilter.txx" #include "itkFlatStructuringElement.txx" #include "itkGeometricalQuadEdge.txx" #include "itkImageToPathFilter.txx" #include "itkLabelOverlayFunctor.h" #include "itkLabelOverlayImageFilter.txx" #include "itkLabelToRGBFunctor.h" #include "itkLabelToRGBImageFilter.txx" #include "itkMatlabTransformIO.h" #include "itkMatlabTransformIOFactory.h" #include "itkMorphologicalWatershedFromMarkersImageFilter.txx" #include "itkMorphologicalWatershedImageFilter.txx" #include "itkNeuralNetworkFileReader.txx" #include "itkNeuralNetworkFileWriter.txx" #include "itkQuadEdge.h" #include "itkQuadEdgeCellTraitsInfo.h" #include "itkQuadEdgeMesh.txx" #include "itkQuadEdgeMeshBaseIterator.h" #include "itkQuadEdgeMeshBoundaryEdgesMeshFunction.txx" #include "itkQuadEdgeMeshEulerOperatorCreateCenterVertexFunction.txx" #include "itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.txx" #include "itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.txx" #include "itkQuadEdgeMeshEulerOperatorJoinFacetFunction.txx" #include "itkQuadEdgeMeshEulerOperatorJoinVertexFunction.txx" #include "itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h" #include "itkQuadEdgeMeshEulerOperatorSplitFacetFunction.txx" #include "itkQuadEdgeMeshEulerOperatorSplitVertexFunction.txx" #include "itkQuadEdgeMeshFrontIterator.txx" #include "itkQuadEdgeMeshFunctionBase.h" #include "itkQuadEdgeMeshLineCell.txx" #include "itkQuadEdgeMeshMacro.h" #include "itkQuadEdgeMeshPoint.txx" #include "itkQuadEdgeMeshPolygonCell.txx" #include "itkQuadEdgeMeshToQuadEdgeMeshFilter.txx" #include "itkQuadEdgeMeshTopologyChecker.txx" #include "itkQuadEdgeMeshTraits.h" #include "itkQuadEdgeMeshZipMeshFunction.txx" #include "itkRegionalMaximaImageFilter.txx" #include "itkRegionalMinimaImageFilter.txx" #include "itkTransformFileReaderWithFactory.h" #include "itkTransformFileWriterWithFactory.h" #include "itkTransformIOBase.h" #include "itkTransformIOFactory.h" #include "itkTxtTransformIO.h" #include "itkTxtTransformIOFactory.h" #include "itkVTKPolyDataReader.txx" #include "itkVTKPolyDataWriter.txx" #include "itkValuedRegionalExtremaImageFilter.txx" #include "itkValuedRegionalMaximaImageFilter.h" #include "itkValuedRegionalMinimaImageFilter.h" #include "itkBoxImageFilter.h" #include "itkKernelImageFilter.h" #include "itkMovingHistogramImageFilterBase.h" #include "itkMovingHistogramImageFilter.h" #include "itkMovingHistogramMorphologyImageFilter.h" #include "itkMovingHistogramDilateImageFilter.h" #include "itkMovingHistogramErodeImageFilter.h" #include "itkMovingHistogramMorphologicalGradientImageFilter.h" #include "itkBasicDilateImageFilter.h" #include "itkBasicErodeImageFilter.h" #include "itkAnchorCloseImageFilter.h" #include "itkAnchorDilateImageFilter.h" #include "itkAnchorErodeDilateImageFilter.h" #include "itkAnchorErodeDilateImageFilter.txx" #include "itkAnchorErodeDilateLine.h" #include "itkAnchorErodeDilateLine.txx" #include "itkAnchorErodeImageFilter.h" #include "itkAnchorHistogram.h" #include "itkAnchorOpenCloseImageFilter.h" #include "itkAnchorOpenCloseImageFilter.txx" #include "itkAnchorOpenCloseLine.h" #include "itkAnchorOpenCloseLine.txx" #include "itkAnchorOpenImageFilter.h" #include "itkAnchorUtilities.h" #include "itkAnchorUtilities.txx" #include "itkBresenhamLine.h" #include "itkBresenhamLine.txx" #include "itkSharedMorphologyUtilities.h" #include "itkSharedMorphologyUtilities.txx" #include "itkVanHerkGilWermanDilateImageFilter.h" #include "itkVanHerkGilWermanErodeDilateImageFilter.h" #include "itkVanHerkGilWermanErodeDilateImageFilter.txx" #include "itkVanHerkGilWermanErodeImageFilter.h" #include "itkVanHerkGilWermanUtilities.h" #include "itkVanHerkGilWermanUtilities.txx" #include "itkBoxUtilities.h" #include "itkBoxMeanImageFilter.h" #include "itkBoxMeanImageFilter.txx" #include "itkBoxSigmaImageFilter.h" #include "itkBoxSigmaImageFilter.txx" #include "itkRankHistogram.h" #include "itkRankImageFilter.h" #include "itkRankImageFilter.txx" #include "itkMaskedRankHistogram.h" #include "itkMaskedRankImageFilter.h" #include "itkMaskedRankImageFilter.txx" #include "itkMiniPipelineSeparableImageFilter.h" #include "itkMiniPipelineSeparableImageFilter.txx" #include "itkFastApproximateRankImageFilter.h" #include "itkBinaryContourImageFilter.h" #include "itkLabelContourImageFilter.h" #include "itkFFTShiftImageFilter.h" #include "itkConvolutionImageFilter.h" #include "itkHessianToObjectnessMeasureImageFilter.h" #include "itkMultiScaleHessianBasedMeasureImageFilter.h" int main ( int , char * [] ) { return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 13129 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkRigidRegistrationPreset.h" #include <itkArray.h> int mitkRigidRegistrationPresetTest(int argc, char* argv[]) { typedef itk::Array<double> ArrayType; mitk::RigidRegistrationPreset* rrp = new mitk::RigidRegistrationPreset; std::cout<<"[PASSED]"<<std::endl; // Check if the default presets (in the Functionality directory) can be loaded. std::cout<<"Testing default parameter loading...\n"; if(!rrp->LoadPreset()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Check if an exemplary parameter set can be extracted from the read presets. std::cout<<"Testing if exemplary default values match default parameters...\n"; ArrayType transformValues = rrp->getTransformValues("ITK Image Registration 12"); ArrayType metricValues = rrp->getMetricValues("ITK Image Registration 12"); ArrayType optimizerValues = rrp->getOptimizerValues("ITK Image Registration 12"); ArrayType interpolatorValues = rrp->getInterpolatorValues("ITK Image Registration 12"); std::cout << transformValues[5] << metricValues[1] << optimizerValues[4] << interpolatorValues[0] << std::endl; if( !(transformValues[5]==0.001) || !(metricValues[1]==1) || !(optimizerValues[4]==0.1) || !(interpolatorValues[0]==0) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing if a save operation can be performed. std::cout<<"Testing if saving is possible...\n"; if (!rrp->newPresets( rrp->getTransformValuesPresets(), rrp->getMetricValuesPresets(), rrp->getOptimizerValuesPresets(), rrp->getInterpolatorValuesPresets() )) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing what happens if we now repeat the test with the previously written xml file delete rrp; mitk::RigidRegistrationPreset* rrp2 = new mitk::RigidRegistrationPreset; std::cout<<"[PASSED]"<<std::endl; // Check if the default presets (in the Functionality directory) can be loaded. std::cout<<"Testing default parameter loading, second time...\n"; if(!rrp2->LoadPreset()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Check if an exemplary parameter set can be extracted from the read presets. std::cout<<"Testing if exemplary default values match default parameters, second time...\n"; transformValues = rrp2->getTransformValues("ITK Image Registration 12"); metricValues = rrp2->getMetricValues("ITK Image Registration 12"); optimizerValues = rrp2->getOptimizerValues("ITK Image Registration 12"); interpolatorValues = rrp2->getInterpolatorValues("ITK Image Registration 12"); if( !(transformValues[5]==0.001) || !(metricValues[1]==1) || !(optimizerValues[4]==0.1) || !(interpolatorValues[0]==0) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; delete rrp2; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; }<commit_msg>COMP: Fix warnings<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 13129 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkRigidRegistrationPreset.h" #include <itkArray.h> int mitkRigidRegistrationPresetTest(int /*argc*/, char* /*argv*/[]) { typedef itk::Array<double> ArrayType; mitk::RigidRegistrationPreset* rrp = new mitk::RigidRegistrationPreset; std::cout<<"[PASSED]"<<std::endl; // Check if the default presets (in the Functionality directory) can be loaded. std::cout<<"Testing default parameter loading...\n"; if(!rrp->LoadPreset()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Check if an exemplary parameter set can be extracted from the read presets. std::cout<<"Testing if exemplary default values match default parameters...\n"; ArrayType transformValues = rrp->getTransformValues("ITK Image Registration 12"); ArrayType metricValues = rrp->getMetricValues("ITK Image Registration 12"); ArrayType optimizerValues = rrp->getOptimizerValues("ITK Image Registration 12"); ArrayType interpolatorValues = rrp->getInterpolatorValues("ITK Image Registration 12"); std::cout << transformValues[5] << metricValues[1] << optimizerValues[4] << interpolatorValues[0] << std::endl; if( !(transformValues[5]==0.001) || !(metricValues[1]==1) || !(optimizerValues[4]==0.1) || !(interpolatorValues[0]==0) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing if a save operation can be performed. std::cout<<"Testing if saving is possible...\n"; if (!rrp->newPresets( rrp->getTransformValuesPresets(), rrp->getMetricValuesPresets(), rrp->getOptimizerValuesPresets(), rrp->getInterpolatorValuesPresets() )) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Testing what happens if we now repeat the test with the previously written xml file delete rrp; mitk::RigidRegistrationPreset* rrp2 = new mitk::RigidRegistrationPreset; std::cout<<"[PASSED]"<<std::endl; // Check if the default presets (in the Functionality directory) can be loaded. std::cout<<"Testing default parameter loading, second time...\n"; if(!rrp2->LoadPreset()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; // Check if an exemplary parameter set can be extracted from the read presets. std::cout<<"Testing if exemplary default values match default parameters, second time...\n"; transformValues = rrp2->getTransformValues("ITK Image Registration 12"); metricValues = rrp2->getMetricValues("ITK Image Registration 12"); optimizerValues = rrp2->getOptimizerValues("ITK Image Registration 12"); interpolatorValues = rrp2->getInterpolatorValues("ITK Image Registration 12"); if( !(transformValues[5]==0.001) || !(metricValues[1]==1) || !(optimizerValues[4]==0.1) || !(interpolatorValues[0]==0) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; delete rrp2; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s ../test_common.cpp EXCLUDE_HIP_PLATFORM nvcc * RUN: %t * HIT_END */ #include <iostream> #include <hip/hip_fp16.h> #include "hip/hip_runtime.h" #include "test_common.h" #if __HIP_ARCH_GFX803__ || __HIP_ARCH_GFX900__ || __HIP_ARCH_GFX906__ __global__ __attribute__((optnone)) void __halfMath(bool* result) { __half a{1}; result[0] = __heq(__hadd(a, __half{1}), __half{2}); result[0] = __heq(__hadd_sat(a, __half{1}), __half{1}) && result[0]; result[0] = __heq(__hfma(a, __half{2}, __half{3}), __half{5}) && result[0]; result[0] = __heq(__hfma_sat(a, __half{2}, __half{3}), __half{1}) && result[0]; result[0] = __heq(__hsub(a, __half{1}), __half{0}) && result[0]; result[0] = __heq(__hsub_sat(a, __half{2}), __half{0}) && result[0]; result[0] = __heq(__hmul(a, __half{2}), __half{2}) && result[0]; result[0] = __heq(__hmul_sat(a, __half{2}), __half{1}) && result[0]; result[0] = __heq(__hdiv(a, __half{2}), __half{0.5}) && result[0]; } __device__ bool to_bool(const __half2& x) { auto r = static_cast<const __half2_raw&>(x); return r.data.x != 0 && r.data.y != 0; } __global__ __attribute__((optnone)) void __half2Math(bool* result) { __half2 a{1, 1}; result[0] = to_bool(__heq2(__hadd2(a, __half2{1, 1}), __half2{2, 2})); result[0] = to_bool(__heq2(__hadd2_sat(a, __half2{1, 1}), __half2{1, 1})) && result[0]; result[0] = to_bool(__heq2( __hfma2(a, __half2{2, 2}, __half2{3, 3}), __half2{5, 5})) && result[0]; result[0] = to_bool(__heq2( __hfma2_sat(a, __half2{2, 2}, __half2{3, 3}), __half2{1, 1})) && result[0]; result[0] = to_bool(__heq2(__hsub2(a, __half2{1, 1}), __half2{0, 0})) && result[0]; result[0] = to_bool(__heq2(__hsub2_sat(a, __half2{2, 2}), __half2{0, 0})) && result[0]; result[0] = to_bool(__heq2(__hmul2(a, __half2{2, 2}), __half2{2, 2})) && result[0]; result[0] = to_bool(__heq2(__hmul2_sat(a, __half2{2, 2}), __half2{1, 1})) && result[0]; result[0] = to_bool(__heq2(__h2div(a, __half2{2, 2}), __half2{0.5, 0.5})) && result[0]; } __global__ void kernel_hisnan(__half* input, int* output) { int tx = threadIdx.x; output[tx] = __hisnan(input[tx]); } __global__ void kernel_hisinf(__half* input, int* output) { int tx = threadIdx.x; output[tx] = __hisinf(input[tx]); } #endif __half host_ushort_as_half(unsigned short s) { union {__half h; unsigned short s; } converter; converter.s = s; return converter.h; } void check_hisnan(int NUM_INPUTS, __half* inputCPU, __half* inputGPU) { // allocate memory auto memsize = NUM_INPUTS * sizeof(int); int* outputGPU = nullptr; hipMalloc((void**)&outputGPU, memsize); // launch the kernel hipLaunchKernelGGL( kernel_hisnan, dim3(1), dim3(NUM_INPUTS), 0, 0, inputGPU, outputGPU); // copy output from device int* outputCPU = (int*) malloc(memsize); hipMemcpy(outputCPU, outputGPU, memsize, hipMemcpyDeviceToHost); // check output for (int i=0; i<NUM_INPUTS; i++) { if ((2 <= i) && (i <= 5)) { // inputs are nan, output should be true if (outputCPU[i] == 0) { failed( "__hisnan() returned false for %f (input idx = %d)\n", static_cast<float>(inputCPU[i]), i); } } else { // inputs are NOT nan, output should be false if (outputCPU[i] != 0) { failed( "__hisnan() returned true for %f (input idx = %d)\n", static_cast<float>(inputCPU[i]), i); } } } // free memory free(outputCPU); hipFree(outputGPU); // done return; } void check_hisinf(int NUM_INPUTS, __half* inputCPU, __half* inputGPU) { // allocate memory auto memsize = NUM_INPUTS * sizeof(int); int* outputGPU = nullptr; hipMalloc((void**)&outputGPU, memsize); // launch the kernel hipLaunchKernelGGL( kernel_hisinf, dim3(1), dim3(NUM_INPUTS), 0, 0, inputGPU, outputGPU); // copy output from device int* outputCPU = (int*) malloc(memsize); hipMemcpy(outputCPU, outputGPU, memsize, hipMemcpyDeviceToHost); // check output for (int i=0; i<NUM_INPUTS; i++) { if ((0 <= i) && (i <= 1)) { // inputs are inf, output should be true if (outputCPU[i] == 0) { failed( "__hisinf() returned false for %f (input idx = %d)\n", static_cast<float>(inputCPU[i]), i); } } else { // inputs are NOT inf, output should be false if (outputCPU[i] != 0) { failed( "__hisinf() returned true for %f (input idx = %d)\n", static_cast<float>(inputCPU[i]), i); } } } // free memory free(outputCPU); hipFree(outputGPU); // done return; } void checkFunctional() { // allocate memory const int NUM_INPUTS = 16; auto memsize = NUM_INPUTS * sizeof(__half); __half* inputCPU = (__half*) malloc(memsize); // populate inputs inputCPU[0] = host_ushort_as_half(0x7c00); // inf inputCPU[1] = host_ushort_as_half(0xfc00); // -inf inputCPU[2] = host_ushort_as_half(0x7c01); // nan inputCPU[3] = host_ushort_as_half(0x7e00); // nan inputCPU[4] = host_ushort_as_half(0xfc01); // nan inputCPU[5] = host_ushort_as_half(0xfe00); // nan inputCPU[6] = host_ushort_as_half(0x0000); // 0 inputCPU[7] = host_ushort_as_half(0x8000); // -0 inputCPU[8] = host_ushort_as_half(0x7bff); // max +ve normal inputCPU[9] = host_ushort_as_half(0xfbff); // max -ve normal inputCPU[10] = host_ushort_as_half(0x0400); // min +ve normal inputCPU[11] = host_ushort_as_half(0x8400); // min -ve normal inputCPU[12] = host_ushort_as_half(0x03ff); // max +ve sub-normal inputCPU[13] = host_ushort_as_half(0x83ff); // max -ve sub-normal inputCPU[14] = host_ushort_as_half(0x0001); // min +ve sub-normal inputCPU[15] = host_ushort_as_half(0x8001); // min -ve sub-normal // copy inputs to the GPU __half* inputGPU = nullptr; hipMalloc((void**)&inputGPU, memsize); hipMemcpy(inputGPU, inputCPU, memsize, hipMemcpyHostToDevice); // run checks check_hisnan(NUM_INPUTS, inputCPU, inputGPU); check_hisinf(NUM_INPUTS, inputCPU, inputGPU); // free memory hipFree(inputGPU); free(inputCPU); // all done return; } int main() { bool* result{nullptr}; hipHostMalloc(&result, sizeof(result)); result[0] = false; hipLaunchKernelGGL(__halfMath, dim3(1, 1, 1), dim3(1, 1, 1), 0, 0, result); hipDeviceSynchronize(); if (!result[0]) { failed("Failed __half tests."); } result[0] = false; hipLaunchKernelGGL(__half2Math, dim3(1, 1, 1), dim3(1, 1, 1), 0, 0, result); hipDeviceSynchronize(); if (!result[0]) { failed("Failed __half2 tests."); } hipHostFree(result); // run some functional checks checkFunctional(); passed(); } <commit_msg>Missing bits.<commit_after>/* Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s ../test_common.cpp EXCLUDE_HIP_PLATFORM nvcc * RUN: %t * HIT_END */ #include <hip/hip_fp16.h> #include "hip/hip_runtime.h" #include "test_common.h" #if __HIP_ARCH_GFX803__ || __HIP_ARCH_GFX900__ || __HIP_ARCH_GFX906__ __global__ __attribute__((optnone)) void __halfMath(bool* result) { __half a{1}; result[0] = __heq(__hadd(a, __half{1}), __half{2}); result[0] = __heq(__hadd_sat(a, __half{1}), __half{1}) && result[0]; result[0] = __heq(__hfma(a, __half{2}, __half{3}), __half{5}) && result[0]; result[0] = __heq(__hfma_sat(a, __half{2}, __half{3}), __half{1}) && result[0]; result[0] = __heq(__hsub(a, __half{1}), __half{0}) && result[0]; result[0] = __heq(__hsub_sat(a, __half{2}), __half{0}) && result[0]; result[0] = __heq(__hmul(a, __half{2}), __half{2}) && result[0]; result[0] = __heq(__hmul_sat(a, __half{2}), __half{1}) && result[0]; result[0] = __heq(__hdiv(a, __half{2}), __half{0.5}) && result[0]; } __device__ bool to_bool(const __half2& x) { auto r = static_cast<const __half2_raw&>(x); return r.data.x != 0 && r.data.y != 0; } __global__ __attribute__((optnone)) void __half2Math(bool* result) { __half2 a{1, 1}; result[0] = to_bool(__heq2(__hadd2(a, __half2{1, 1}), __half2{2, 2})); result[0] = to_bool(__heq2(__hadd2_sat(a, __half2{1, 1}), __half2{1, 1})) && result[0]; result[0] = to_bool(__heq2( __hfma2(a, __half2{2, 2}, __half2{3, 3}), __half2{5, 5})) && result[0]; result[0] = to_bool(__heq2( __hfma2_sat(a, __half2{2, 2}, __half2{3, 3}), __half2{1, 1})) && result[0]; result[0] = to_bool(__heq2(__hsub2(a, __half2{1, 1}), __half2{0, 0})) && result[0]; result[0] = to_bool(__heq2(__hsub2_sat(a, __half2{2, 2}), __half2{0, 0})) && result[0]; result[0] = to_bool(__heq2(__hmul2(a, __half2{2, 2}), __half2{2, 2})) && result[0]; result[0] = to_bool(__heq2(__hmul2_sat(a, __half2{2, 2}), __half2{1, 1})) && result[0]; result[0] = to_bool(__heq2(__h2div(a, __half2{2, 2}), __half2{0.5, 0.5})) && result[0]; } __global__ void kernel_hisnan(__half* input, int* output) { int tx = threadIdx.x; output[tx] = __hisnan(input[tx]); } __global__ void kernel_hisinf(__half* input, int* output) { int tx = threadIdx.x; output[tx] = __hisinf(input[tx]); } #endif __half host_ushort_as_half(unsigned short s) { union {__half h; unsigned short s; } converter; converter.s = s; return converter.h; } void check_hisnan(int NUM_INPUTS, __half* inputCPU, __half* inputGPU) { // allocate memory auto memsize = NUM_INPUTS * sizeof(int); int* outputGPU = nullptr; hipMalloc((void**)&outputGPU, memsize); // launch the kernel hipLaunchKernelGGL( kernel_hisnan, dim3(1), dim3(NUM_INPUTS), 0, 0, inputGPU, outputGPU); // copy output from device int* outputCPU = (int*) malloc(memsize); hipMemcpy(outputCPU, outputGPU, memsize, hipMemcpyDeviceToHost); // check output for (int i=0; i<NUM_INPUTS; i++) { if ((2 <= i) && (i <= 5)) { // inputs are nan, output should be true if (outputCPU[i] == 0) { failed( "__hisnan() returned false for %f (input idx = %d)\n", static_cast<float>(inputCPU[i]), i); } } else { // inputs are NOT nan, output should be false if (outputCPU[i] != 0) { failed( "__hisnan() returned true for %f (input idx = %d)\n", static_cast<float>(inputCPU[i]), i); } } } // free memory free(outputCPU); hipFree(outputGPU); // done return; } void check_hisinf(int NUM_INPUTS, __half* inputCPU, __half* inputGPU) { // allocate memory auto memsize = NUM_INPUTS * sizeof(int); int* outputGPU = nullptr; hipMalloc((void**)&outputGPU, memsize); // launch the kernel hipLaunchKernelGGL( kernel_hisinf, dim3(1), dim3(NUM_INPUTS), 0, 0, inputGPU, outputGPU); // copy output from device int* outputCPU = (int*) malloc(memsize); hipMemcpy(outputCPU, outputGPU, memsize, hipMemcpyDeviceToHost); // check output for (int i=0; i<NUM_INPUTS; i++) { if ((0 <= i) && (i <= 1)) { // inputs are inf, output should be true if (outputCPU[i] == 0) { failed( "__hisinf() returned false for %f (input idx = %d)\n", static_cast<float>(inputCPU[i]), i); } } else { // inputs are NOT inf, output should be false if (outputCPU[i] != 0) { failed( "__hisinf() returned true for %f (input idx = %d)\n", static_cast<float>(inputCPU[i]), i); } } } // free memory free(outputCPU); hipFree(outputGPU); // done return; } void checkFunctional() { // allocate memory const int NUM_INPUTS = 16; auto memsize = NUM_INPUTS * sizeof(__half); __half* inputCPU = (__half*) malloc(memsize); // populate inputs inputCPU[0] = host_ushort_as_half(0x7c00); // inf inputCPU[1] = host_ushort_as_half(0xfc00); // -inf inputCPU[2] = host_ushort_as_half(0x7c01); // nan inputCPU[3] = host_ushort_as_half(0x7e00); // nan inputCPU[4] = host_ushort_as_half(0xfc01); // nan inputCPU[5] = host_ushort_as_half(0xfe00); // nan inputCPU[6] = host_ushort_as_half(0x0000); // 0 inputCPU[7] = host_ushort_as_half(0x8000); // -0 inputCPU[8] = host_ushort_as_half(0x7bff); // max +ve normal inputCPU[9] = host_ushort_as_half(0xfbff); // max -ve normal inputCPU[10] = host_ushort_as_half(0x0400); // min +ve normal inputCPU[11] = host_ushort_as_half(0x8400); // min -ve normal inputCPU[12] = host_ushort_as_half(0x03ff); // max +ve sub-normal inputCPU[13] = host_ushort_as_half(0x83ff); // max -ve sub-normal inputCPU[14] = host_ushort_as_half(0x0001); // min +ve sub-normal inputCPU[15] = host_ushort_as_half(0x8001); // min -ve sub-normal // copy inputs to the GPU __half* inputGPU = nullptr; hipMalloc((void**)&inputGPU, memsize); hipMemcpy(inputGPU, inputCPU, memsize, hipMemcpyHostToDevice); // run checks check_hisnan(NUM_INPUTS, inputCPU, inputGPU); check_hisinf(NUM_INPUTS, inputCPU, inputGPU); // free memory hipFree(inputGPU); free(inputCPU); // all done return; } int main() { bool* result{nullptr}; hipHostMalloc(&result, sizeof(result)); result[0] = false; hipLaunchKernelGGL(__halfMath, dim3(1, 1, 1), dim3(1, 1, 1), 0, 0, result); hipDeviceSynchronize(); if (!result[0]) { failed("Failed __half tests."); } result[0] = false; hipLaunchKernelGGL(__half2Math, dim3(1, 1, 1), dim3(1, 1, 1), 0, 0, result); hipDeviceSynchronize(); if (!result[0]) { failed("Failed __half2 tests."); } hipHostFree(result); // run some functional checks checkFunctional(); passed(); } <|endoftext|>
<commit_before>// SMESH SMESH : implementaion of SMESH idl descriptions // // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // 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. // // 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 // // See http://www.opencascade.org/SALOME/ or email : [email protected] // // // // File : SMESH_Hexa_3D.hxx // Author : Paul RASCLE, EDF // Module : SMESH // $Header$ #ifndef _SMESH_HEXA_3D_HXX_ #define _SMESH_HEXA_3D_HXX_ #include "SMESH_3D_Algo.hxx" #include "SMESH_Mesh.hxx" #include "SMESH_Quadrangle_2D.hxx" #include "Utils_SALOME_Exception.hxx" typedef struct point3Dstruct { int nodeId; } Point3DStruct; typedef double Pt3[3]; typedef struct conv2dstruct { double a1; // X = a1*x + b1*y + c1 double b1; // Y = a2*x + b2*y + c2 double c1; // a1, b1 a2, b2 in {-1,0,1} double a2; // c1, c2 in {0,1} double b2; double c2; int ia; // I = ia*i + ib*j + ic int ib; int ic; int ja; // J = ja*i + jb*j + jc int jb; int jc; } Conv2DStruct; typedef struct cubeStruct { TopoDS_Vertex V000; TopoDS_Vertex V001; TopoDS_Vertex V010; TopoDS_Vertex V011; TopoDS_Vertex V100; TopoDS_Vertex V101; TopoDS_Vertex V110; TopoDS_Vertex V111; faceQuadStruct* quad_X0; faceQuadStruct* quad_X1; faceQuadStruct* quad_Y0; faceQuadStruct* quad_Y1; faceQuadStruct* quad_Z0; faceQuadStruct* quad_Z1; Point3DStruct* np; // normalised 3D coordinates } CubeStruct; class SMESH_Hexa_3D: public SMESH_3D_Algo { public: SMESH_Hexa_3D(int hypId, int studyId, SMESH_Gen* gen); virtual ~SMESH_Hexa_3D(); virtual bool CheckHypothesis(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape); virtual bool Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) throw (SALOME_Exception); ostream & SaveTo(ostream & save); istream & LoadFrom(istream & load); friend ostream & operator << (ostream & save, SMESH_Hexa_3D & hyp); friend istream & operator >> (istream & load, SMESH_Hexa_3D & hyp); protected: TopoDS_Edge EdgeNotInFace(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape, const TopoDS_Face& aFace, const TopoDS_Vertex& aVertex, const TopTools_IndexedDataMapOfShapeListOfShape& MS); int GetFaceIndex(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape, const vector<SMESH_subMesh*>& meshFaces, const TopoDS_Vertex& V0, const TopoDS_Vertex& V1, const TopoDS_Vertex& V2, const TopoDS_Vertex& V3); void GetConv2DCoefs(const faceQuadStruct& quad, const TopoDS_Shape& aShape, const TopoDS_Vertex& V0, const TopoDS_Vertex& V1, const TopoDS_Vertex& V2, const TopoDS_Vertex& V3, Conv2DStruct& conv); void GetPoint(Pt3 p, int i, int j, int k, int nbx, int nby, int nbz, Point3DStruct *np, const Handle(SMESHDS_Mesh)& meshDS); CubeStruct _cube; FaceQuadStruct* _quads[6]; int _indX0; int _indX1; int _indY0; int _indY1; int _indZ0; int _indZ1; }; #endif <commit_msg>Update to match the change of SMDS (new DS).<commit_after>// SMESH SMESH : implementaion of SMESH idl descriptions // // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // 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. // // 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 // // See http://www.opencascade.org/SALOME/ or email : [email protected] // // // // File : SMESH_Hexa_3D.hxx // Author : Paul RASCLE, EDF // Module : SMESH // $Header$ #ifndef _SMESH_HEXA_3D_HXX_ #define _SMESH_HEXA_3D_HXX_ #include "SMESH_3D_Algo.hxx" #include "SMESH_Mesh.hxx" #include "SMESH_Quadrangle_2D.hxx" #include "Utils_SALOME_Exception.hxx" typedef struct point3Dstruct { int nodeId; } Point3DStruct; typedef double Pt3[3]; typedef struct conv2dstruct { double a1; // X = a1*x + b1*y + c1 double b1; // Y = a2*x + b2*y + c2 double c1; // a1, b1 a2, b2 in {-1,0,1} double a2; // c1, c2 in {0,1} double b2; double c2; int ia; // I = ia*i + ib*j + ic int ib; int ic; int ja; // J = ja*i + jb*j + jc int jb; int jc; } Conv2DStruct; typedef struct cubeStruct { TopoDS_Vertex V000; TopoDS_Vertex V001; TopoDS_Vertex V010; TopoDS_Vertex V011; TopoDS_Vertex V100; TopoDS_Vertex V101; TopoDS_Vertex V110; TopoDS_Vertex V111; faceQuadStruct* quad_X0; faceQuadStruct* quad_X1; faceQuadStruct* quad_Y0; faceQuadStruct* quad_Y1; faceQuadStruct* quad_Z0; faceQuadStruct* quad_Z1; Point3DStruct* np; // normalised 3D coordinates } CubeStruct; class SMESH_Hexa_3D: public SMESH_3D_Algo { public: SMESH_Hexa_3D(int hypId, int studyId, SMESH_Gen* gen); virtual ~SMESH_Hexa_3D(); virtual bool CheckHypothesis(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape); virtual bool Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) throw (SALOME_Exception); ostream & SaveTo(ostream & save); istream & LoadFrom(istream & load); friend ostream & operator << (ostream & save, SMESH_Hexa_3D & hyp); friend istream & operator >> (istream & load, SMESH_Hexa_3D & hyp); protected: TopoDS_Edge EdgeNotInFace(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape, const TopoDS_Face& aFace, const TopoDS_Vertex& aVertex, const TopTools_IndexedDataMapOfShapeListOfShape& MS); int GetFaceIndex(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape, const vector<SMESH_subMesh*>& meshFaces, const TopoDS_Vertex& V0, const TopoDS_Vertex& V1, const TopoDS_Vertex& V2, const TopoDS_Vertex& V3); void GetConv2DCoefs(const faceQuadStruct& quad, const TopoDS_Shape& aShape, const TopoDS_Vertex& V0, const TopoDS_Vertex& V1, const TopoDS_Vertex& V2, const TopoDS_Vertex& V3, Conv2DStruct& conv); void GetPoint(Pt3 p, int i, int j, int k, int nbx, int nby, int nbz, Point3DStruct *np, const SMESHDS_Mesh* meshDS); CubeStruct _cube; FaceQuadStruct* _quads[6]; int _indX0; int _indX1; int _indY0; int _indY1; int _indZ0; int _indZ1; }; #endif <|endoftext|>
<commit_before>#include "HexShape.h" #include "LinTetShape.h" #include "QuadTetShape.h" #include "BarShape.h" #include "LMEShape.h" #include "MRKPMShape.h" using namespace voom; int main() { cout << endl << "Testing voom shape classes... " << endl; cout << ".............................." << endl << endl; // HexShape testing { cout << "Testing HexShape" << endl; Vector3d Point3D = Vector3d::Zero(); srand( time(NULL) ); Point3D(0) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point3D(1) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point3D(2) = 2.0*(Real(rand())/RAND_MAX - 0.5); HexShape HexShp(Point3D); HexShp.checkConsistency(Point3D); HexShp.checkPartitionUnity(Point3D); } // TetShape testing { Vector3d Point3D = Vector3d::Zero(); srand( time(NULL) ); Point3D(0) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point3D(1) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point3D(2) = 2.0*(Real(rand())/RAND_MAX - 0.5); cout << "Testing LinTetShape" << endl; LinTetShape LinTetShp(Point3D); LinTetShp.checkConsistency(Point3D); LinTetShp.checkPartitionUnity(Point3D); cout << "Testing QuadTetShape" << endl; QuadTetShape QuadTetShp(Point3D); QuadTetShp.checkConsistency(Point3D); QuadTetShp.checkPartitionUnity(Point3D); } // BarShape testing { cout << "Testing BarShape" << endl; VectorXd Point1D = VectorXd::Zero(1); srand( time(NULL) ); Point1D(0) = 2.0*(Real(rand())/RAND_MAX - 0.5); BarShape BarShp(Point1D); BarShp.checkConsistency(Point1D); BarShp.checkPartitionUnity(Point1D); } // LMEshape testing { cout << "Testing LMEshape (cube domain)" << endl; vector<VectorXd > Nodes(8, Vector3d::Zero(3)); Nodes[0] << 0.0, 0.0, 0.0; Nodes[1] << 1.0, 0.0, 0.0; Nodes[2] << 1.0, 1.0, 0.0; Nodes[3] << 0.0, 1.0, 0.0; Nodes[4] << 0.0, 0.0, 1.0; Nodes[5] << 1.0, 0.0, 1.0; Nodes[6] << 1.0, 1.0, 1.0; Nodes[7] << 0.0, 1.0, 1.0; VectorXd Point(3); Point << 0.4, 0.5, 0.6; Real beta = 0.8, tol = 1.0e-12; uint maxIter = 20; LMEShape LMEshp(Nodes, Point, beta, tol, maxIter); LMEshp.update(Point); cout << "Print LME at [0.4, 0.5, 0.6]" << endl; for (uint i=0; i<LMEshp.getShapeFunctionNum(); i++) { cout << "Node = " << i << " N = " << LMEshp.getN(i) << " DN = "; for (uint j=0; j<Point.size(); j++) { cout << LMEshp.getDN(i,j) << " "; }; cout << endl; }; // Check consistency Point(0) = (Real(rand())/RAND_MAX ); Point(1) = (Real(rand())/RAND_MAX ); Point(2) = (Real(rand())/RAND_MAX ); cout << "Check consistency at Point " << Point.transpose() << endl; LMEshp.checkConsistency(Point, 1.0e-8, 1.0e-6); LMEshp.checkPartitionUnity(Point); LMEshp.checkReproducingCondition(Point, 1.0e-6); } { cout << "Testing LMEshape (tet domain)" << endl; vector<VectorXd > Nodes(4, Vector3d::Zero(3)); Nodes[0] << 0.0, 0.0, 0.0; Nodes[1] << 1.0, 0.0, 0.0; Nodes[2] << 0.0, 1.0, 0.0; Nodes[3] << 0.0, 0.0, 1.0; VectorXd Point(3); Point << 0.2, 0.1, 0.3; Real beta = 0.8, tol = 1.0e-12; uint maxIter = 20; LMEShape LMEshp(Nodes, Point, beta, tol, maxIter); LMEshp.update(Point); cout << "Print LME at [0.2, 0.1, 0.3]" << endl; for (uint i=0; i<LMEshp.getShapeFunctionNum(); i++) { cout << "Node = " << i << " N = " << LMEshp.getN(i) << " DN = "; for (uint j=0; j<Point.size(); j++) { cout << LMEshp.getDN(i,j) << " "; }; cout << endl; }; // Check consistency Point(0) = (Real(rand())/RAND_MAX )*0.25; Point(1) = (Real(rand())/RAND_MAX )*0.25; Point(2) = (Real(rand())/RAND_MAX )*0.25; cout << "Check consistency at Point " << Point.transpose() << endl; LMEshp.checkConsistency(Point, 1.0e-8, 1.0e-6); LMEshp.checkPartitionUnity(Point); LMEshp.checkReproducingCondition(Point, 1.0e-6); } // MRKPMshape testing { // using same points as LME const Real radius = 0.001, support = 1.414, supportHat = 1.0; VectorXd Point2D(2); Point2D(0) = Point2D(1) = 0.5; vector<VectorXd > Nodes2D(4, Vector2d::Zero(2)); Nodes2D[0] << 0.0, 0.0; Nodes2D[1] << 1.0, 0.0; Nodes2D[2] << 1.0, 1.0; Nodes2D[3] << 0.0, 1.0; MRKPMShape MRKPMshp(Nodes2D, Point2D, support, radius, supportHat); cout << "Print MRKPM at [0.5, 0.5]" << endl; for (uint i=0; i<MRKPMshp.getShapeFunctionNum(); i++) { cout << "Node = " << i << " N = " << MRKPMshp.getN(i) << " DN = "; for (uint j=0; j<Point2D.size(); j++) { cout << MRKPMshp.getDN(i,j) << " "; }; cout << endl; }; Point2D(0) = (Real(rand())/RAND_MAX ); Point2D(1) = (Real(rand())/RAND_MAX ); cout << "Check consistency at Point " << Point2D.transpose() << endl; MRKPMshp.checkConsistency(Point2D, 1.0e-8, 1.0e-6); MRKPMshp.checkPartitionUnity(Point2D); MRKPMshp.checkReproducingCondition(Point2D, 1.0e-7); } } <commit_msg>New code<commit_after>#include "HexShape.h" #include "LinTetShape.h" #include "QuadTetShape.h" #include "LinTriShape.h" #include "QuadTriShape.h" #include "BarShape.h" #include "LMEShape.h" #include "MRKPMShape.h" using namespace voom; int main() { cout << endl << "Testing voom shape classes... " << endl; cout << ".............................." << endl << endl; // HexShape testing { cout << "Testing HexShape" << endl; Vector3d Point3D = Vector3d::Zero(); srand( time(NULL) ); Point3D(0) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point3D(1) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point3D(2) = 2.0*(Real(rand())/RAND_MAX - 0.5); HexShape HexShp(Point3D); HexShp.checkConsistency(Point3D); HexShp.checkPartitionUnity(Point3D); } // TetShape testing { Vector3d Point3D = Vector3d::Zero(); srand( time(NULL) ); Point3D(0) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point3D(1) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point3D(2) = 2.0*(Real(rand())/RAND_MAX - 0.5); cout << "Testing LinTetShape" << endl; LinTetShape LinTetShp(Point3D); LinTetShp.checkConsistency(Point3D); LinTetShp.checkPartitionUnity(Point3D); cout << "Testing QuadTetShape" << endl; QuadTetShape QuadTetShp(Point3D); QuadTetShp.checkConsistency(Point3D); QuadTetShp.checkPartitionUnity(Point3D); } // TriShape testing { Vector2d Point2D = Vector2d::Zero(); srand( time(NULL) ); Point2D(0) = 2.0*(Real(rand())/RAND_MAX - 0.5); Point2D(1) = 2.0*(Real(rand())/RAND_MAX - 0.5); cout << "Testing LinTriShape" << endl; LinTriShape LinTriShp(Point2D); LinTriShp.checkConsistency(Point2D); LinTriShp.checkPartitionUnity(Point2D); cout << "Testing QuadTriShape" << endl; QuadTriShape QuadTriShp(Point2D); QuadTriShp.checkConsistency(Point2D); QuadTriShp.checkPartitionUnity(Point2D); } // BarShape testing { cout << "Testing BarShape" << endl; VectorXd Point1D = VectorXd::Zero(1); srand( time(NULL) ); Point1D(0) = 2.0*(Real(rand())/RAND_MAX - 0.5); BarShape BarShp(Point1D); BarShp.checkConsistency(Point1D); BarShp.checkPartitionUnity(Point1D); } // LMEshape testing { cout << "Testing LMEshape (cube domain)" << endl; vector<VectorXd > Nodes(8, Vector3d::Zero(3)); Nodes[0] << 0.0, 0.0, 0.0; Nodes[1] << 1.0, 0.0, 0.0; Nodes[2] << 1.0, 1.0, 0.0; Nodes[3] << 0.0, 1.0, 0.0; Nodes[4] << 0.0, 0.0, 1.0; Nodes[5] << 1.0, 0.0, 1.0; Nodes[6] << 1.0, 1.0, 1.0; Nodes[7] << 0.0, 1.0, 1.0; VectorXd Point(3); Point << 0.4, 0.5, 0.6; Real beta = 0.8, tol = 1.0e-12; uint maxIter = 20; LMEShape LMEshp(Nodes, Point, beta, tol, maxIter); LMEshp.update(Point); cout << "Print LME at [0.4, 0.5, 0.6]" << endl; for (uint i=0; i<LMEshp.getShapeFunctionNum(); i++) { cout << "Node = " << i << " N = " << LMEshp.getN(i) << " DN = "; for (uint j=0; j<Point.size(); j++) { cout << LMEshp.getDN(i,j) << " "; }; cout << endl; }; // Check consistency Point(0) = (Real(rand())/RAND_MAX ); Point(1) = (Real(rand())/RAND_MAX ); Point(2) = (Real(rand())/RAND_MAX ); cout << "Check consistency at Point " << Point.transpose() << endl; LMEshp.checkConsistency(Point, 1.0e-8, 1.0e-6); LMEshp.checkPartitionUnity(Point); LMEshp.checkReproducingCondition(Point, 1.0e-6); } { cout << "Testing LMEshape (tet domain)" << endl; vector<VectorXd > Nodes(4, Vector3d::Zero(3)); Nodes[0] << 0.0, 0.0, 0.0; Nodes[1] << 1.0, 0.0, 0.0; Nodes[2] << 0.0, 1.0, 0.0; Nodes[3] << 0.0, 0.0, 1.0; VectorXd Point(3); Point << 0.2, 0.1, 0.3; Real beta = 0.8, tol = 1.0e-12; uint maxIter = 20; LMEShape LMEshp(Nodes, Point, beta, tol, maxIter); LMEshp.update(Point); cout << "Print LME at [0.2, 0.1, 0.3]" << endl; for (uint i=0; i<LMEshp.getShapeFunctionNum(); i++) { cout << "Node = " << i << " N = " << LMEshp.getN(i) << " DN = "; for (uint j=0; j<Point.size(); j++) { cout << LMEshp.getDN(i,j) << " "; }; cout << endl; }; // Check consistency Point(0) = (Real(rand())/RAND_MAX )*0.25; Point(1) = (Real(rand())/RAND_MAX )*0.25; Point(2) = (Real(rand())/RAND_MAX )*0.25; cout << "Check consistency at Point " << Point.transpose() << endl; LMEshp.checkConsistency(Point, 1.0e-8, 1.0e-6); LMEshp.checkPartitionUnity(Point); LMEshp.checkReproducingCondition(Point, 1.0e-6); } // MRKPMshape testing { // using same points as LME const Real radius = 0.001, support = 1.414, supportHat = 1.0; VectorXd Point2D(2); Point2D(0) = Point2D(1) = 0.5; vector<VectorXd > Nodes2D(4, Vector2d::Zero(2)); Nodes2D[0] << 0.0, 0.0; Nodes2D[1] << 1.0, 0.0; Nodes2D[2] << 1.0, 1.0; Nodes2D[3] << 0.0, 1.0; MRKPMShape MRKPMshp(Nodes2D, Point2D, support, radius, supportHat); cout << "Print MRKPM at [0.5, 0.5]" << endl; for (uint i=0; i<MRKPMshp.getShapeFunctionNum(); i++) { cout << "Node = " << i << " N = " << MRKPMshp.getN(i) << " DN = "; for (uint j=0; j<Point2D.size(); j++) { cout << MRKPMshp.getDN(i,j) << " "; }; cout << endl; }; Point2D(0) = (Real(rand())/RAND_MAX ); Point2D(1) = (Real(rand())/RAND_MAX ); cout << "Check consistency at Point " << Point2D.transpose() << endl; MRKPMshp.checkConsistency(Point2D, 1.0e-8, 1.0e-6); MRKPMshp.checkPartitionUnity(Point2D); MRKPMshp.checkReproducingCondition(Point2D, 1.0e-7); } } <|endoftext|>
<commit_before>// SolLimTests.cpp #include <deque> #include <map> #include <gtest/gtest.h> #include "SolLim.h" #include "NuclideModel.h" #include "CycException.h" #include "Material.h" using namespace std; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class SolLimTest : public ::testing::Test { protected: CompMapPtr test_comp_; mat_rsrc_ptr test_mat_; int one_mol_; int u235_, am241_; int u_; double test_size_; Radius r_four_, r_five_; Length len_five_; point_t origin_; int time_; double K_d_; virtual void SetUp(){ // composition set up u235_=92235; u_=92; one_mol_=1.0; test_comp_= CompMapPtr(new CompMap(MASS)); (*test_comp_)[u235_] = one_mol_; test_size_=10.0; // material creation test_mat_ = mat_rsrc_ptr(new Material(test_comp_)); test_mat_->setQuantity(test_size_); // useful numbers K_d_ = 0.001; } virtual void TearDown() { } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_f){ double V_f, V_s, m_T; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=10.*i; // Generally meets expectations double expected = (m_T*V_s/V_f)*(1/(K_d_-K_d_*V_f/V_s + V_f/V_s)); EXPECT_FLOAT_EQ(expected, SolLim::m_f(m_T, K_d_, V_s, V_f)); // If the contaminant mass is zero, there is no m_f EXPECT_FLOAT_EQ(0, SolLim::m_f(0, K_d_, V_s, V_f)); // If the K_d is zero, there is no sorption and m_f = m_T. EXPECT_FLOAT_EQ(m_T, SolLim::m_f(m_T, 0, V_s, V_f)); // If solid volume is zero, there is no sorption and m_f = m_T. EXPECT_FLOAT_EQ(m_T, SolLim::m_f(m_T, K_d_, 0, V_f)); // If fluid volume is zero, sorption is total and m_f = 0. EXPECT_FLOAT_EQ(0, SolLim::m_f(m_T, K_d_, V_s, 0)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_s){ double V_f, V_s, m_T; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; // Generally meets expectations double expected = K_d_*(V_s/V_f)*(m_T*V_s/V_f)*(1/(K_d_-K_d_*V_f/V_s + V_f/V_s)); EXPECT_FLOAT_EQ(expected, SolLim::m_s(m_T, K_d_, V_s, V_f)); // If the contaminant mass is zero, there is no m_T EXPECT_FLOAT_EQ(0, SolLim::m_s(0, K_d_, V_s, V_f)); // If the K_d is zero, there is no sorption and m_s = 0. EXPECT_FLOAT_EQ(0, SolLim::m_s(m_T, 0, V_s, V_f)); // If solid volume is zero, there is no sorption and m_s = 0 EXPECT_FLOAT_EQ(0, SolLim::m_s(m_T, K_d_, 0, V_f)); // If fluid volume is zero, sorption is total and m_s = m_T. EXPECT_FLOAT_EQ(m_T, SolLim::m_s(m_T, K_d_, V_s, 0)); EXPECT_FLOAT_EQ((K_d_*(V_s/V_f))*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_s(m_T, K_d_, V_s, V_f)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_ds){ double V_f, V_s, m_T, d; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ(d*(K_d_*(V_s/V_f))*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_ds(m_T, K_d_, V_s, V_f, d)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_ms){ double V_f, V_s, m_T, d; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ((1-d)*(K_d_*(V_s/V_f))*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_ms(m_T, K_d_, V_s, V_f, d)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_ff){ double V_f, V_s, m_T, d; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ(d*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_ff(m_T, K_d_, V_s, V_f, d)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_mf){ double V_f, V_s, m_T, d; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ((1-d)*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_mf(m_T, K_d_, V_s, V_f, d)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_aff){ double V_f, V_ff, V_s, m_T, d; double C_sol; double expected, mff; for(int c = 0; c<100; c++){ C_sol = 0.1/c; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; V_ff=V_f*d; mff= SolLim::m_ff(m_T, K_d_, V_s, V_f, d); EXPECT_FLOAT_EQ(0, SolLim::m_aff(mff, V_ff, 0)); expected = min(C_sol*V_ff, d*m_T/(1+K_d_*(V_s/V_f))); EXPECT_FLOAT_EQ(expected, SolLim::m_aff(mff, V_ff, C_sol)); EXPECT_GE(mff, SolLim::m_aff(mff, V_ff, C_sol)); } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_aff_kd0){ double V_f, V_ff, V_s, m_T, d; double C_sol; double expected, mff; for(int c = 0; c<100; c++){ C_sol = 0.1/c; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; V_ff=V_f*d; mff= SolLim::m_ff(m_T, 0, V_s, V_f, d); EXPECT_FLOAT_EQ(0, SolLim::m_aff(mff, V_ff, 0)); expected = min(C_sol*V_ff, d*m_T/(1+0*(V_s/V_f))); EXPECT_FLOAT_EQ(expected, SolLim::m_aff(mff, V_ff, C_sol)); EXPECT_GE(mff, SolLim::m_aff(mff, V_ff, C_sol)); } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_ps){ double V_f, V_s, m_T, d; double C_sol = 0.001; double expected; double m_ff; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ(0, SolLim::m_ps(m_T, K_d_, V_s, V_f, d, 10000)); m_ff = (d)*m_T/(1+K_d_*(V_s/V_f)); expected = m_ff - min(C_sol*V_f, m_ff); EXPECT_FLOAT_EQ(expected, SolLim::m_ps(m_T, K_d_, V_s, V_f, d, C_sol)); EXPECT_FLOAT_EQ(expected, SolLim::m_ps(m_T, K_d_, V_s, V_f, d, C_sol)); } } <commit_msg>now we trust m_f so we can refer to it in other tests<commit_after>// SolLimTests.cpp #include <deque> #include <map> #include <gtest/gtest.h> #include "SolLim.h" #include "NuclideModel.h" #include "CycException.h" #include "Material.h" using namespace std; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class SolLimTest : public ::testing::Test { protected: CompMapPtr test_comp_; mat_rsrc_ptr test_mat_; int one_mol_; int u235_, am241_; int u_; double test_size_; Radius r_four_, r_five_; Length len_five_; point_t origin_; int time_; double K_d_; virtual void SetUp(){ // composition set up u235_=92235; u_=92; one_mol_=1.0; test_comp_= CompMapPtr(new CompMap(MASS)); (*test_comp_)[u235_] = one_mol_; test_size_=10.0; // material creation test_mat_ = mat_rsrc_ptr(new Material(test_comp_)); test_mat_->setQuantity(test_size_); // useful numbers K_d_ = 0.001; } virtual void TearDown() { } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_f){ double V_f, V_s, m_T; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=10.*i; // Generally meets expectations double expected = (m_T*V_s/V_f)*(1/(K_d_-K_d_*V_f/V_s + V_f/V_s)); EXPECT_FLOAT_EQ(expected, SolLim::m_f(m_T, K_d_, V_s, V_f)); // If the contaminant mass is zero, there is no m_f EXPECT_FLOAT_EQ(0, SolLim::m_f(0, K_d_, V_s, V_f)); // If the K_d is zero, there is no sorption and m_f = m_T. EXPECT_FLOAT_EQ(m_T, SolLim::m_f(m_T, 0, V_s, V_f)); // If solid volume is zero, there is no sorption and m_f = m_T. EXPECT_FLOAT_EQ(m_T, SolLim::m_f(m_T, K_d_, 0, V_f)); // If fluid volume is zero, sorption is total and m_f = 0. EXPECT_FLOAT_EQ(0, SolLim::m_f(m_T, K_d_, V_s, 0)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_s){ double V_f, V_s, m_T; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; // Generally meets expectations double expected = K_d_*(V_s/V_f)*(m_T*V_s/V_f)*(1/(K_d_-K_d_*V_f/V_s + V_f/V_s)); EXPECT_FLOAT_EQ(expected, SolLim::m_s(m_T, K_d_, V_s, V_f)); // If the contaminant mass is zero, there is no m_T EXPECT_FLOAT_EQ(0, SolLim::m_s(0, K_d_, V_s, V_f)); // If the K_d is zero, there is no sorption and m_s = 0. EXPECT_FLOAT_EQ(0, SolLim::m_s(m_T, 0, V_s, V_f)); // If solid volume is zero, there is no sorption and m_s = 0 EXPECT_FLOAT_EQ(0, SolLim::m_s(m_T, K_d_, 0, V_f)); // If fluid volume is zero, sorption is total and m_s = m_T. EXPECT_FLOAT_EQ(m_T, SolLim::m_s(m_T, K_d_, V_s, 0)); EXPECT_FLOAT_EQ((K_d_*(V_s/V_f))*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_s(m_T, K_d_, V_s, V_f)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_ds){ double V_f, V_s, m_T, d; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ(d*(K_d_*(V_s/V_f))*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_ds(m_T, K_d_, V_s, V_f, d)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_ms){ double V_f, V_s, m_T, d; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ((1-d)*(K_d_*(V_s/V_f))*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_ms(m_T, K_d_, V_s, V_f, d)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_ff){ double V_f, V_s, m_T, d; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ(d*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_ff(m_T, K_d_, V_s, V_f, d)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_mf){ double V_f, V_s, m_T, d; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ((1-d)*SolLim::m_f(m_T, K_d_,V_s, V_f), SolLim::m_mf(m_T, K_d_, V_s, V_f, d)); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_aff){ double V_f, V_ff, V_s, m_T, d; double C_sol; double expected, mff; for(int c = 0; c<100; c++){ C_sol = 0.1/c; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; V_ff=V_f*d; mff= SolLim::m_ff(m_T, K_d_, V_s, V_f, d); EXPECT_FLOAT_EQ(0, SolLim::m_aff(mff, V_ff, 0)); expected = min(C_sol*V_ff, d*SolLim::m_f(m_T, K_d_, V_s, V_f)); EXPECT_FLOAT_EQ(expected, SolLim::m_aff(mff, V_ff, C_sol)); EXPECT_GE(mff, SolLim::m_aff(mff, V_ff, C_sol)); } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_aff_kd0){ double V_f, V_ff, V_s, m_T, d; double C_sol; double expected, mff; for(int c = 0; c<100; c++){ C_sol = 0.1/c; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; V_ff=V_f*d; mff= SolLim::m_ff(m_T, 0, V_s, V_f, d); EXPECT_FLOAT_EQ(0, SolLim::m_aff(mff, V_ff, 0)); expected = min(C_sol*V_ff, d*SolLim::m_f(m_T, 0, V_s, V_f)); EXPECT_FLOAT_EQ(expected, SolLim::m_aff(mff, V_ff, C_sol)); EXPECT_GE(mff, SolLim::m_aff(mff, V_ff, C_sol)); } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TEST_F(SolLimTest, m_ps){ double V_f, V_s, m_T, d; double C_sol = 0.001; double expected; double m_ff; for(int i=1; i<10; i++){ V_f=0.1*i; V_s=0.1*i; m_T=0.1*i; d=0.1*i; EXPECT_FLOAT_EQ(0, SolLim::m_ps(m_T, K_d_, V_s, V_f, d, 10000)); m_ff = (d)*m_T/(1+K_d_*(V_s/V_f)); expected = m_ff - min(C_sol*V_f, m_ff); EXPECT_FLOAT_EQ(expected, SolLim::m_ps(m_T, K_d_, V_s, V_f, d, C_sol)); EXPECT_FLOAT_EQ(expected, SolLim::m_ps(m_T, K_d_, V_s, V_f, d, C_sol)); } } <|endoftext|>
<commit_before>/* Copyright 2007-2015 QReal Research Group * * 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 "boundRegion.h" #include <QtXml/QDomElement> using namespace twoDModel::items; const int defaultStroke = 0; BoundRegion::BoundRegion(const QGraphicsObject &boundItem, const QString &boundId, QGraphicsItem *parent) : RegionItem(parent) , mBoundItem(boundItem) , mBoundId(boundId) , mStroke(defaultStroke) { // We should dispose this item if bound item is deleted. connect(&mBoundItem, &QObject::destroyed, this, &QObject::deleteLater); } int BoundRegion::stroke() const { return mStroke; } void BoundRegion::setStroke(int stroke) { mStroke = stroke; } void BoundRegion::serialize(QDomElement &element) { RegionItem::serialize(element); element.setAttribute("boundItem", mBoundId); element.setAttribute("stroke", mStroke); } void BoundRegion::deserialize(const QDomElement &element) { RegionItem::deserialize(element); if (element.hasAttribute("stroke")) { bool ok = false; const int stroke = element.attribute("stroke").toInt(&ok); if (ok) { mStroke = stroke; } } } QRectF BoundRegion::boundingRect() const { return mBoundItem.boundingRect().adjusted(-mStroke, -mStroke, mStroke, mStroke); } QPainterPath BoundRegion::shape() const { if (!mStroke) { return mBoundItem.shape(); } QPainterPathStroker stroker; stroker.setWidth(mStroke); return stroker.createStroke(mBoundItem.shape()); } QString BoundRegion::regionType() const { return "bound"; } <commit_msg>Fixed holes in regions bound to line item<commit_after>/* Copyright 2007-2015 QReal Research Group * * 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 "boundRegion.h" #include <src/engine/items/lineItem.h> #include <QtXml/QDomElement> using namespace twoDModel::items; const int defaultStroke = 0; BoundRegion::BoundRegion(const QGraphicsObject &boundItem, const QString &boundId, QGraphicsItem *parent) : RegionItem(parent) , mBoundItem(boundItem) , mBoundId(boundId) , mStroke(defaultStroke) { // We should dispose this item if bound item is deleted. connect(&mBoundItem, &QObject::destroyed, this, &QObject::deleteLater); } int BoundRegion::stroke() const { return mStroke; } void BoundRegion::setStroke(int stroke) { mStroke = stroke; } void BoundRegion::serialize(QDomElement &element) { RegionItem::serialize(element); element.setAttribute("boundItem", mBoundId); element.setAttribute("stroke", mStroke); } void BoundRegion::deserialize(const QDomElement &element) { RegionItem::deserialize(element); if (element.hasAttribute("stroke")) { bool ok = false; const int stroke = element.attribute("stroke").toInt(&ok); if (ok) { mStroke = stroke; } } } QRectF BoundRegion::boundingRect() const { return mBoundItem.boundingRect().adjusted(-mStroke, -mStroke, mStroke, mStroke); } QPainterPath BoundRegion::shape() const { const QPainterPath originalShape = mBoundItem.shape(); if (!mStroke) { return originalShape; } QPainterPathStroker stroker; stroker.setWidth(mStroke); const QPainterPath result = stroker.createStroke(originalShape); return dynamic_cast<const LineItem *>(&mBoundItem) ? result.united(originalShape) : result; } QString BoundRegion::regionType() const { return "bound"; } <|endoftext|>
<commit_before>#include <QtCore/QCoreApplication> #include <QtWidgets/QApplication> #include <QQmlApplicationEngine> #include <QPluginLoader> #include <QDebug> #include "Tools.h" using namespace sofa::qtquick; int main(int argc, char **argv) { // TODO: this command disable the multithreaded render loop, currently we need this on Linux/OSX because our implementation of the sofa interface is not thread-safe qputenv("QML_BAD_GUI_RENDER_LOOP", "1"); QApplication app(argc, argv); app.addLibraryPath(QCoreApplication::applicationDirPath() + "/../lib/"); // application specific settings app.setOrganizationName("Sofa"); app.setApplicationName("qtQuickSofa"); QSettings::setPath(QSettings::Format::IniFormat, QSettings::Scope::UserScope, "./user/config/"); QSettings::setDefaultFormat(QSettings::Format::IniFormat); // use the default.ini settings if it is the first time the user launch the application Tools::useDefaultSettingsAtFirstLaunch(); // plugin initialization QString pluginName("SofaQtQuickGUI"); #ifdef SOFA_LIBSUFFIX pluginName += sofa_tostring(SOFA_LIBSUFFIX); #endif QPluginLoader pluginLoader(pluginName); // first call to instance() initialize the plugin if(0 == pluginLoader.instance()) { qCritical() << "SofaQtQuickGUI plugin has not been found!"; return -1; } // launch the main script QQmlApplicationEngine applicationEngine; applicationEngine.addImportPath("qrc:/"); applicationEngine.load(QUrl("qrc:/qml/Main.qml")); return app.exec(); } <commit_msg>FIX application config path<commit_after>#include <QtCore/QCoreApplication> #include <QtWidgets/QApplication> #include <QQmlApplicationEngine> #include <QPluginLoader> #include <QDebug> #include "Tools.h" using namespace sofa::qtquick; int main(int argc, char **argv) { // TODO: this command disable the multithreaded render loop, currently we need this on Linux/OSX because our implementation of the sofa interface is not thread-safe qputenv("QML_BAD_GUI_RENDER_LOOP", "1"); QApplication app(argc, argv); app.addLibraryPath(QCoreApplication::applicationDirPath() + "/../lib/"); // application specific settings app.setOrganizationName("Sofa"); app.setApplicationName("qtQuickSofa"); QSettings::setPath(QSettings::Format::IniFormat, QSettings::Scope::UserScope, QCoreApplication::applicationDirPath() + "/config/"); QSettings::setDefaultFormat(QSettings::Format::IniFormat); // use the default.ini settings if it is the first time the user launch the application Tools::useDefaultSettingsAtFirstLaunch(); // plugin initialization QString pluginName("SofaQtQuickGUI"); #ifdef SOFA_LIBSUFFIX pluginName += sofa_tostring(SOFA_LIBSUFFIX); #endif QPluginLoader pluginLoader(pluginName); // first call to instance() initialize the plugin if(0 == pluginLoader.instance()) { qCritical() << "SofaQtQuickGUI plugin has not been found!"; return -1; } // launch the main script QQmlApplicationEngine applicationEngine; applicationEngine.addImportPath("qrc:/"); applicationEngine.load(QUrl("qrc:/qml/Main.qml")); return app.exec(); } <|endoftext|>
<commit_before>#include <pybind11/embed.h> #include <iostream> #include <string> namespace py = pybind11; #include "app_config_impl.h" #include "load_module.h" #pragma GCC visibility push(hidden) class AppConfigImpl : public virtual AppConfig { public: AppConfigImpl(); virtual ~AppConfigImpl() = default; public: virtual std::string GetEntry(const char * path, const char * default_value) override; virtual int64_t GetEntryInt64(const char * path, int64_t default_value) override; virtual uint64_t GetEntryUInt64(const char * path, uint64_t default_value) override; virtual bool GetEntryBool(const char * path, bool default_value) override; virtual bool LoadFromFile(const char * file_path) override; private: void ResetDefaults(); bool m_Loaded; py::object m_AppConfig; }; std::shared_ptr<AppConfig> g_AppConfig {new AppConfigImpl()}; AppConfigImpl::AppConfigImpl() { ResetDefaults(); } std::string AppConfigImpl::GetEntry(const char * path, const char * default_value) { return m_AppConfig.attr("get")(path, py::cast(default_value)).cast<std::string>(); } int64_t AppConfigImpl::GetEntryInt64(const char * path, int64_t default_value) { return m_AppConfig.attr("get")(path, py::cast(default_value)).cast<int64_t>(); } uint64_t AppConfigImpl::GetEntryUInt64(const char * path, uint64_t default_value) { return m_AppConfig.attr("get")(path, py::cast(default_value)).cast<uint64_t>(); } bool AppConfigImpl::GetEntryBool(const char * path, bool default_value) { return m_AppConfig.attr("get")(path, py::cast(default_value)).cast<bool>(); } bool AppConfigImpl::LoadFromFile(const char * file_path) { try { const char *module_content = #include "app_config.inc" ; m_AppConfig = LoadModuleFromString(module_content, "app_config", "app_config.py").attr("load_config")(file_path); m_Loaded = true; } catch(std::exception & e) { std::cerr << "load configuration from file:" << file_path << " failed!" << std::endl << e.what() << std::endl; m_Loaded = false; } catch(...) { std::cerr << "load configuration from file:" << file_path << " failed!" << std::endl; PyErr_Print(); m_Loaded = false; } return m_Loaded; } void AppConfigImpl::ResetDefaults() { m_Loaded = false; } #pragma GCC visibility pop <commit_msg>return default value if config is not loaded<commit_after>#include <pybind11/embed.h> #include <iostream> #include <string> namespace py = pybind11; #include "app_config_impl.h" #include "load_module.h" #pragma GCC visibility push(hidden) class AppConfigImpl : public virtual AppConfig { public: AppConfigImpl(); virtual ~AppConfigImpl() = default; public: virtual std::string GetEntry(const char * path, const char * default_value) override; virtual int64_t GetEntryInt64(const char * path, int64_t default_value) override; virtual uint64_t GetEntryUInt64(const char * path, uint64_t default_value) override; virtual bool GetEntryBool(const char * path, bool default_value) override; virtual bool LoadFromFile(const char * file_path) override; private: void ResetDefaults(); bool m_bLoaded; py::object m_AppConfig; }; std::shared_ptr<AppConfig> g_AppConfig {new AppConfigImpl()}; AppConfigImpl::AppConfigImpl() { ResetDefaults(); } std::string AppConfigImpl::GetEntry(const char * path, const char * default_value) { return m_bLoaded ? m_AppConfig.attr("get")(path, py::cast(default_value)).cast<std::string>() : default_value; } int64_t AppConfigImpl::GetEntryInt64(const char * path, int64_t default_value) { return m_bLoaded ? m_AppConfig.attr("get")(path, py::cast(default_value)).cast<int64_t>() : default_value; } uint64_t AppConfigImpl::GetEntryUInt64(const char * path, uint64_t default_value) { return m_bLoaded ? m_AppConfig.attr("get")(path, py::cast(default_value)).cast<uint64_t>() : default_value; } bool AppConfigImpl::GetEntryBool(const char * path, bool default_value) { return m_bLoaded ? m_AppConfig.attr("get")(path, py::cast(default_value)).cast<bool>() : default_value; } bool AppConfigImpl::LoadFromFile(const char * file_path) { try { const char *module_content = #include "app_config.inc" ; m_AppConfig = LoadModuleFromString(module_content, "app_config", "app_config.py").attr("load_config")(file_path); m_bLoaded = true; } catch(std::exception & e) { std::cerr << "load configuration from file:" << file_path << " failed!" << std::endl << e.what() << std::endl; m_bLoaded = false; } catch(...) { std::cerr << "load configuration from file:" << file_path << " failed!" << std::endl; PyErr_Print(); m_bLoaded = false; } return m_bLoaded; } void AppConfigImpl::ResetDefaults() { m_bLoaded = false; } #pragma GCC visibility pop <|endoftext|>
<commit_before>#include "vision/BackboardFinder.h" #include "vision/BetterBinaryImage.h" #include <math.h> #include "WPILib.h" #include "util/Logger.h" #include "config/Constants.h" #include "subsystems/Drive.h" BackboardFinder::BackboardFinder(Drive* drive) : VisionProcess() { cameraLog_ = new Logger("/cameraLog.log"); printf("Initting camera\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); width_ = 0; vDiff_ = 0; constants_ = Constants::GetInstance(); useTopForWidth_ = false; drive_ = drive; useSkew_ = true; //camera.WriteResolution(AxisCameraParams::kResolution_320x240); } double BackboardFinder::GetX() { if (-1.0 <= x_ && x_ <= 1.0) { return x_; } else { // printf("Bad x val :( %f\n", x_); return 0; } } double BackboardFinder::GetHDiff() { return width_; } double BackboardFinder::GetVDiff() { return vDiff_; } bool BackboardFinder::SeesTarget() { return HasFreshTarget() && seesTarget_; } void BackboardFinder::LogCamera() { cameraLog_->Log("%f,%f,%f\n", GetX(), width_, vDiff_); } double BackboardFinder::GetDistance() { double w = width_; if (useTopForWidth_) { w += 7; // difference between target width and side to side distance } return constants_->distanceCoeffA * pow(width_, 6) + constants_->distanceCoeffB * pow(width_, 5) + constants_->distanceCoeffC * pow(width_, 4) + constants_->distanceCoeffD * pow(width_, 3) + constants_->distanceCoeffE * pow(width_, 2) + constants_->distanceCoeffF * width_ + constants_->distanceCoeffG; } double BackboardFinder::GetAngle() { //normalized x location (-1 to 1) times the pixels along //that one side = number of pixels off //47/320 = degree/pixel based on fov/horizontal resolution //pixels * degrees / pixels = degrees //printf("get: %f\n", (float) GetX()); double offset = Constants::GetInstance()->cameraOffset; double ret = GetX() * 160.0 * 47.0 / 320.0 + offset; if (useSkew_) { ret += (orientation_ * 2.0 / 18.0); } return ret; } void BackboardFinder::SetUseSkew(bool useSkew) { useSkew_ = useSkew; } void BackboardFinder::DoVision() { // Get image from camera AxisCamera &camera = AxisCamera::GetInstance("10.2.54.11"); ColorImage img(IMAQ_IMAGE_RGB); if (!camera.GetImage(&img)) return; // // RGB Threshold -> BinaryImage BinaryImage* bimg = img.ThresholdRGB((int)constants_->thresholdRMin, (int)constants_->thresholdRMax, (int)constants_->thresholdGMin, (int)constants_->thresholdGMax, (int)constants_->thresholdBMin, (int)constants_->thresholdBMax); // take out small things Image* image = bimg->GetImaqImage(); if (!image) return; int pKernel[9] = {1,1,1,1,1,1,1,1,1}; StructuringElement structElem; structElem.matrixCols = 3; structElem.matrixRows = 3; structElem.hexa = FALSE; structElem.kernel = pKernel; // Filters particles based on their size. imaqSizeFilter(image, image, TRUE, 1, IMAQ_KEEP_LARGE, &structElem); // Convex Hull imaqConvexHull(image, image, true); // Convex Hull Perimeter, pParamter = perimeter Paramater int pParameter[1] = {20}; double pLower[1] = {0}; double pUpper[1] = {100}; int pCalibrated[1] = {0}; int pExclude[1] = {0}; ParticleFilterCriteria2* pParticleCriteria = NULL; ParticleFilterOptions pParticleFilterOptions; int pNumParticles; pParticleCriteria = (ParticleFilterCriteria2*)malloc(sizeof(ParticleFilterCriteria2)); pParticleCriteria[0].parameter = (MeasurementType)pParameter[0]; pParticleCriteria[0].lower = pLower[0]; pParticleCriteria[0].upper = pUpper[0]; pParticleCriteria[0].calibrated = pCalibrated[0]; pParticleCriteria[0].exclude = pExclude[0]; pParticleFilterOptions.rejectMatches = TRUE; pParticleFilterOptions.rejectBorder = 0; pParticleFilterOptions.connectivity8 = TRUE; imaqParticleFilter3(image, image, pParticleCriteria, 1, &pParticleFilterOptions, NULL, &pNumParticles); free(pParticleCriteria); // Filter based on squarishness, eParamter = elongationParamter int eParameter = 53; double eLower = 1.2; double eUpper = 2.7; int eCalibrated = 0; int eExclude = 0; ParticleFilterCriteria2* eParticleCriteria = NULL; ParticleFilterOptions eParticleFilterOptions; int eNumParticles; eParticleCriteria = (ParticleFilterCriteria2*)malloc(sizeof(ParticleFilterCriteria2)); eParticleCriteria[0].parameter = (MeasurementType) eParameter; eParticleCriteria[0].lower = eLower; eParticleCriteria[0].upper = eUpper; eParticleCriteria[0].calibrated = eCalibrated; eParticleCriteria[0].exclude = eExclude; eParticleFilterOptions.rejectMatches = FALSE; eParticleFilterOptions.rejectBorder = 0; eParticleFilterOptions.connectivity8 = TRUE; imaqParticleFilter3(image, image, eParticleCriteria, 1, &eParticleFilterOptions, NULL, &eNumParticles); free(eParticleCriteria); // Extract Particles (4?) ParticleAnalysisReport left, right, top, bottom; vector<ParticleAnalysisReport>* particles = bimg->GetOrderedParticleAnalysisReports(); // Find L,R,T,B based on CoM X,Y int i = 0; #if 0 switch (particles->size()) { case 4: for (i = 0; i < particles->size(); i++) { ParticleAnalysisReport p = (*particles)[i]; if (i == 0) { left = top = right = bottom = p; } if (p.center_mass_x_normalized < left.center_mass_x_normalized) { left = p; } if (p.center_mass_x_normalized > right.center_mass_x_normalized) { right = p; } if (p.center_mass_y_normalized < top.center_mass_y_normalized) { top = p; } if (p.center_mass_y_normalized > bottom.center_mass_y_normalized) { bottom = p; } } break; #define X_DELTA .1 #define Y_DELTA .2 #define IN_LINE_X(a,b) (fabs(a.center_mass_x_normalized - b.center_mass_x_normalized) < X_DELTA) #define IN_LINE_Y(a,b) (fabs(a.center_mass_y_normalized - b.center_mass_y_normalized) < Y_DELTA) #define HIGHEST(a,b) ((a.center_mass_y_normalized < b.center_mass_y_normalized) ? a : b) case 3: // Two Horizontal or two vertical targets if (IN_LINE_Y(particles->at(0), particles->at(1))){ printf("case A\n"); top = particles->at(2); } else if (IN_LINE_Y(particles->at(1), particles->at(2))) { printf("case B\n"); top = particles->at(0); } else if (IN_LINE_Y(particles->at(0), particles->at(2))){ printf("case C\n"); top = particles->at(1); } else if (IN_LINE_X(particles->at(0), particles->at(1))){ printf("case D\n"); top = HIGHEST(particles->at(0), particles->at(1)); } else if (IN_LINE_X(particles->at(1), particles->at(2))){ printf("case E\n"); top = HIGHEST(particles->at(1), particles->at(2)); } else if (IN_LINE_X(particles->at(0), particles->at(2))){ printf("case F\n"); top = HIGHEST(particles->at(0), particles->at(2)); } else { printf("case Q\n"); // wtf, mate? } break; case 2: if (particles->at(0).center_mass_x_normalized > .3 && particles->at(1).center_mass_x_normalized > .3) { //case where they are both on the right side of the screen, center axis is the one more to the right //if it only sees 2, the other is the left if (particles->at(0).center_mass_x_normalized > particles->at(1).center_mass_x_normalized) { top = particles->at(0); } else { top = particles->at(1); } } else if (particles->at(0).center_mass_x_normalized < -.3 && particles->at(1).center_mass_x_normalized < -.3) { //case where both are on the left side of the screen, center axis is the one more to the left //if it only sees 2, because the other is to the right if (particles->at(0).center_mass_x_normalized < particles->at(1).center_mass_x_normalized) { top = particles->at(0); } else { top = particles->at(1); } } else if (fabs(particles->at(0).center_mass_x_normalized) < .3 && fabs(particles->at(1).center_mass_x_normalized) < .3) { //case where we can only see 2 in the center, possibly super zoomed in, both have same axis if (particles->at(0).center_mass_y_normalized > particles->at(1).center_mass_y_normalized) { top = particles->at(0); } else { top = particles->at(1); } } else if (fabs(particles->at(0).center_mass_y_normalized) > .3) { //case where one on the side is blocked and one is in the center //the one off from the center line is the top or bottom, central //axis is the same top = particles->at(0); } else { top = particles->at(1); } break; case 1: if (particles->at(0).center_mass_x_normalized > .5) { left = particles->at(0); top = particles->at(0); top.center_mass_x_normalized = 1; } else if (particles->at(0).center_mass_x_normalized < -.5) { right = particles->at(0); top = particles->at(0); top.center_mass_x_normalized = -1; } else { //same desired axis bottom = particles->at(0); top = particles->at(0); } //if it's not left or right and still see's them then the top is set break; default: break; } #undef X_DELTA #undef Y_DELTA #undef IN_LINE_X #undef IN_LINE_Y #endif int topIndex = 0; for (int i = 0; i < particles->size(); i++){ ParticleAnalysisReport p = (*particles)[i]; if (i == 0){ top = p; } if (p.center_mass_y_normalized < top.center_mass_y_normalized) { top = p; topIndex = i; } } // Orientation double orientation; if (particles->size() >=1 ) { bimg->ParticleMeasurement(topIndex, IMAQ_MT_ORIENTATION, &orientation); } else { orientation = 0; } if (orientation > 90) { orientation -= 180; } orientation_ = orientation; // Calculate x offset from target center seesTarget_ = (particles->size() >= 1) && particles->size() < 5; x_ = seesTarget_ ? top.center_mass_x_normalized : 0.0; // Calculate angle on fieled based on ? width_ = top.boundingRect.width; printf("num particles: %d\n", particles->size()); for (int i = 0; i < particles->size(); i++){ printf("* i:%d | x:%f y:%f\n", i , particles->at(i).center_mass_x_normalized, particles->at(i).center_mass_y_normalized ); } printf("or: %f\n\n", orientation_); static Logger * l = new Logger("/vision.csv"); //l->Log("%f,%d,%d,%d\n", drive_->GetLeftEncoderDistance(),particles->size(), (right.boundingRect.left - (left.boundingRect.left + left.boundingRect.width)), top.boundingRect.width ); delete bimg; static double t = 0; double diff = Timer::GetFPGATimestamp() - t; t = Timer::GetFPGATimestamp(); lastUpdate_ = t; double middleGap = right.boundingRect.left - (left.boundingRect.left + left.boundingRect.width); } bool BackboardFinder::HasFreshTarget() { return (Timer::GetFPGATimestamp() - lastUpdate_ < .5); // 500ms } <commit_msg>Fixed the unordered orientation report bug<commit_after>#include "vision/BackboardFinder.h" #include "vision/BetterBinaryImage.h" #include <math.h> #include "WPILib.h" #include "util/Logger.h" #include "config/Constants.h" #include "subsystems/Drive.h" BackboardFinder::BackboardFinder(Drive* drive) : VisionProcess() { cameraLog_ = new Logger("/cameraLog.log"); printf("Initting camera\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); width_ = 0; vDiff_ = 0; constants_ = Constants::GetInstance(); useTopForWidth_ = false; drive_ = drive; useSkew_ = true; //camera.WriteResolution(AxisCameraParams::kResolution_320x240); } double BackboardFinder::GetX() { if (-1.0 <= x_ && x_ <= 1.0) { return x_; } else { // printf("Bad x val :( %f\n", x_); return 0; } } double BackboardFinder::GetHDiff() { return width_; } double BackboardFinder::GetVDiff() { return vDiff_; } bool BackboardFinder::SeesTarget() { return HasFreshTarget() && seesTarget_; } void BackboardFinder::LogCamera() { cameraLog_->Log("%f,%f,%f\n", GetX(), width_, vDiff_); } double BackboardFinder::GetDistance() { double w = width_; if (useTopForWidth_) { w += 7; // difference between target width and side to side distance } return constants_->distanceCoeffA * pow(width_, 6) + constants_->distanceCoeffB * pow(width_, 5) + constants_->distanceCoeffC * pow(width_, 4) + constants_->distanceCoeffD * pow(width_, 3) + constants_->distanceCoeffE * pow(width_, 2) + constants_->distanceCoeffF * width_ + constants_->distanceCoeffG; } double BackboardFinder::GetAngle() { //normalized x location (-1 to 1) times the pixels along //that one side = number of pixels off //47/320 = degree/pixel based on fov/horizontal resolution //pixels * degrees / pixels = degrees //printf("get: %f\n", (float) GetX()); double offset = Constants::GetInstance()->cameraOffset; double ret = GetX() * 160.0 * 47.0 / 320.0 + offset; if (useSkew_) { ret += (orientation_ * 2.0 / 18.0); } return ret; } void BackboardFinder::SetUseSkew(bool useSkew) { useSkew_ = useSkew; } void BackboardFinder::DoVision() { // Get image from camera AxisCamera &camera = AxisCamera::GetInstance("10.2.54.11"); ColorImage img(IMAQ_IMAGE_RGB); if (!camera.GetImage(&img)) return; // // RGB Threshold -> BinaryImage BinaryImage* bimg = img.ThresholdRGB((int)constants_->thresholdRMin, (int)constants_->thresholdRMax, (int)constants_->thresholdGMin, (int)constants_->thresholdGMax, (int)constants_->thresholdBMin, (int)constants_->thresholdBMax); // take out small things Image* image = bimg->GetImaqImage(); if (!image) return; int pKernel[9] = {1,1,1,1,1,1,1,1,1}; StructuringElement structElem; structElem.matrixCols = 3; structElem.matrixRows = 3; structElem.hexa = FALSE; structElem.kernel = pKernel; // Filters particles based on their size. imaqSizeFilter(image, image, TRUE, 1, IMAQ_KEEP_LARGE, &structElem); // Convex Hull imaqConvexHull(image, image, true); // Convex Hull Perimeter, pParamter = perimeter Paramater int pParameter[1] = {20}; double pLower[1] = {0}; double pUpper[1] = {100}; int pCalibrated[1] = {0}; int pExclude[1] = {0}; ParticleFilterCriteria2* pParticleCriteria = NULL; ParticleFilterOptions pParticleFilterOptions; int pNumParticles; pParticleCriteria = (ParticleFilterCriteria2*)malloc(sizeof(ParticleFilterCriteria2)); pParticleCriteria[0].parameter = (MeasurementType)pParameter[0]; pParticleCriteria[0].lower = pLower[0]; pParticleCriteria[0].upper = pUpper[0]; pParticleCriteria[0].calibrated = pCalibrated[0]; pParticleCriteria[0].exclude = pExclude[0]; pParticleFilterOptions.rejectMatches = TRUE; pParticleFilterOptions.rejectBorder = 0; pParticleFilterOptions.connectivity8 = TRUE; imaqParticleFilter3(image, image, pParticleCriteria, 1, &pParticleFilterOptions, NULL, &pNumParticles); free(pParticleCriteria); // Filter based on squarishness, eParamter = elongationParamter int eParameter = 53; double eLower = 1.2; double eUpper = 2.7; int eCalibrated = 0; int eExclude = 0; ParticleFilterCriteria2* eParticleCriteria = NULL; ParticleFilterOptions eParticleFilterOptions; int eNumParticles; eParticleCriteria = (ParticleFilterCriteria2*)malloc(sizeof(ParticleFilterCriteria2)); eParticleCriteria[0].parameter = (MeasurementType) eParameter; eParticleCriteria[0].lower = eLower; eParticleCriteria[0].upper = eUpper; eParticleCriteria[0].calibrated = eCalibrated; eParticleCriteria[0].exclude = eExclude; eParticleFilterOptions.rejectMatches = FALSE; eParticleFilterOptions.rejectBorder = 0; eParticleFilterOptions.connectivity8 = TRUE; imaqParticleFilter3(image, image, eParticleCriteria, 1, &eParticleFilterOptions, NULL, &eNumParticles); free(eParticleCriteria); // Extract Particles (4?) ParticleAnalysisReport top; vector<ParticleAnalysisReport>* particles = new vector<ParticleAnalysisReport>; int particleCount = bimg->GetNumberParticles(); for(int particleIndex = 0; particleIndex < particleCount; particleIndex++) { particles->push_back(bimg->GetParticleAnalysisReport(particleIndex)); } // Find top target int topIndex = 0; for (int i = 0; i < particles->size(); i++){ ParticleAnalysisReport p = (*particles)[i]; if (i == 0){ top = p; } if (p.center_mass_y_normalized < top.center_mass_y_normalized) { top = p; topIndex = i; } } // Skew of target gives us our lateral position on the field double orientation =0; int comx = 0; if (particles->size() >=1 ) { bimg->ParticleMeasurement(topIndex, IMAQ_MT_ORIENTATION, &orientation); bimg->ParticleMeasurement(topIndex, IMAQ_MT_CENTER_OF_MASS_X, &comx); } else { orientation = 0; } if (orientation > 90) { orientation -= 180; } orientation_ = orientation; // Calculate x offset from target center seesTarget_ = (particles->size() >= 1) && particles->size() < 5; x_ = seesTarget_ ? top.center_mass_x_normalized : 0.0; // Calculate angle on fieled based on ? width_ = top.boundingRect.width; #if 0 int comx2 = 0; printf("num particles: %d\n", particles->size()); for (int i = 0; i < particles->size(); i++){ bimg->ParticleMeasurement(i, IMAQ_MT_ORIENTATION, &orientation); bimg->ParticleMeasurement(i, IMAQ_MT_CENTER_OF_MASS_X, &comx2); printf("* i:%d | x:%d y:%f or:%f comx2:%d\n", i , particles->at(i).center_mass_x, particles->at(i).center_mass_y_normalized, orientation, comx2 ); } printf("topIndex:%d\ncomxq:%d\nor: %f\n\n", topIndex, comx, orientation_); #endif static Logger * l = new Logger("/vision.csv"); //l->Log("%f,%d,%d,%d\n", drive_->GetLeftEncoderDistance(),particles->size(), (right.boundingRect.left - (left.boundingRect.left + left.boundingRect.width)), top.boundingRect.width ); delete bimg; static double t = 0; double diff = Timer::GetFPGATimestamp() - t; t = Timer::GetFPGATimestamp(); lastUpdate_ = t; } bool BackboardFinder::HasFreshTarget() { return (Timer::GetFPGATimestamp() - lastUpdate_ < .5); // 500ms } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ // This file *must* remain with absolutely no run-time dependency. #include <string> #include <iostream> #include <cstdlib> #include <cstring> #include <libport/windows.hh> #include <libport/foreach.hh> #include "urbi-root.hh" #define ECHO(S) \ std::cerr << S << std::endl // Quick hackish portability layer. We cannot use the one from libport as // it is not header-only. #ifdef WIN32 #define RTLD_LAZY 0 #define RTLD_GLOBAL 0 static HMODULE dlopen(const char* name, int) { HMODULE res = LoadLibrary(name); if (res) { char buf[BUFSIZ]; GetModuleFileName(res, buf, sizeof buf - 1); buf[sizeof buf - 1] = 0; ECHO("loaded: " << buf); } return res; } static void* dlsym(HMODULE module, const char* name) { return GetProcAddress(module, name); } static const char* dlerror(DWORD err = GetLastError()) { static char buf[1024]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, 0, (LPTSTR)buf, sizeof buf, 0); return buf; } static strings_type split(std::string lib) { strings_type res; size_t pos; while ((pos = lib.find_first_of(':')) != lib.npos) { std::string s = lib.substr(0, pos); lib = lib.substr(pos + 1, lib.npos); // In case we split "c:\foo" into "c" and "\foo", glue them // together again. if (s[0] == '\\' && !res.empty() && res.back().length() == 1) res.back() += ':' + s; else res.push_back(s); } if (!lib.empty()) res.push_back(lib); return res; } #else typedef void* HMODULE; # include <dlfcn.h> #endif std::string xgetenv(const char* var) { const char* res = getenv(var); return res ? res : ""; } void xsetenv(const std::string& var, const std::string& val, int force) { #ifdef WIN32 if (force || xgetenv(var).empty()) _putenv(strdup((var + "=" + val).c_str())); #else setenv(var.c_str(), val.c_str(), force); #endif } /// Main. Load liburbi and call urbi_launch int main(int argc, char* argv[]) { /* Unfortunately, shared object search path cannot be modified once * the program has started under linux (see dlopen(3)). * Plan A would be to load our dependencies manualy, which implies * knowing all of them and keeping this file up-to-date. * Plan B is simpler: setenv and exec */ std::string urbi_root = get_urbi_root(argv[0]); std::string libdir = urbi_root + "/" + lib_rel_path; std::string ld_lib_path = xgetenv(LD_LIBRARY_PATH_NAME); // Only set URBI_ROOT if not already present. xsetenv("URBI_ROOT", urbi_root, 0); #ifndef WIN32 // Look if what we need is in (DY)LD_LIBRARY_PATH. Proceed if it is. // Otherwise, add it and exec ourselve to retry. if (ld_lib_path.find(libdir) == ld_lib_path.npos) { xsetenv(LD_LIBRARY_PATH_NAME, ld_lib_path + ":" + libdir, 1); execv(argv[0], argv); } #else std::string path = xgetenv("PATH"); strings_type ldpath_list = split(ld_lib_path); foreach(const std::string& s, ldpath_list) path += ";" + s; ECHO("ENV PATH=" << path); xsetenv("PATH", path, 1); #endif std::string liburbi_path = std::string() + libdir + "/liburbi" + lib_ext; // First try using LIBRARY_PATH in the environment. HMODULE handle = dlopen((std::string("liburbi") + lib_ext).c_str(), RTLD_LAZY | RTLD_GLOBAL); // If it fails, force path based on URBI_ROOT. if (!handle) handle = dlopen(liburbi_path.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (!handle) { ECHO("cannot open liburbi: " << liburbi_path << ':' << dlerror()); ECHO(getenv(LD_LIBRARY_PATH_NAME)); return 1; } typedef int(*main_t)(int, char*[]); main_t urbi_launch = (main_t)dlsym(handle, "urbi_launch"); if (!urbi_launch) { ECHO("cannot locate urbi_launch symbol: " << dlerror()); return 2; } return urbi_launch(argc, argv); } <commit_msg>urbi-launch: fix win32 code.<commit_after>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ // This file *must* remain with absolutely no run-time dependency. #include <cstdlib> #include <cstring> #include <iostream> #include <libport/foreach.hh> #include <libport/windows.hh> #include <list> #include <string> #include "urbi-root.hh" #define ECHO(S) \ std::cerr << S << std::endl // Quick hackish portability layer. We cannot use the one from libport as // it is not header-only. #ifdef WIN32 #define RTLD_LAZY 0 #define RTLD_GLOBAL 0 static HMODULE dlopen(const char* name, int) { HMODULE res = LoadLibrary(name); if (res) { char buf[BUFSIZ]; GetModuleFileName(res, buf, sizeof buf - 1); buf[sizeof buf - 1] = 0; ECHO("loaded: " << buf); } return res; } static void* dlsym(HMODULE module, const char* name) { return GetProcAddress(module, name); } static const char* dlerror(DWORD err = GetLastError()) { static char buf[1024]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, 0, (LPTSTR)buf, sizeof buf, 0); return buf; } typedef std::list<std::string> strings_type; static strings_type split(std::string lib) { strings_type res; size_t pos; while ((pos = lib.find_first_of(':')) != lib.npos) { std::string s = lib.substr(0, pos); lib = lib.substr(pos + 1, lib.npos); // In case we split "c:\foo" into "c" and "\foo", glue them // together again. if (s[0] == '\\' && !res.empty() && res.back().length() == 1) res.back() += ':' + s; else res.push_back(s); } if (!lib.empty()) res.push_back(lib); return res; } #else typedef void* HMODULE; # include <dlfcn.h> #endif std::string xgetenv(const std::string& var) { const char* res = getenv(var.c_str()); return res ? res : ""; } void xsetenv(const std::string& var, const std::string& val, int force) { #ifdef WIN32 if (force || xgetenv(var).empty()) _putenv(strdup((var + "=" + val).c_str())); #else setenv(var.c_str(), val.c_str(), force); #endif } /// Main. Load liburbi and call urbi_launch int main(int argc, char* argv[]) { /* Unfortunately, shared object search path cannot be modified once * the program has started under linux (see dlopen(3)). * Plan A would be to load our dependencies manualy, which implies * knowing all of them and keeping this file up-to-date. * Plan B is simpler: setenv and exec */ std::string urbi_root = get_urbi_root(argv[0]); std::string libdir = urbi_root + "/" + lib_rel_path; std::string ld_lib_path = xgetenv(LD_LIBRARY_PATH_NAME); // Only set URBI_ROOT if not already present. xsetenv("URBI_ROOT", urbi_root, 0); #ifndef WIN32 // Look if what we need is in (DY)LD_LIBRARY_PATH. Proceed if it is. // Otherwise, add it and exec ourselve to retry. if (ld_lib_path.find(libdir) == ld_lib_path.npos) { xsetenv(LD_LIBRARY_PATH_NAME, ld_lib_path + ":" + libdir, 1); execv(argv[0], argv); } #else std::string path = xgetenv("PATH"); strings_type ldpath_list = split(ld_lib_path); foreach(const std::string& s, ldpath_list) path += ";" + s; ECHO("ENV PATH=" << path); xsetenv("PATH", path, 1); #endif std::string liburbi_path = std::string() + libdir + "/liburbi" + lib_ext; // First try using LIBRARY_PATH in the environment. HMODULE handle = dlopen((std::string("liburbi") + lib_ext).c_str(), RTLD_LAZY | RTLD_GLOBAL); // If it fails, force path based on URBI_ROOT. if (!handle) handle = dlopen(liburbi_path.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (!handle) { ECHO("cannot open liburbi: " << liburbi_path << ':' << dlerror()); ECHO(getenv(LD_LIBRARY_PATH_NAME)); return 1; } typedef int(*main_t)(int, char*[]); main_t urbi_launch = (main_t)dlsym(handle, "urbi_launch"); if (!urbi_launch) { ECHO("cannot locate urbi_launch symbol: " << dlerror()); return 2; } return urbi_launch(argc, argv); } <|endoftext|>
<commit_before>#include "chimera/colladaDB/ColladaMaterial.hpp" #include "chimera/colladaDB/ColladaShader.hpp" #include "chimera/core/visible/Components.hpp" #include "chimera/core/visible/TextureManager.hpp" namespace Chimera { ColladaMaterial::~ColladaMaterial() {} Texture* ColladaMaterial::loadImage(pugi::xml_node nodeParent, const std::string& url) { pugi::xml_node node = getLibrary("library_images", url); // FIXME!!! pugi::xml_node init = node.child("init_from"); if (init != nullptr) { pugi::xml_text pathFile = init.text(); if (pathFile != nullptr) { std::string f = pathFile.as_string(); SDL_Log("Nova textura %s, Key: %s", f.c_str(), url.c_str()); TextureManager::loadFromFile(url, f, TexParam()); return TextureManager::getLast(); } } throw std::string("Textura nao encontrada: " + url); } void ColladaMaterial::createEffect(Material* pMat, pugi::xml_node nodeParent) { std::unordered_map<std::string, Texture*> mapaTex; std::unordered_map<std::string, std::string> mapa2D; for (pugi::xml_node param = nodeParent.first_child(); param; param = param.next_sibling()) { std::string sProf = param.name(); std::string sid = param.attribute("sid").value(); if (sProf == "newparam") { pugi::xml_node val1 = param.first_child(); std::string sVal1 = val1.name(); if (sVal1 == "surface") { std::string keyImage = val1.child("init_from").text().as_string(); Texture* tex = loadImage(val1, keyImage); mapaTex[sid] = tex; } else if (sVal1 == "sampler2D") { std::string keyMap = val1.child("source").text().as_string(); mapa2D[sid] = keyMap; } } else if (sProf == "technique") { pugi::xml_node phong = param.child("phong"); for (pugi::xml_node prop = phong.first_child(); prop; prop = prop.next_sibling()) { std::string p = prop.name(); if (p == "emission") { pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "color") pMat->setEmission(textToVec4(first.text().as_string())); else if (std::string(first.name()) == "texture") { // TODO: implementar } } else if (p == "ambient") { pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "color") pMat->setAmbient(textToVec4(first.text().as_string())); else if (std::string(first.name()) == "texture") { // TODO: implementar } } else if (p == "diffuse") { pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "color") pMat->setDiffuse(textToVec4(first.text().as_string())); else if (std::string(first.name()) == "texture") { std::string sAddr = first.attribute("texture").value(); std::string sAddr2 = mapa2D[sAddr]; Texture* tex = mapaTex[sAddr2]; pMat->addTexture(SHADE_TEXTURE_DIFFUSE, tex); pMat->setDiffuse(glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); // FIXME: Arquivo do blender nao tem!! } } else if (p == "specular") { pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "color") pMat->setSpecular(textToVec4(first.text().as_string())); else if (std::string(first.name()) == "texture") { // TODO: implementar } } else if (p == "shininess") { // TODO: implementar pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "float") { float aa = first.text().as_float(); pMat->setShine(aa); } } else if (p == "index_of_refraction") { // TODO: implementar } } } } } void ColladaMaterial::create(Entity& entity, pugi::xml_node nodeParent) { std::string refName = ""; pugi::xml_node material = getLibrary("library_materials", nodeParent.attribute("symbol").value()); pugi::xml_node instanceEffect = material.child("instance_effect"); pugi::xml_node technique_hint = instanceEffect.child("technique_hint"); if (technique_hint != nullptr) { if (std::string(technique_hint.attribute("profile").value()) == "GLSL") refName = technique_hint.attribute("ref").value(); } pugi::xml_node effect = getLibrary("library_effects", instanceEffect.attribute("url").value()); ComponentMaterial& eMaterial = entity.addComponent<ComponentMaterial>(); eMaterial.tag.id = material.attribute("id").value(); eMaterial.tag.tag = material.attribute("name").value(); eMaterial.tag.serial = Collada::getNewSerial(); pugi::xml_node profile = effect.child("profile_COMMON"); if (profile != nullptr) createEffect(eMaterial.material, profile); pugi::xml_node extra = effect.child("extra"); if (extra != nullptr) { pugi::xml_node instanceEffectShade = extra.child("instance_effect"); std::string url = instanceEffectShade.attribute("url").value(); ColladaShader cs(colladaDom, url); cs.create(refName, entity, cs.getLibrary("library_effects", url)); } else { pugi::xml_node profileGLSL = effect.child("profile_GLSL"); if (profileGLSL != nullptr) { ColladaShader cs(colladaDom, refName); cs.create(refName, entity, profileGLSL); } } } } // namespace Chimera<commit_msg>ProfileGLSL tambem funciona em mateial<commit_after>#include "chimera/colladaDB/ColladaMaterial.hpp" #include "chimera/colladaDB/ColladaShader.hpp" #include "chimera/core/visible/Components.hpp" #include "chimera/core/visible/TextureManager.hpp" namespace Chimera { ColladaMaterial::~ColladaMaterial() {} Texture* ColladaMaterial::loadImage(pugi::xml_node nodeParent, const std::string& url) { pugi::xml_node node = getLibrary("library_images", url); // FIXME!!! pugi::xml_node init = node.child("init_from"); if (init != nullptr) { pugi::xml_text pathFile = init.text(); if (pathFile != nullptr) { std::string f = pathFile.as_string(); SDL_Log("Nova textura %s, Key: %s", f.c_str(), url.c_str()); TextureManager::loadFromFile(url, f, TexParam()); return TextureManager::getLast(); } } throw std::string("Textura nao encontrada: " + url); } void ColladaMaterial::createEffect(Material* pMat, pugi::xml_node nodeParent) { std::unordered_map<std::string, Texture*> mapaTex; std::unordered_map<std::string, std::string> mapa2D; for (pugi::xml_node param = nodeParent.first_child(); param; param = param.next_sibling()) { std::string sProf = param.name(); std::string sid = param.attribute("sid").value(); if (sProf == "newparam") { pugi::xml_node val1 = param.first_child(); std::string sVal1 = val1.name(); if (sVal1 == "surface") { std::string keyImage = val1.child("init_from").text().as_string(); Texture* tex = loadImage(val1, keyImage); mapaTex[sid] = tex; } else if (sVal1 == "sampler2D") { std::string keyMap = val1.child("source").text().as_string(); mapa2D[sid] = keyMap; } } else if (sProf == "technique") { pugi::xml_node phong = param.child("phong"); for (pugi::xml_node prop = phong.first_child(); prop; prop = prop.next_sibling()) { std::string p = prop.name(); if (p == "emission") { pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "color") pMat->setEmission(textToVec4(first.text().as_string())); else if (std::string(first.name()) == "texture") { // TODO: implementar } } else if (p == "ambient") { pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "color") pMat->setAmbient(textToVec4(first.text().as_string())); else if (std::string(first.name()) == "texture") { // TODO: implementar } } else if (p == "diffuse") { pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "color") pMat->setDiffuse(textToVec4(first.text().as_string())); else if (std::string(first.name()) == "texture") { std::string sAddr = first.attribute("texture").value(); std::string sAddr2 = mapa2D[sAddr]; Texture* tex = mapaTex[sAddr2]; pMat->addTexture(SHADE_TEXTURE_DIFFUSE, tex); pMat->setDiffuse(glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); // FIXME: Arquivo do blender nao tem!! } } else if (p == "specular") { pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "color") pMat->setSpecular(textToVec4(first.text().as_string())); else if (std::string(first.name()) == "texture") { // TODO: implementar } } else if (p == "shininess") { // TODO: implementar pugi::xml_node first = prop.first_child(); if (std::string(first.name()) == "float") { float aa = first.text().as_float(); pMat->setShine(aa); } } else if (p == "index_of_refraction") { // TODO: implementar } } } } } void ColladaMaterial::create(Entity& entity, pugi::xml_node nodeParent) { std::string refName = ""; pugi::xml_node material = getLibrary("library_materials", nodeParent.attribute("symbol").value()); pugi::xml_node instanceEffect = material.child("instance_effect"); pugi::xml_node technique_hint = instanceEffect.child("technique_hint"); if (technique_hint != nullptr) { if (std::string(technique_hint.attribute("profile").value()) == "GLSL") refName = technique_hint.attribute("ref").value(); } pugi::xml_node effect = getLibrary("library_effects", instanceEffect.attribute("url").value()); ComponentMaterial& eMaterial = entity.addComponent<ComponentMaterial>(); eMaterial.tag.id = material.attribute("id").value(); eMaterial.tag.tag = material.attribute("name").value(); eMaterial.tag.serial = Collada::getNewSerial(); pugi::xml_node profile = effect.child("profile_COMMON"); if (profile != nullptr) createEffect(eMaterial.material, profile); pugi::xml_node extra = effect.child("extra"); if (extra != nullptr) { pugi::xml_node instanceEffectShade = extra.child("instance_effect"); std::string url = instanceEffectShade.attribute("url").value(); ColladaShader cs(colladaDom, url); cs.create(refName, entity, cs.getLibrary("library_effects", url)); } else { pugi::xml_node profileGLSL = effect.child("profile_GLSL"); if (profileGLSL != nullptr) { ColladaShader cs(colladaDom, refName); cs.create(refName, entity, effect); // get profileGLSL inside here } } } } // namespace Chimera<|endoftext|>
<commit_before>/* * Copyright (c) 2009 The University of Edinburgh * 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: Timothy M. Jones */ #ifndef __ARCH_POWER_REGISTERS_HH__ #define __ARCH_POWER_REGISTERS_HH__ #include "arch/power/generated/max_inst_regs.hh" #include "arch/power/miscregs.hh" namespace PowerISA { using PowerISAInst::MaxInstSrcRegs; using PowerISAInst::MaxInstDestRegs; using PowerISAInst::MaxMiscDestRegs; typedef uint8_t RegIndex; typedef uint64_t IntReg; // Floating point register file entry type typedef uint64_t FloatRegBits; typedef double FloatReg; typedef uint64_t MiscReg; // Constants Related to the number of registers const int NumIntArchRegs = 32; // CR, XER, LR, CTR, FPSCR, RSV, RSV-LEN, RSV-ADDR // and zero register, which doesn't actually exist but needs a number const int NumIntSpecialRegs = 9; const int NumFloatArchRegs = 32; const int NumFloatSpecialRegs = 0; const int NumInternalProcRegs = 0; const int NumIntRegs = NumIntArchRegs + NumIntSpecialRegs; const int NumFloatRegs = NumFloatArchRegs + NumFloatSpecialRegs; const int NumMiscRegs = NUM_MISCREGS; // Semantically meaningful register indices const int ReturnValueReg = 3; const int ArgumentReg0 = 3; const int ArgumentReg1 = 4; const int ArgumentReg2 = 5; const int ArgumentReg3 = 6; const int ArgumentReg4 = 7; const int FramePointerReg = 31; const int StackPointerReg = 1; // There isn't one in Power, but we need to define one somewhere const int ZeroReg = NumIntRegs - 1; const int SyscallNumReg = 0; const int SyscallPseudoReturnReg = 3; const int SyscallSuccessReg = 3; // These help enumerate all the registers for dependence tracking. const int FP_Base_DepTag = NumIntRegs; const int Ctrl_Base_DepTag = FP_Base_DepTag + NumFloatRegs; const int Max_DepTag = Ctrl_Base_DepTag + NumMiscRegs; typedef union { IntReg intreg; FloatReg fpreg; MiscReg ctrlreg; } AnyReg; enum MiscIntRegNums { INTREG_CR = NumIntArchRegs, INTREG_XER, INTREG_LR, INTREG_CTR, INTREG_FPSCR, INTREG_RSV, INTREG_RSV_LEN, INTREG_RSV_ADDR }; } // namespace PowerISA #endif // __ARCH_POWER_REGISTERS_HH__ <commit_msg>Power: Fix MaxMiscDestRegs which was set to zero<commit_after>/* * Copyright (c) 2009 The University of Edinburgh * 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: Timothy M. Jones */ #ifndef __ARCH_POWER_REGISTERS_HH__ #define __ARCH_POWER_REGISTERS_HH__ #include "arch/power/generated/max_inst_regs.hh" #include "arch/power/miscregs.hh" namespace PowerISA { using PowerISAInst::MaxInstSrcRegs; using PowerISAInst::MaxInstDestRegs; // Power writes a misc register outside of the isa parser, so it can't // be detected by it. Manually add it here. const int MaxMiscDestRegs = PowerISAInst::MaxMiscDestRegs + 1; typedef uint8_t RegIndex; typedef uint64_t IntReg; // Floating point register file entry type typedef uint64_t FloatRegBits; typedef double FloatReg; typedef uint64_t MiscReg; // Constants Related to the number of registers const int NumIntArchRegs = 32; // CR, XER, LR, CTR, FPSCR, RSV, RSV-LEN, RSV-ADDR // and zero register, which doesn't actually exist but needs a number const int NumIntSpecialRegs = 9; const int NumFloatArchRegs = 32; const int NumFloatSpecialRegs = 0; const int NumInternalProcRegs = 0; const int NumIntRegs = NumIntArchRegs + NumIntSpecialRegs; const int NumFloatRegs = NumFloatArchRegs + NumFloatSpecialRegs; const int NumMiscRegs = NUM_MISCREGS; // Semantically meaningful register indices const int ReturnValueReg = 3; const int ArgumentReg0 = 3; const int ArgumentReg1 = 4; const int ArgumentReg2 = 5; const int ArgumentReg3 = 6; const int ArgumentReg4 = 7; const int FramePointerReg = 31; const int StackPointerReg = 1; // There isn't one in Power, but we need to define one somewhere const int ZeroReg = NumIntRegs - 1; const int SyscallNumReg = 0; const int SyscallPseudoReturnReg = 3; const int SyscallSuccessReg = 3; // These help enumerate all the registers for dependence tracking. const int FP_Base_DepTag = NumIntRegs; const int Ctrl_Base_DepTag = FP_Base_DepTag + NumFloatRegs; const int Max_DepTag = Ctrl_Base_DepTag + NumMiscRegs; typedef union { IntReg intreg; FloatReg fpreg; MiscReg ctrlreg; } AnyReg; enum MiscIntRegNums { INTREG_CR = NumIntArchRegs, INTREG_XER, INTREG_LR, INTREG_CTR, INTREG_FPSCR, INTREG_RSV, INTREG_RSV_LEN, INTREG_RSV_ADDR }; } // namespace PowerISA #endif // __ARCH_POWER_REGISTERS_HH__ <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file libuobject/main.cc #include <libport/cstdio> #include <libport/unistd.h> #include <libport/cerrno> #include <iostream> #include <list> #include <sstream> #include <libport/cli.hh> #include <libport/containers.hh> #include <libport/foreach.hh> #include <libport/lexical-cast.hh> #include <libport/package-info.hh> #include <libport/program-name.hh> #include <libport/sysexits.hh> #include <urbi/package-info.hh> #include <urbi/uexternal.hh> #include <urbi/umain.hh> #include <urbi/umessage.hh> #include <urbi/uobject.hh> #include <urbi/urbi-root.hh> #include <urbi/usyncclient.hh> #include <libuobject/remote-ucontext-impl.hh> using libport::program_name; namespace urbi { static impl::RemoteUContextImpl* defaultContext; UCallbackAction debug(const UMessage& msg) { msg.client.printf("DEBUG: got a message: %s\n", string_cast(msg).c_str()); return URBI_CONTINUE; } UCallbackAction static endProgram(const UMessage& msg) { msg.client.printf("ERROR: got a disconnection message: %s\n", string_cast(msg).c_str()); exit(1); return URBI_CONTINUE; //stupid gcc } static void usage() { std::cout << "usage:\n" << libport::program_name() << " [OPTION]...\n" "\n" "Options:\n" " -b, --buffer SIZE input buffer size" << " [" << UAbstractClient::URBI_BUFLEN << "]\n" " -h, --help display this message and exit\n" " -H, --host ADDR server host name" << " [" << UClient::default_host() << "]\n" " --server put remote in server mode\n" " --no-sync-client Use UClient instead of USyncClient\n" " -p, --port PORT tcp port URBI will listen to" << " [" << UAbstractClient::URBI_PORT << "]\n" " -r, --port-file FILE file containing the port to listen to\n" " -V, --version print version information and exit\n" " -d, --disconnect exit program if disconnected(defaults)\n" " -s, --stay-alive do not exit program if disconnected\n" << libport::exit (EX_OK); } static void version() { std::cout << urbi::package_info() << std::endl << libport::exit (EX_OK); } typedef std::vector<std::string> files_type; int initialize(const std::string& host, int port, size_t buflen, bool exitOnDisconnect, bool server, const files_type& files, bool useSyncClient) { std::cerr << program_name() << ": " << urbi::package_info() << std::endl << program_name() << ": Remote Component Running on " << host << " " << port << std::endl; if (useSyncClient) { USyncClient::options o; o.server(server); new USyncClient(host, port, buflen, o); } else { std::cerr << "#WARNING: the no-sync-client mode is dangerous.\n" "Any attempt to use synchronous operation will crash your program." << std::endl; UClient::options o; o.server(server); setDefaultClient(new UClient(host, port, buflen, o)); } if (exitOnDisconnect) { if (!getDefaultClient() || getDefaultClient()->error()) std::cerr << "ERROR: failed to connect, exiting..." << std::endl << libport::exit(1); getDefaultClient()->setClientErrorCallback(callback(&endProgram)); } if (!getDefaultClient() || getDefaultClient()->error()) return 1; defaultContext = new impl::RemoteUContextImpl( (USyncClient*)dynamic_cast<UClient*>(getDefaultClient())); #ifdef LIBURBIDEBUG getDefaultClient()->setWildcardCallback(callback(&debug)); #else getDefaultClient()->setErrorCallback(callback(&debug)); #endif // Wait for client to be connected if in server mode. while (getDefaultClient() && !getDefaultClient()->error() && !getDefaultClient()->init()) usleep(20000); // Waiting for connectionID. while (getDefaultClient() && getDefaultClient()->connectionID() == "") usleep(5000); defaultContext->init(); //baseURBIStarter::init(); // Send a ';' since UObject likely sent a serie of piped commands. URBI_SEND_COMMAND(""); // Load initialization files. foreach (const std::string& file, files) getDefaultClient()->sendFile(file); return 0; } namespace { static void argument_with_option(const char* longopt, char shortopt, const std::string& val) { std::cerr << program_name() << ": warning: arguments without options are deprecated" << std::endl << "use `-" << shortopt << ' ' << val << '\'' << " or `--" << longopt << ' ' << val << "' instead" << std::endl << "Try `" << program_name() << " --help' for more information." << std::endl; } } URBI_SDK_API int main(const libport::cli_args_type& args, UrbiRoot&, bool block, bool) { std::string host = UClient::default_host(); bool exitOnDisconnect = true; int port = UAbstractClient::URBI_PORT; bool server = false; bool useSyncClient = true; size_t buflen = UAbstractClient::URBI_BUFLEN; // Files to load files_type files; // The number of the next (non-option) argument. unsigned argp = 1; for (unsigned i = 1; i < args.size(); ++i) { const std::string& arg = args[i]; if (arg == "--buffer" || arg == "-b") buflen = libport::convert_argument<size_t>(args, i++); else if (arg == "--disconnect" || arg == "-d") exitOnDisconnect = true; else if (arg == "--file" || arg == "-f") files.push_back(libport::convert_argument<const char*>(args, i++)); else if (arg == "--stay-alive" || arg == "-s") exitOnDisconnect = false; else if (arg == "--help" || arg == "-h") usage(); else if (arg == "--host" || arg == "-H") host = libport::convert_argument<std::string>(args, i++); else if (arg == "--no-sync-client") useSyncClient = false; else if (arg == "--port" || arg == "-p") port = libport::convert_argument<unsigned>(args, i++); else if (arg == "--port-file" || arg == "-r") port = (libport::file_contents_get<int> (libport::convert_argument<const char*>(args, i++))); else if (arg == "--server") server = true; // FIXME: Remove -v some day. else if (arg == "--version" || arg == "-V" || arg == "-v") version(); else if (arg[0] == '-') libport::invalid_option(arg); else // A genuine argument. switch (argp++) { case 1: argument_with_option("host", 'H', args[i]); host = args[i]; break; case 2: argument_with_option("port", 'p', args[i]); port = libport::convert_argument<unsigned> ("port", args[i].c_str()); break; default: std::cerr << "unexpected argument: " << arg << std::endl << libport::exit(EX_USAGE); } } initialize(host, port, buflen, exitOnDisconnect, server, files, useSyncClient); if (block) while (true) usleep(30000000); return 0; } } <commit_msg>Add --describe and --describe-file options to remote mode.<commit_after>/* * Copyright (C) 2008-2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file libuobject/main.cc #include <libport/cstdio> #include <libport/unistd.h> #include <libport/cerrno> #include <iostream> #include <list> #include <sstream> #include <libport/cli.hh> #include <libport/containers.hh> #include <libport/foreach.hh> #include <libport/lexical-cast.hh> #include <libport/package-info.hh> #include <libport/program-name.hh> #include <libport/sysexits.hh> #include <urbi/package-info.hh> #include <urbi/uexternal.hh> #include <urbi/umain.hh> #include <urbi/umessage.hh> #include <urbi/uobject.hh> #include <urbi/urbi-root.hh> #include <urbi/usyncclient.hh> #include <libuobject/remote-ucontext-impl.hh> using libport::program_name; namespace urbi { static impl::RemoteUContextImpl* defaultContext; UCallbackAction debug(const UMessage& msg) { msg.client.printf("DEBUG: got a message: %s\n", string_cast(msg).c_str()); return URBI_CONTINUE; } UCallbackAction static endProgram(const UMessage& msg) { msg.client.printf("ERROR: got a disconnection message: %s\n", string_cast(msg).c_str()); exit(1); return URBI_CONTINUE; //stupid gcc } static void usage() { std::cout << "usage:\n" << libport::program_name() << " [OPTION]...\n" "\n" "Options:\n" " -b, --buffer SIZE input buffer size" << " [" << UAbstractClient::URBI_BUFLEN << "]\n" " -h, --help display this message and exit\n" " -H, --host ADDR server host name" << " [" << UClient::default_host() << "]\n" " --server put remote in server mode\n" " --no-sync-client Use UClient instead of USyncClient\n" " -p, --port PORT tcp port URBI will listen to" << " [" << UAbstractClient::URBI_PORT << "]\n" " -r, --port-file FILE file containing the port to listen to\n" " -V, --version print version information and exit\n" " -d, --disconnect exit program if disconnected(defaults)\n" " -s, --stay-alive do not exit program if disconnected\n" " --describe describe loaded UObjects and exit\n" " --describe-file FILE write the list of present UObjects to FILE\n" << libport::exit (EX_OK); } static void version() { std::cout << urbi::package_info() << std::endl << libport::exit (EX_OK); } typedef std::vector<std::string> files_type; int initialize(const std::string& host, int port, size_t buflen, bool exitOnDisconnect, bool server, const files_type& files, bool useSyncClient) { std::cerr << program_name() << ": " << urbi::package_info() << std::endl << program_name() << ": Remote Component Running on " << host << " " << port << std::endl; if (useSyncClient) { USyncClient::options o; o.server(server); new USyncClient(host, port, buflen, o); } else { std::cerr << "#WARNING: the no-sync-client mode is dangerous.\n" "Any attempt to use synchronous operation will crash your program." << std::endl; UClient::options o; o.server(server); setDefaultClient(new UClient(host, port, buflen, o)); } if (exitOnDisconnect) { if (!getDefaultClient() || getDefaultClient()->error()) std::cerr << "ERROR: failed to connect, exiting..." << std::endl << libport::exit(1); getDefaultClient()->setClientErrorCallback(callback(&endProgram)); } if (!getDefaultClient() || getDefaultClient()->error()) return 1; defaultContext = new impl::RemoteUContextImpl( (USyncClient*)dynamic_cast<UClient*>(getDefaultClient())); #ifdef LIBURBIDEBUG getDefaultClient()->setWildcardCallback(callback(&debug)); #else getDefaultClient()->setErrorCallback(callback(&debug)); #endif // Wait for client to be connected if in server mode. while (getDefaultClient() && !getDefaultClient()->error() && !getDefaultClient()->init()) usleep(20000); // Waiting for connectionID. while (getDefaultClient() && getDefaultClient()->connectionID() == "") usleep(5000); defaultContext->init(); //baseURBIStarter::init(); // Send a ';' since UObject likely sent a serie of piped commands. URBI_SEND_COMMAND(""); // Load initialization files. foreach (const std::string& file, files) getDefaultClient()->sendFile(file); return 0; } namespace { static void argument_with_option(const char* longopt, char shortopt, const std::string& val) { std::cerr << program_name() << ": warning: arguments without options are deprecated" << std::endl << "use `-" << shortopt << ' ' << val << '\'' << " or `--" << longopt << ' ' << val << "' instead" << std::endl << "Try `" << program_name() << " --help' for more information." << std::endl; } } URBI_SDK_API int main(const libport::cli_args_type& args, UrbiRoot&, bool block, bool) { std::string host = UClient::default_host(); bool exitOnDisconnect = true; int port = UAbstractClient::URBI_PORT; bool server = false; bool useSyncClient = true; bool describeMode = false; std::string describeFile; size_t buflen = UAbstractClient::URBI_BUFLEN; // Files to load files_type files; // The number of the next (non-option) argument. unsigned argp = 1; for (unsigned i = 1; i < args.size(); ++i) { const std::string& arg = args[i]; if (arg == "--buffer" || arg == "-b") buflen = libport::convert_argument<size_t>(args, i++); else if (arg == "--disconnect" || arg == "-d") exitOnDisconnect = true; else if (arg == "--file" || arg == "-f") files.push_back(libport::convert_argument<const char*>(args, i++)); else if (arg == "--stay-alive" || arg == "-s") exitOnDisconnect = false; else if (arg == "--help" || arg == "-h") usage(); else if (arg == "--host" || arg == "-H") host = libport::convert_argument<std::string>(args, i++); else if (arg == "--no-sync-client") useSyncClient = false; else if (arg == "--port" || arg == "-p") port = libport::convert_argument<unsigned>(args, i++); else if (arg == "--port-file" || arg == "-r") port = (libport::file_contents_get<int> (libport::convert_argument<const char*>(args, i++))); else if (arg == "--server") server = true; // FIXME: Remove -v some day. else if (arg == "--version" || arg == "-V" || arg == "-v") version(); else if (arg == "--describe") describeMode = true; else if (arg == "--describe-file") describeFile = libport::convert_argument<const char*>(args, i++); else if (arg[0] == '-') libport::invalid_option(arg); else // A genuine argument. switch (argp++) { case 1: argument_with_option("host", 'H', args[i]); host = args[i]; break; case 2: argument_with_option("port", 'p', args[i]); port = libport::convert_argument<unsigned> ("port", args[i].c_str()); break; default: std::cerr << "unexpected argument: " << arg << std::endl << libport::exit(EX_USAGE); } } if (describeMode) { foreach(baseURBIStarter* s, baseURBIStarter::list()) std::cout << s->name << std::endl; foreach(baseURBIStarterHub* s, baseURBIStarterHub::list()) std::cout << s->name << std::endl; return 0; } if (!describeFile.empty()) { std::ofstream of(describeFile.c_str()); foreach(baseURBIStarter* s, baseURBIStarter::list()) of << s->name << std::endl; foreach(baseURBIStarterHub* s, baseURBIStarterHub::list()) of << s->name << std::endl; } initialize(host, port, buflen, exitOnDisconnect, server, files, useSyncClient); if (block) while (true) usleep(30000000); return 0; } } <|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 "chrome/browser/cookie_modal_dialog.h" #include "app/gtk_util.h" #include "app/l10n_util.h" #include "base/logging.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/gtk/gtk_chrome_cookie_view.h" #include "chrome/browser/gtk/gtk_chrome_link_button.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/views/cookie_prompt_view.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/pref_names.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" namespace { void OnExpanderActivate(GtkExpander* expander) { g_browser_process->local_state()-> SetBoolean(prefs::kCookiePromptExpanded, gtk_expander_get_expanded(GTK_EXPANDER(expander))); } } // namespace void CookiePromptModalDialog::CreateAndShowDialog() { dialog_ = CreateNativeDialog(); gtk_widget_show_all(GTK_WIDGET(dialog_)); // Suggest a minimum size. gint width; GtkRequisition req; gtk_widget_size_request(dialog_, &req); gtk_util::GetWidgetSizeFromResources(dialog_, IDS_ALERT_DIALOG_WIDTH_CHARS, 0, &width, NULL); if (width > req.width) gtk_widget_set_size_request(dialog_, width, -1); } void CookiePromptModalDialog::AcceptWindow() { HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT); } void CookiePromptModalDialog::CancelWindow() { HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_REJECT); } NativeDialog CookiePromptModalDialog::CreateNativeDialog() { gfx::NativeWindow window = tab_contents_->GetMessageBoxRootWindow(); CookiePromptModalDialog::DialogType type = dialog_type(); NativeDialog dialog = gtk_dialog_new_with_buttons( l10n_util::GetStringFUTF8( type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ? IDS_COOKIE_ALERT_TITLE : IDS_DATA_ALERT_TITLE, UTF8ToUTF16(origin().host())).c_str(), window, static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_BLOCK_BUTTON).c_str(), GTK_RESPONSE_REJECT, l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ALLOW_BUTTON).c_str(), GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE); GtkWidget* content_area = GTK_DIALOG(dialog)->vbox; gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing); string16 display_host = UTF8ToUTF16(origin().host()); GtkWidget* label = gtk_util::LeftAlignMisc(gtk_label_new( l10n_util::GetStringFUTF8( type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ? IDS_COOKIE_ALERT_LABEL : IDS_DATA_ALERT_LABEL, display_host).c_str())); gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0); // Create a vbox for all the radio buttons so they aren't too far away from // each other. bool remember_enabled = DecisionPersistable(); GtkWidget* radio_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); remember_radio_ = gtk_radio_button_new_with_label(NULL, l10n_util::GetStringFUTF8(IDS_COOKIE_ALERT_REMEMBER_RADIO, display_host).c_str()); gtk_widget_set_sensitive(GTK_WIDGET(remember_radio_), remember_enabled); gtk_box_pack_start(GTK_BOX(radio_box), remember_radio_, FALSE, FALSE, 0); GtkWidget* ask_radio = gtk_radio_button_new_with_label_from_widget( GTK_RADIO_BUTTON(remember_radio_), l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ASK_RADIO).c_str()); gtk_widget_set_sensitive(GTK_WIDGET(ask_radio), remember_enabled); if (!remember_enabled) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(ask_radio), true); gtk_box_pack_start(GTK_BOX(radio_box), ask_radio, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(content_area), radio_box, FALSE, FALSE, 0); GtkWidget* expander = gtk_expander_new( l10n_util::GetStringUTF8(IDS_COOKIE_SHOW_DETAILS_LABEL).c_str()); gtk_expander_set_expanded(GTK_EXPANDER(expander), g_browser_process->local_state()-> GetBoolean(prefs::kCookiePromptExpanded)); g_signal_connect(expander, "notify::expanded", G_CALLBACK(OnExpanderActivate), NULL); GtkChromeCookieView* cookie_view = gtk_chrome_cookie_view_new(); gtk_chrome_cookie_view_clear(cookie_view); if (type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE) { gtk_chrome_cookie_view_display_cookie_string(cookie_view, origin(), cookie_line()); } else if (type == CookiePromptModalDialog::DIALOG_TYPE_LOCAL_STORAGE) { gtk_chrome_cookie_view_display_local_storage_item( cookie_view, origin().host(), local_storage_key(), local_storage_value()); } else if (type == CookiePromptModalDialog::DIALOG_TYPE_DATABASE) { gtk_chrome_cookie_view_display_database_accessed( cookie_view, origin().host(), database_name(), display_name(), estimated_size()); } else if (type == CookiePromptModalDialog::DIALOG_TYPE_APPCACHE) { gtk_chrome_cookie_view_display_appcache_created( cookie_view, appcache_manifest_url()); } else { NOTIMPLEMENTED(); } gtk_container_add(GTK_CONTAINER(expander), GTK_WIDGET(cookie_view)); gtk_box_pack_end(GTK_BOX(content_area), GTK_WIDGET(expander), FALSE, FALSE, 0); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT); g_signal_connect(dialog, "response", G_CALLBACK(AppModalDialog::OnDialogResponse), reinterpret_cast<AppModalDialog*>(this)); gtk_util::MakeAppModalWindowGroup(); return dialog; } void CookiePromptModalDialog::HandleDialogResponse(GtkDialog* dialog, gint response_id) { bool remember_radio = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(remember_radio_)); if (response_id == GTK_RESPONSE_REJECT) { BlockSiteData(remember_radio); } else if (response_id == GTK_RESPONSE_ACCEPT) { // TODO(erg): Needs to use |session_expire_| instead of true. AllowSiteData(remember_radio, true); } else { BlockSiteData(false); } gtk_widget_destroy(GTK_WIDGET(dialog)); CompleteDialog(); gtk_util::AppModalDismissedUngroupWindows(); delete this; } <commit_msg>GTK: Fix app-modality of the cookie ask dialog.<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 "chrome/browser/cookie_modal_dialog.h" #include "app/gtk_util.h" #include "app/l10n_util.h" #include "base/logging.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/gtk/gtk_chrome_cookie_view.h" #include "chrome/browser/gtk/gtk_chrome_link_button.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/views/cookie_prompt_view.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/pref_names.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" namespace { void OnExpanderActivate(GtkExpander* expander) { g_browser_process->local_state()-> SetBoolean(prefs::kCookiePromptExpanded, gtk_expander_get_expanded(GTK_EXPANDER(expander))); } } // namespace void CookiePromptModalDialog::CreateAndShowDialog() { dialog_ = CreateNativeDialog(); gtk_widget_show_all(GTK_WIDGET(dialog_)); // Suggest a minimum size. gint width; GtkRequisition req; gtk_widget_size_request(dialog_, &req); gtk_util::GetWidgetSizeFromResources(dialog_, IDS_ALERT_DIALOG_WIDTH_CHARS, 0, &width, NULL); if (width > req.width) gtk_widget_set_size_request(dialog_, width, -1); } void CookiePromptModalDialog::AcceptWindow() { HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT); } void CookiePromptModalDialog::CancelWindow() { HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_REJECT); } NativeDialog CookiePromptModalDialog::CreateNativeDialog() { gtk_util::MakeAppModalWindowGroup(); gfx::NativeWindow window = tab_contents_->GetMessageBoxRootWindow(); CookiePromptModalDialog::DialogType type = dialog_type(); NativeDialog dialog = gtk_dialog_new_with_buttons( l10n_util::GetStringFUTF8( type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ? IDS_COOKIE_ALERT_TITLE : IDS_DATA_ALERT_TITLE, UTF8ToUTF16(origin().host())).c_str(), window, static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_BLOCK_BUTTON).c_str(), GTK_RESPONSE_REJECT, l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ALLOW_BUTTON).c_str(), GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE); GtkWidget* content_area = GTK_DIALOG(dialog)->vbox; gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing); string16 display_host = UTF8ToUTF16(origin().host()); GtkWidget* label = gtk_util::LeftAlignMisc(gtk_label_new( l10n_util::GetStringFUTF8( type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ? IDS_COOKIE_ALERT_LABEL : IDS_DATA_ALERT_LABEL, display_host).c_str())); gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0); // Create a vbox for all the radio buttons so they aren't too far away from // each other. bool remember_enabled = DecisionPersistable(); GtkWidget* radio_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); remember_radio_ = gtk_radio_button_new_with_label(NULL, l10n_util::GetStringFUTF8(IDS_COOKIE_ALERT_REMEMBER_RADIO, display_host).c_str()); gtk_widget_set_sensitive(GTK_WIDGET(remember_radio_), remember_enabled); gtk_box_pack_start(GTK_BOX(radio_box), remember_radio_, FALSE, FALSE, 0); GtkWidget* ask_radio = gtk_radio_button_new_with_label_from_widget( GTK_RADIO_BUTTON(remember_radio_), l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ASK_RADIO).c_str()); gtk_widget_set_sensitive(GTK_WIDGET(ask_radio), remember_enabled); if (!remember_enabled) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(ask_radio), true); gtk_box_pack_start(GTK_BOX(radio_box), ask_radio, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(content_area), radio_box, FALSE, FALSE, 0); GtkWidget* expander = gtk_expander_new( l10n_util::GetStringUTF8(IDS_COOKIE_SHOW_DETAILS_LABEL).c_str()); gtk_expander_set_expanded(GTK_EXPANDER(expander), g_browser_process->local_state()-> GetBoolean(prefs::kCookiePromptExpanded)); g_signal_connect(expander, "notify::expanded", G_CALLBACK(OnExpanderActivate), NULL); GtkChromeCookieView* cookie_view = gtk_chrome_cookie_view_new(); gtk_chrome_cookie_view_clear(cookie_view); if (type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE) { gtk_chrome_cookie_view_display_cookie_string(cookie_view, origin(), cookie_line()); } else if (type == CookiePromptModalDialog::DIALOG_TYPE_LOCAL_STORAGE) { gtk_chrome_cookie_view_display_local_storage_item( cookie_view, origin().host(), local_storage_key(), local_storage_value()); } else if (type == CookiePromptModalDialog::DIALOG_TYPE_DATABASE) { gtk_chrome_cookie_view_display_database_accessed( cookie_view, origin().host(), database_name(), display_name(), estimated_size()); } else if (type == CookiePromptModalDialog::DIALOG_TYPE_APPCACHE) { gtk_chrome_cookie_view_display_appcache_created( cookie_view, appcache_manifest_url()); } else { NOTIMPLEMENTED(); } gtk_container_add(GTK_CONTAINER(expander), GTK_WIDGET(cookie_view)); gtk_box_pack_end(GTK_BOX(content_area), GTK_WIDGET(expander), FALSE, FALSE, 0); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT); g_signal_connect(dialog, "response", G_CALLBACK(AppModalDialog::OnDialogResponse), reinterpret_cast<AppModalDialog*>(this)); return dialog; } void CookiePromptModalDialog::HandleDialogResponse(GtkDialog* dialog, gint response_id) { bool remember_radio = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(remember_radio_)); if (response_id == GTK_RESPONSE_REJECT) { BlockSiteData(remember_radio); } else if (response_id == GTK_RESPONSE_ACCEPT) { // TODO(erg): Needs to use |session_expire_| instead of true. AllowSiteData(remember_radio, true); } else { BlockSiteData(false); } gtk_widget_destroy(GTK_WIDGET(dialog)); CompleteDialog(); gtk_util::AppModalDismissedUngroupWindows(); delete this; } <|endoftext|>
<commit_before>// Copyright (c) 2009 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 <Carbon/Carbon.h> #include "build/build_config.h" #include <vector> #include "base/logging.h" #include "base/mac_util.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/plugin_process_host.h" void PluginProcessHost::OnPluginSelectWindow(uint32 window_id, gfx::Rect window_rect, bool modal) { plugin_visible_windows_set_.insert(window_id); if (modal) plugin_modal_windows_set_.insert(window_id); } void PluginProcessHost::OnPluginShowWindow(uint32 window_id, gfx::Rect window_rect, bool modal) { plugin_visible_windows_set_.insert(window_id); if (modal) plugin_modal_windows_set_.insert(window_id); CGRect window_bounds = { { window_rect.x(), window_rect.y() }, { window_rect.width(), window_rect.height() } }; CGRect main_display_bounds = CGDisplayBounds(CGMainDisplayID()); if (CGRectEqualToRect(window_bounds, main_display_bounds)) { plugin_fullscreen_windows_set_.insert(window_id); // If the plugin has just shown a window that's the same dimensions as // the main display, hide the menubar so that it has the whole screen. ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::RequestFullScreen)); } } void PluginProcessHost::OnPluginHideWindow(uint32 window_id, gfx::Rect window_rect) { plugin_visible_windows_set_.erase(window_id); plugin_modal_windows_set_.erase(window_id); if (plugin_fullscreen_windows_set_.find(window_id) != plugin_fullscreen_windows_set_.end()) { plugin_fullscreen_windows_set_.erase(window_id); ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::ReleaseFullScreen)); } } void PluginProcessHost::OnPluginDisposeWindow(uint32 window_id, gfx::Rect window_rect) { OnPluginHideWindow(window_id, window_rect); } void PluginProcessHost::OnAppActivation() { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); // If our plugin process has any modal windows up, we need to bring it forward // so that they act more like an in-process modal window would. if (!plugin_modal_windows_set_.empty()) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::ActivateProcess, handle())); } } <commit_msg>Only request full-screen once per plugin window<commit_after>// Copyright (c) 2009 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 <Carbon/Carbon.h> #include "build/build_config.h" #include <vector> #include "base/logging.h" #include "base/mac_util.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/plugin_process_host.h" void PluginProcessHost::OnPluginSelectWindow(uint32 window_id, gfx::Rect window_rect, bool modal) { plugin_visible_windows_set_.insert(window_id); if (modal) plugin_modal_windows_set_.insert(window_id); } void PluginProcessHost::OnPluginShowWindow(uint32 window_id, gfx::Rect window_rect, bool modal) { plugin_visible_windows_set_.insert(window_id); if (modal) plugin_modal_windows_set_.insert(window_id); CGRect window_bounds = { { window_rect.x(), window_rect.y() }, { window_rect.width(), window_rect.height() } }; CGRect main_display_bounds = CGDisplayBounds(CGMainDisplayID()); if (CGRectEqualToRect(window_bounds, main_display_bounds) && (plugin_fullscreen_windows_set_.find(window_id) == plugin_fullscreen_windows_set_.end())) { plugin_fullscreen_windows_set_.insert(window_id); // If the plugin has just shown a window that's the same dimensions as // the main display, hide the menubar so that it has the whole screen. // (but only if we haven't already seen this fullscreen window, since // otherwise our refcounting can get skewed). ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::RequestFullScreen)); } } void PluginProcessHost::OnPluginHideWindow(uint32 window_id, gfx::Rect window_rect) { plugin_visible_windows_set_.erase(window_id); plugin_modal_windows_set_.erase(window_id); if (plugin_fullscreen_windows_set_.find(window_id) != plugin_fullscreen_windows_set_.end()) { plugin_fullscreen_windows_set_.erase(window_id); ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::ReleaseFullScreen)); } } void PluginProcessHost::OnPluginDisposeWindow(uint32 window_id, gfx::Rect window_rect) { OnPluginHideWindow(window_id, window_rect); } void PluginProcessHost::OnAppActivation() { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); // If our plugin process has any modal windows up, we need to bring it forward // so that they act more like an in-process modal window would. if (!plugin_modal_windows_set_.empty()) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(mac_util::ActivateProcess, handle())); } } <|endoftext|>
<commit_before>// Copyright 2008, Google 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 Google 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. #include "chrome/browser/printing/print_settings.h" #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "chrome/browser/printing/units.h" #include "chrome/common/render_messages.h" namespace printing { // Global SequenceNumber used for generating unique cookie values. static base::AtomicSequenceNumber cookie_seq; PrintSettings::PrintSettings() : min_shrink(1.25), max_shrink(2.0), desired_dpi(72), dpi_(0), landscape_(false) { } void PrintSettings::Clear() { ranges.clear(); min_shrink = 1.25; max_shrink = 2.; desired_dpi = 72; printer_name_.clear(); device_name_.clear(); page_setup_cmm_.Clear(); page_setup_pixels_.Clear(); dpi_ = 0; landscape_ = false; } #ifdef WIN32 void PrintSettings::Init(HDC hdc, const DEVMODE& dev_mode, const PageRanges& new_ranges, const std::wstring& new_device_name) { DCHECK(hdc); printer_name_ = dev_mode.dmDeviceName; device_name_ = new_device_name; ranges = new_ranges; landscape_ = dev_mode.dmOrientation == DMORIENT_LANDSCAPE; int old_dpi = dpi_; dpi_ = GetDeviceCaps(hdc, LOGPIXELSX); // No printer device is known to advertise different dpi in X and Y axis; even // the fax device using the 200x100 dpi setting. It's ought to break so many // applications that it's not even needed to care about. WebKit doesn't // support different dpi settings in X and Y axis. DCHECK_EQ(dpi_, GetDeviceCaps(hdc, LOGPIXELSY)); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); // Initialize page_setup_pixels_. gfx::Size physical_size_pixels(GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT)); gfx::Rect printable_area_pixels(GetDeviceCaps(hdc, PHYSICALOFFSETX), GetDeviceCaps(hdc, PHYSICALOFFSETY), GetDeviceCaps(hdc, HORZRES), GetDeviceCaps(hdc, VERTRES)); // Hard-code text_height = 0.5cm = ~1/5 of inch page_setup_pixels_.Init(physical_size_pixels, printable_area_pixels, ConvertUnit(500, kHundrethsMMPerInch, dpi_)); // Initialize page_setup_cmm_. // In theory, we should be using HORZSIZE and VERTSIZE but their value is // so wrong it's useless. So read the values in dpi unit and convert them back // in 0.01 mm. gfx::Size physical_size_cmm( ConvertUnit(physical_size_pixels.width(), dpi_, kHundrethsMMPerInch), ConvertUnit(physical_size_pixels.height(), dpi_, kHundrethsMMPerInch)); gfx::Rect printable_area_cmm( ConvertUnit(printable_area_pixels.x(), dpi_, kHundrethsMMPerInch), ConvertUnit(printable_area_pixels.y(), dpi_, kHundrethsMMPerInch), ConvertUnit(printable_area_pixels.width(), dpi_, kHundrethsMMPerInch), ConvertUnit(printable_area_pixels.bottom(), dpi_, kHundrethsMMPerInch)); static const int kRoundingTolerance = 5; // Some printers may advertise a slightly larger printable area than the // physical area. This is mostly due to integer calculation and rounding. if (physical_size_cmm.height() > printable_area_cmm.bottom() && physical_size_cmm.height() <= (printable_area_cmm.bottom() + kRoundingTolerance)) { physical_size_cmm.set_height(printable_area_cmm.bottom()); } if (physical_size_cmm.width() > printable_area_cmm.right() && physical_size_cmm.width() <= (printable_area_cmm.right() + kRoundingTolerance)) { physical_size_cmm.set_width(printable_area_cmm.right()); } page_setup_cmm_.Init(physical_size_cmm, printable_area_cmm, 500); } #endif void PrintSettings::UpdateMarginsMetric(const PageMargins& new_margins) { // Apply the new margins in 0.01 mm unit. page_setup_cmm_.SetRequestedMargins(new_margins); // Converts the margins in dpi unit and apply those too. PageMargins pixels_margins; pixels_margins.header = ConvertUnit(new_margins.header, kHundrethsMMPerInch, dpi_); pixels_margins.footer = ConvertUnit(new_margins.footer, kHundrethsMMPerInch, dpi_); pixels_margins.left = ConvertUnit(new_margins.left, kHundrethsMMPerInch, dpi_); pixels_margins.top = ConvertUnit(new_margins.top, kHundrethsMMPerInch, dpi_); pixels_margins.right = ConvertUnit(new_margins.right, kHundrethsMMPerInch, dpi_); pixels_margins.bottom = ConvertUnit(new_margins.bottom, kHundrethsMMPerInch, dpi_); page_setup_pixels_.SetRequestedMargins(pixels_margins); } void PrintSettings::UpdateMarginsMilliInch(const PageMargins& new_margins) { // Convert margins from thousandth inches to cmm (0.01mm). PageMargins cmm_margins; cmm_margins.header = ConvertMilliInchToHundredThousanthMeter(new_margins.header); cmm_margins.footer = ConvertMilliInchToHundredThousanthMeter(new_margins.footer); cmm_margins.left = ConvertMilliInchToHundredThousanthMeter(new_margins.left); cmm_margins.top = ConvertMilliInchToHundredThousanthMeter(new_margins.top); cmm_margins.right = ConvertMilliInchToHundredThousanthMeter(new_margins.right); cmm_margins.bottom = ConvertMilliInchToHundredThousanthMeter(new_margins.bottom); UpdateMarginsMetric(cmm_margins); } void PrintSettings::RenderParams(ViewMsg_Print_Params* params) const { DCHECK(params); params->printable_size.SetSize(page_setup_pixels_.content_area().width(), page_setup_pixels_.content_area().height()); params->dpi = dpi_; // Currently hardcoded at 1.25. See PrintSettings' constructor. params->min_shrink = min_shrink; // Currently hardcoded at 2.0. See PrintSettings' constructor. params->max_shrink = max_shrink; // Currently hardcoded at 72dpi. See PrintSettings' constructor. params->desired_dpi = desired_dpi; // Always use an invalid cookie. params->document_cookie = 0; } bool PrintSettings::Equals(const PrintSettings& rhs) const { // Do not test the display device name (printer_name_) for equality since it // may sometimes be chopped off at 30 chars. As long as device_name is the // same, that's fine. return ranges == rhs.ranges && min_shrink == rhs.min_shrink && max_shrink == rhs.max_shrink && desired_dpi == rhs.desired_dpi && overlays.Equals(rhs.overlays) && device_name_ == rhs.device_name_ && page_setup_pixels_.Equals(rhs.page_setup_pixels_) && page_setup_cmm_.Equals(rhs.page_setup_cmm_) && dpi_ == rhs.dpi_ && landscape_ == rhs.landscape_; } int PrintSettings::NewCookie() { return cookie_seq.GetNext(); } } // namespace printing <commit_msg>The printing NewCookie() must start counting at 1 and not 0, since 0 is reserved to mark a document as unassigned.<commit_after>// Copyright 2008, Google 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 Google 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. #include "chrome/browser/printing/print_settings.h" #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "chrome/browser/printing/units.h" #include "chrome/common/render_messages.h" namespace printing { // Global SequenceNumber used for generating unique cookie values. static base::AtomicSequenceNumber cookie_seq; PrintSettings::PrintSettings() : min_shrink(1.25), max_shrink(2.0), desired_dpi(72), dpi_(0), landscape_(false) { } void PrintSettings::Clear() { ranges.clear(); min_shrink = 1.25; max_shrink = 2.; desired_dpi = 72; printer_name_.clear(); device_name_.clear(); page_setup_cmm_.Clear(); page_setup_pixels_.Clear(); dpi_ = 0; landscape_ = false; } #ifdef WIN32 void PrintSettings::Init(HDC hdc, const DEVMODE& dev_mode, const PageRanges& new_ranges, const std::wstring& new_device_name) { DCHECK(hdc); printer_name_ = dev_mode.dmDeviceName; device_name_ = new_device_name; ranges = new_ranges; landscape_ = dev_mode.dmOrientation == DMORIENT_LANDSCAPE; int old_dpi = dpi_; dpi_ = GetDeviceCaps(hdc, LOGPIXELSX); // No printer device is known to advertise different dpi in X and Y axis; even // the fax device using the 200x100 dpi setting. It's ought to break so many // applications that it's not even needed to care about. WebKit doesn't // support different dpi settings in X and Y axis. DCHECK_EQ(dpi_, GetDeviceCaps(hdc, LOGPIXELSY)); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); // Initialize page_setup_pixels_. gfx::Size physical_size_pixels(GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT)); gfx::Rect printable_area_pixels(GetDeviceCaps(hdc, PHYSICALOFFSETX), GetDeviceCaps(hdc, PHYSICALOFFSETY), GetDeviceCaps(hdc, HORZRES), GetDeviceCaps(hdc, VERTRES)); // Hard-code text_height = 0.5cm = ~1/5 of inch page_setup_pixels_.Init(physical_size_pixels, printable_area_pixels, ConvertUnit(500, kHundrethsMMPerInch, dpi_)); // Initialize page_setup_cmm_. // In theory, we should be using HORZSIZE and VERTSIZE but their value is // so wrong it's useless. So read the values in dpi unit and convert them back // in 0.01 mm. gfx::Size physical_size_cmm( ConvertUnit(physical_size_pixels.width(), dpi_, kHundrethsMMPerInch), ConvertUnit(physical_size_pixels.height(), dpi_, kHundrethsMMPerInch)); gfx::Rect printable_area_cmm( ConvertUnit(printable_area_pixels.x(), dpi_, kHundrethsMMPerInch), ConvertUnit(printable_area_pixels.y(), dpi_, kHundrethsMMPerInch), ConvertUnit(printable_area_pixels.width(), dpi_, kHundrethsMMPerInch), ConvertUnit(printable_area_pixels.bottom(), dpi_, kHundrethsMMPerInch)); static const int kRoundingTolerance = 5; // Some printers may advertise a slightly larger printable area than the // physical area. This is mostly due to integer calculation and rounding. if (physical_size_cmm.height() > printable_area_cmm.bottom() && physical_size_cmm.height() <= (printable_area_cmm.bottom() + kRoundingTolerance)) { physical_size_cmm.set_height(printable_area_cmm.bottom()); } if (physical_size_cmm.width() > printable_area_cmm.right() && physical_size_cmm.width() <= (printable_area_cmm.right() + kRoundingTolerance)) { physical_size_cmm.set_width(printable_area_cmm.right()); } page_setup_cmm_.Init(physical_size_cmm, printable_area_cmm, 500); } #endif void PrintSettings::UpdateMarginsMetric(const PageMargins& new_margins) { // Apply the new margins in 0.01 mm unit. page_setup_cmm_.SetRequestedMargins(new_margins); // Converts the margins in dpi unit and apply those too. PageMargins pixels_margins; pixels_margins.header = ConvertUnit(new_margins.header, kHundrethsMMPerInch, dpi_); pixels_margins.footer = ConvertUnit(new_margins.footer, kHundrethsMMPerInch, dpi_); pixels_margins.left = ConvertUnit(new_margins.left, kHundrethsMMPerInch, dpi_); pixels_margins.top = ConvertUnit(new_margins.top, kHundrethsMMPerInch, dpi_); pixels_margins.right = ConvertUnit(new_margins.right, kHundrethsMMPerInch, dpi_); pixels_margins.bottom = ConvertUnit(new_margins.bottom, kHundrethsMMPerInch, dpi_); page_setup_pixels_.SetRequestedMargins(pixels_margins); } void PrintSettings::UpdateMarginsMilliInch(const PageMargins& new_margins) { // Convert margins from thousandth inches to cmm (0.01mm). PageMargins cmm_margins; cmm_margins.header = ConvertMilliInchToHundredThousanthMeter(new_margins.header); cmm_margins.footer = ConvertMilliInchToHundredThousanthMeter(new_margins.footer); cmm_margins.left = ConvertMilliInchToHundredThousanthMeter(new_margins.left); cmm_margins.top = ConvertMilliInchToHundredThousanthMeter(new_margins.top); cmm_margins.right = ConvertMilliInchToHundredThousanthMeter(new_margins.right); cmm_margins.bottom = ConvertMilliInchToHundredThousanthMeter(new_margins.bottom); UpdateMarginsMetric(cmm_margins); } void PrintSettings::RenderParams(ViewMsg_Print_Params* params) const { DCHECK(params); params->printable_size.SetSize(page_setup_pixels_.content_area().width(), page_setup_pixels_.content_area().height()); params->dpi = dpi_; // Currently hardcoded at 1.25. See PrintSettings' constructor. params->min_shrink = min_shrink; // Currently hardcoded at 2.0. See PrintSettings' constructor. params->max_shrink = max_shrink; // Currently hardcoded at 72dpi. See PrintSettings' constructor. params->desired_dpi = desired_dpi; // Always use an invalid cookie. params->document_cookie = 0; } bool PrintSettings::Equals(const PrintSettings& rhs) const { // Do not test the display device name (printer_name_) for equality since it // may sometimes be chopped off at 30 chars. As long as device_name is the // same, that's fine. return ranges == rhs.ranges && min_shrink == rhs.min_shrink && max_shrink == rhs.max_shrink && desired_dpi == rhs.desired_dpi && overlays.Equals(rhs.overlays) && device_name_ == rhs.device_name_ && page_setup_pixels_.Equals(rhs.page_setup_pixels_) && page_setup_cmm_.Equals(rhs.page_setup_cmm_) && dpi_ == rhs.dpi_ && landscape_ == rhs.landscape_; } int PrintSettings::NewCookie() { // A cookie of 0 is used to mark a document as unassigned, count from 1. return cookie_seq.GetNext() + 1; } } // namespace printing <|endoftext|>
<commit_before><commit_msg>control: minor refactor in latteral control<commit_after><|endoftext|>
<commit_before>/** * \file * \remark This file is part of VITA. * * \copyright Copyright (C) 2015 EOS di Manlio Morini. * * \license * 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 <cstdlib> #include <sstream> #include "kernel/ga/i_ga.h" #include "kernel/ga/interpreter.h" #include "kernel/ga/ga_evaluator.h" #include "kernel/ga/ga_search.h" #include "kernel/evolution.h" #include "kernel/problem.h" #if !defined(MASTER_TEST_SET) #define BOOST_TEST_MODULE t_ga_perf #include <boost/test/unit_test.hpp> using namespace boost; #include "factory_fixture5.h" #endif BOOST_FIXTURE_TEST_SUITE(t_ga2, F_FACTORY5_NO_INIT) // Test problem 7 from "An Efficient Constraint Handling Method for Genetic // Algorithms" BOOST_AUTO_TEST_CASE(Search_TestProblem7) { env.individuals = 100; env.generations = 2000; env.f_threashold = {0, 0}; env.verbosity = 1; vita::problem prob; prob.env = env; prob.env.stat_dir = "."; prob.env.stat_layers = true; prob.sset.insert(vita::ga::parameter(0, -2.3, 2.3)); prob.sset.insert(vita::ga::parameter(1, -2.3, 2.3)); prob.sset.insert(vita::ga::parameter(2, -3.2, 3.2)); prob.sset.insert(vita::ga::parameter(3, -3.2, 3.2)); prob.sset.insert(vita::ga::parameter(4, -3.2, 3.2)); auto f = [](const std::vector<double> &x) { return -std::exp(x[0] * x[1] * x[2] * x[3] * x[4]); }; auto p = [](const vita::i_ga &prg) { auto h1 = [](const std::vector<double> &x) { return x[0] * x[0] + x[1] * x[1] + x[2] * x[2] + x[3] * x[3] + x[4] * x[4] - 10.0; }; auto h2 = [](const std::vector<double> &x) { return x[1] * x[2] - 5.0 * x[3] * x[4]; }; auto h3 = [](const std::vector<double> &x) { return x[0] * x[0] * x[0] + x[1] * x[1] * x[1] + 1.0; }; const double delta(0.01); double r(0.0); const auto c1(std::abs(h1(prg))); if (c1 > delta) r += c1; const auto c2(std::abs(h2(prg))); if (c2 > delta) r += c2; const auto c3(std::abs(h3(prg))); if (c3 > delta) r += c3; for (unsigned i(0), size(prg.size()); i < size; ++i) { if (prg[i] < -2.3) r += -2.3 - prg[i]; else if (prg[i] > 3.2) r += prg[i] - 3.2; } return r; }; vita::ga_search<vita::i_ga, vita::de_es, decltype(f)> s(prob, f, p); BOOST_REQUIRE(s.debug(true)); const auto res(s.run(10)); BOOST_CHECK_CLOSE(-f(res), 0.053950, 2.0); BOOST_CHECK_CLOSE(res[0], -1.717143, 1.0); BOOST_CHECK_CLOSE(res[1], 1.595709, 1.0); BOOST_CHECK_CLOSE(res[2], 1.827247, 1.0); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>[TEST] Fixed compilation error for test/ga_perf<commit_after>/** * \file * \remark This file is part of VITA. * * \copyright Copyright (C) 2015-2017 EOS di Manlio Morini. * * \license * 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 <cstdlib> #include <sstream> #include "kernel/ga/evaluator.h" #include "kernel/ga/i_de.h" #include "kernel/ga/search.h" #include "kernel/evolution.h" #include "kernel/problem.h" #if !defined(MASTER_TEST_SET) #define BOOST_TEST_MODULE t_de_perf #include <boost/test/unit_test.hpp> using namespace boost; #include "factory_fixture5.h" #endif BOOST_FIXTURE_TEST_SUITE(t_de7, F_FACTORY5_NO_INIT) // Test problem 7 from "An Efficient Constraint Handling Method for Genetic // Algorithms" BOOST_AUTO_TEST_CASE(Search_TestProblem7, * boost::unit_test::tolerance(1.0)) { vita::print.verbosity(vita::log::L_WARNING); vita::problem prob; prob.env.individuals = 100; prob.env.generations = 2000; prob.env.threshold.fitness = {0, 0}; prob.env.stat.dir = "."; prob.env.stat.layers = true; prob.sset.insert(vita::ga::parameter(0, -2.3, 2.3)); prob.sset.insert(vita::ga::parameter(1, -2.3, 2.3)); prob.sset.insert(vita::ga::parameter(2, -3.2, 3.2)); prob.sset.insert(vita::ga::parameter(3, -3.2, 3.2)); prob.sset.insert(vita::ga::parameter(4, -3.2, 3.2)); auto f = [](const std::vector<double> &x) { return -std::exp(x[0] * x[1] * x[2] * x[3] * x[4]); }; auto p = [](const vita::i_de &prg) { auto h1 = [](const std::vector<double> &x) { return x[0] * x[0] + x[1] * x[1] + x[2] * x[2] + x[3] * x[3] + x[4] * x[4] - 10.0; }; auto h2 = [](const std::vector<double> &x) { return x[1] * x[2] - 5.0 * x[3] * x[4]; }; auto h3 = [](const std::vector<double> &x) { return x[0] * x[0] * x[0] + x[1] * x[1] * x[1] + 1.0; }; const double delta(0.01); double r(0.0); const auto c1(std::abs(h1(prg))); if (c1 > delta) r += c1; const auto c2(std::abs(h2(prg))); if (c2 > delta) r += c2; const auto c3(std::abs(h3(prg))); if (c3 > delta) r += c3; for (const auto &pi : prg) { if (pi < -2.3) r += -2.3 - pi; else if (pi > 3.2) r += pi - 3.2; } return r; }; vita::ga_search<vita::i_de, vita::de_es, decltype(f)> s(prob, f, p); BOOST_TEST(s.debug()); const auto res(s.run(10).best.solution); BOOST_TEST(-f(res) == 0.053950); BOOST_TEST(res[0] == -1.717143); BOOST_TEST(res[1] == 1.595709); BOOST_TEST(res[2] == 1.827247); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 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 "chrome/browser/shell_integration.h" #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <vector> #include "app/gfx/codec/png_codec.h" #include "base/command_line.h" #include "base/eintr_wrapper.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/file_util_icu.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/scoped_temp_dir.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_plugin_util.h" #include "chrome/common/chrome_switches.h" #include "googleurl/src/gurl.h" namespace { const char* GetDesktopName() { #if defined(GOOGLE_CHROME_BUILD) return "google-chrome.desktop"; #else // CHROMIUM_BUILD static const char* name = NULL; if (!name) { // Allow $CHROME_DESKTOP to override the built-in value, so that development // versions can set themselves as the default without interfering with // non-official, packaged versions using the built-in value. name = getenv("CHROME_DESKTOP"); if (!name) name = "chromium-browser.desktop"; } return name; #endif } // Helper to launch xdg scripts. We don't want them to ask any questions on the // terminal etc. bool LaunchXdgUtility(const std::vector<std::string>& argv) { // xdg-settings internally runs xdg-mime, which uses mv to move newly-created // files on top of originals after making changes to them. In the event that // the original files are owned by another user (e.g. root, which can happen // if they are updated within sudo), mv will prompt the user to confirm if // standard input is a terminal (otherwise it just does it). So make sure it's // not, to avoid locking everything up waiting for mv. int devnull = open("/dev/null", O_RDONLY); if (devnull < 0) return false; base::file_handle_mapping_vector no_stdin; no_stdin.push_back(std::make_pair(devnull, STDIN_FILENO)); base::ProcessHandle handle; if (!base::LaunchApp(argv, no_stdin, false, &handle)) { close(devnull); return false; } close(devnull); int success_code; base::WaitForExitCode(handle, &success_code); return success_code == EXIT_SUCCESS; } bool GetDesktopShortcutTemplate(std::string* output) { std::vector<FilePath> search_paths; const char* xdg_data_home = getenv("XDG_DATA_HOME"); if (xdg_data_home) search_paths.push_back(FilePath(xdg_data_home)); const char* xdg_data_dirs = getenv("XDG_DATA_DIRS"); if (xdg_data_dirs) { CStringTokenizer tokenizer(xdg_data_dirs, xdg_data_dirs + strlen(xdg_data_dirs), ":"); while (tokenizer.GetNext()) { FilePath data_dir(tokenizer.token()); search_paths.push_back(data_dir); search_paths.push_back(data_dir.Append("applications")); } } std::string template_filename(GetDesktopName()); for (std::vector<FilePath>::const_iterator i = search_paths.begin(); i != search_paths.end(); ++i) { FilePath path = (*i).Append(template_filename); if (file_util::PathExists(path)) return file_util::ReadFileToString(path, output); } return false; } class CreateDesktopShortcutTask : public Task { public: CreateDesktopShortcutTask(const ShellIntegration::ShortcutInfo& shortcut_info) : shortcut_info_(shortcut_info) { } virtual void Run() { // TODO(phajdan.jr): Report errors from this function, possibly as infobars. std::string template_contents; if (!GetDesktopShortcutTemplate(&template_contents)) return; FilePath shortcut_filename = ShellIntegration::GetDesktopShortcutFilename(shortcut_info_.url); if (shortcut_filename.empty()) return; std::string icon_name = CreateIcon(shortcut_filename); std::string contents = ShellIntegration::GetDesktopFileContents( template_contents, shortcut_info_.url, shortcut_info_.title, icon_name); if (shortcut_info_.create_on_desktop) CreateOnDesktop(shortcut_filename, contents); if (shortcut_info_.create_in_applications_menu) CreateInApplicationsMenu(shortcut_filename, contents); } private: std::string CreateIcon(const FilePath& shortcut_filename) { if (shortcut_info_.favicon.isNull()) return std::string(); // TODO(phajdan.jr): Report errors from this function, possibly as infobars. ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDir()) return std::string(); FilePath temp_file_path = temp_dir.path().Append( shortcut_filename.ReplaceExtension("png")); std::vector<unsigned char> png_data; gfx::PNGCodec::EncodeBGRASkBitmap(shortcut_info_.favicon, false, &png_data); int bytes_written = file_util::WriteFile(temp_file_path, reinterpret_cast<char*>(png_data.data()), png_data.size()); if (bytes_written != static_cast<int>(png_data.size())) return std::string(); std::vector<std::string> argv; argv.push_back("xdg-icon-resource"); argv.push_back("install"); // Always install in user mode, even if someone runs the browser as root // (people do that). argv.push_back("--mode"); argv.push_back("user"); argv.push_back("--size"); argv.push_back(IntToString(shortcut_info_.favicon.width())); argv.push_back(temp_file_path.value()); std::string icon_name = temp_file_path.BaseName().RemoveExtension().value(); argv.push_back(icon_name); LaunchXdgUtility(argv); return icon_name; } void CreateOnDesktop(const FilePath& shortcut_filename, const std::string& contents) { // TODO(phajdan.jr): Report errors from this function, possibly as infobars. // Make sure that we will later call openat in a secure way. DCHECK_EQ(shortcut_filename.BaseName().value(), shortcut_filename.value()); FilePath desktop_path; if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_path)) return; int desktop_fd = open(desktop_path.value().c_str(), O_RDONLY | O_DIRECTORY); if (desktop_fd < 0) return; int fd = openat(desktop_fd, shortcut_filename.value().c_str(), O_CREAT | O_EXCL | O_WRONLY, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); if (fd < 0) { HANDLE_EINTR(close(desktop_fd)); return; } ssize_t bytes_written = file_util::WriteFileDescriptor(fd, contents.data(), contents.length()); HANDLE_EINTR(close(fd)); if (bytes_written != static_cast<ssize_t>(contents.length())) { // Delete the file. No shortuct is better than corrupted one. Use unlinkat // to make sure we're deleting the file in the directory we think we are. // Even if an attacker manager to put something other at // |shortcut_filename| we'll just undo his action. unlinkat(desktop_fd, shortcut_filename.value().c_str(), 0); } HANDLE_EINTR(close(desktop_fd)); } void CreateInApplicationsMenu(const FilePath& shortcut_filename, const std::string& contents) { // TODO(phajdan.jr): Report errors from this function, possibly as infobars. ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDir()) return; FilePath temp_file_path = temp_dir.path().Append(shortcut_filename); int bytes_written = file_util::WriteFile(temp_file_path, contents.data(), contents.length()); if (bytes_written != static_cast<int>(contents.length())) return; std::vector<std::string> argv; argv.push_back("xdg-desktop-menu"); argv.push_back("install"); // Always install in user mode, even if someone runs the browser as root // (people do that). argv.push_back("--mode"); argv.push_back("user"); argv.push_back(temp_file_path.value()); LaunchXdgUtility(argv); } const ShellIntegration::ShortcutInfo shortcut_info_; DISALLOW_COPY_AND_ASSIGN(CreateDesktopShortcutTask); }; } // namespace // We delegate the difficulty of setting the default browser in Linux desktop // environments to a new xdg utility, xdg-settings. We have to include a copy of // it for this to work, obviously, but that's actually the suggested approach // for xdg utilities anyway. bool ShellIntegration::SetAsDefaultBrowser() { std::vector<std::string> argv; argv.push_back("xdg-settings"); argv.push_back("set"); argv.push_back("default-web-browser"); argv.push_back(GetDesktopName()); return LaunchXdgUtility(argv); } ShellIntegration::DefaultBrowserState ShellIntegration::IsDefaultBrowser() { std::vector<std::string> argv; argv.push_back("xdg-settings"); argv.push_back("check"); argv.push_back("default-web-browser"); argv.push_back(GetDesktopName()); std::string reply; if (!base::GetAppOutput(CommandLine(argv), &reply)) { // xdg-settings failed: we can't determine or set the default browser. return UNKNOWN_DEFAULT_BROWSER; } // Allow any reply that starts with "yes". return (reply.find("yes") == 0) ? IS_DEFAULT_BROWSER : NOT_DEFAULT_BROWSER; } bool ShellIntegration::IsFirefoxDefaultBrowser() { std::vector<std::string> argv; argv.push_back("xdg-settings"); argv.push_back("get"); argv.push_back("default-web-browser"); std::string browser; // We don't care about the return value here. base::GetAppOutput(CommandLine(argv), &browser); return browser.find("irefox") != std::string::npos; } FilePath ShellIntegration::GetDesktopShortcutFilename(const GURL& url) { // Use a prefix, because xdg-desktop-menu requires it. std::wstring filename_wide = std::wstring(chrome::kBrowserProcessExecutableName) + L"-" + UTF8ToWide(url.spec()); file_util::ReplaceIllegalCharacters(&filename_wide, '_'); FilePath desktop_path; if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_path)) return FilePath(); FilePath filepath = desktop_path.Append( FilePath::FromWStringHack(filename_wide)); FilePath alternative_filepath(filepath.value() + ".desktop"); for (size_t i = 1; i < 100; ++i) { if (file_util::PathExists(FilePath(alternative_filepath))) { alternative_filepath = FilePath(filepath.value() + "_" + IntToString(i) + ".desktop"); } else { return FilePath(alternative_filepath).BaseName(); } } return FilePath(); } std::string ShellIntegration::GetDesktopFileContents( const std::string& template_contents, const GURL& url, const string16& title, const std::string& icon_name) { // See http://standards.freedesktop.org/desktop-entry-spec/latest/ // Although not required by the spec, Nautilus on Ubuntu Karmic creates its // launchers with an xdg-open shebang. Follow that convention. std::string output_buffer("#!/usr/bin/env xdg-open\n"); StringTokenizer tokenizer(template_contents, "\n"); while (tokenizer.GetNext()) { if (tokenizer.token().substr(0, 5) == "Exec=") { std::string exec_path = tokenizer.token().substr(5); StringTokenizer exec_tokenizer(exec_path, " "); std::string final_path; while (exec_tokenizer.GetNext()) { if (exec_tokenizer.token() != "%U") final_path += exec_tokenizer.token() + " "; } std::string switches; CPB_GetCommandLineArgumentsCommon(url.spec().c_str(), &switches); output_buffer += std::string("Exec=") + final_path + switches + "\n"; } else if (tokenizer.token().substr(0, 5) == "Name=") { std::string final_title = UTF16ToUTF8(title); // Make sure no endline characters can slip in and possibly introduce // additional lines (like Exec, which makes it a security risk). Also // use the URL as a default when the title is empty. if (final_title.empty() || final_title.find("\n") != std::string::npos || final_title.find("\r") != std::string::npos) { final_title = url.spec(); } output_buffer += StringPrintf("Name=%s\n", final_title.c_str()); } else if (tokenizer.token().substr(0, 11) == "GenericName" || tokenizer.token().substr(0, 7) == "Comment" || tokenizer.token().substr(0, 1) == "#") { // Skip comment lines. } else if (tokenizer.token().substr(0, 5) == "Icon=" && !icon_name.empty()) { output_buffer += StringPrintf("Icon=%s\n", icon_name.c_str()); } else { output_buffer += tokenizer.token() + "\n"; } } return output_buffer; } void ShellIntegration::CreateDesktopShortcut( const ShortcutInfo& shortcut_info) { g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, new CreateDesktopShortcutTask(shortcut_info)); } <commit_msg>Fix creating desktop shortcuts for systems with empty or incomplete XDG_DATA_DIRS.<commit_after>// Copyright (c) 2006-2009 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 "chrome/browser/shell_integration.h" #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <vector> #include "app/gfx/codec/png_codec.h" #include "base/command_line.h" #include "base/eintr_wrapper.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/file_util_icu.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/scoped_temp_dir.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_plugin_util.h" #include "chrome/common/chrome_switches.h" #include "googleurl/src/gurl.h" namespace { const char* GetDesktopName() { #if defined(GOOGLE_CHROME_BUILD) return "google-chrome.desktop"; #else // CHROMIUM_BUILD static const char* name = NULL; if (!name) { // Allow $CHROME_DESKTOP to override the built-in value, so that development // versions can set themselves as the default without interfering with // non-official, packaged versions using the built-in value. name = getenv("CHROME_DESKTOP"); if (!name) name = "chromium-browser.desktop"; } return name; #endif } // Helper to launch xdg scripts. We don't want them to ask any questions on the // terminal etc. bool LaunchXdgUtility(const std::vector<std::string>& argv) { // xdg-settings internally runs xdg-mime, which uses mv to move newly-created // files on top of originals after making changes to them. In the event that // the original files are owned by another user (e.g. root, which can happen // if they are updated within sudo), mv will prompt the user to confirm if // standard input is a terminal (otherwise it just does it). So make sure it's // not, to avoid locking everything up waiting for mv. int devnull = open("/dev/null", O_RDONLY); if (devnull < 0) return false; base::file_handle_mapping_vector no_stdin; no_stdin.push_back(std::make_pair(devnull, STDIN_FILENO)); base::ProcessHandle handle; if (!base::LaunchApp(argv, no_stdin, false, &handle)) { close(devnull); return false; } close(devnull); int success_code; base::WaitForExitCode(handle, &success_code); return success_code == EXIT_SUCCESS; } bool GetDesktopShortcutTemplate(std::string* output) { std::vector<FilePath> search_paths; const char* xdg_data_home = getenv("XDG_DATA_HOME"); if (xdg_data_home) search_paths.push_back(FilePath(xdg_data_home)); const char* xdg_data_dirs = getenv("XDG_DATA_DIRS"); if (xdg_data_dirs) { CStringTokenizer tokenizer(xdg_data_dirs, xdg_data_dirs + strlen(xdg_data_dirs), ":"); while (tokenizer.GetNext()) { FilePath data_dir(tokenizer.token()); search_paths.push_back(data_dir); search_paths.push_back(data_dir.Append("applications")); } } // Add some fallback paths for systems which don't have XDG_DATA_DIRS or have // it incomplete. search_paths.push_back(FilePath("/usr/share/applications")); search_paths.push_back(FilePath("/usr/local/share/applications")); std::string template_filename(GetDesktopName()); for (std::vector<FilePath>::const_iterator i = search_paths.begin(); i != search_paths.end(); ++i) { FilePath path = (*i).Append(template_filename); if (file_util::PathExists(path)) return file_util::ReadFileToString(path, output); } return false; } class CreateDesktopShortcutTask : public Task { public: CreateDesktopShortcutTask(const ShellIntegration::ShortcutInfo& shortcut_info) : shortcut_info_(shortcut_info) { } virtual void Run() { // TODO(phajdan.jr): Report errors from this function, possibly as infobars. std::string template_contents; if (!GetDesktopShortcutTemplate(&template_contents)) return; FilePath shortcut_filename = ShellIntegration::GetDesktopShortcutFilename(shortcut_info_.url); if (shortcut_filename.empty()) return; std::string icon_name = CreateIcon(shortcut_filename); std::string contents = ShellIntegration::GetDesktopFileContents( template_contents, shortcut_info_.url, shortcut_info_.title, icon_name); if (shortcut_info_.create_on_desktop) CreateOnDesktop(shortcut_filename, contents); if (shortcut_info_.create_in_applications_menu) CreateInApplicationsMenu(shortcut_filename, contents); } private: std::string CreateIcon(const FilePath& shortcut_filename) { if (shortcut_info_.favicon.isNull()) return std::string(); // TODO(phajdan.jr): Report errors from this function, possibly as infobars. ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDir()) return std::string(); FilePath temp_file_path = temp_dir.path().Append( shortcut_filename.ReplaceExtension("png")); std::vector<unsigned char> png_data; gfx::PNGCodec::EncodeBGRASkBitmap(shortcut_info_.favicon, false, &png_data); int bytes_written = file_util::WriteFile(temp_file_path, reinterpret_cast<char*>(png_data.data()), png_data.size()); if (bytes_written != static_cast<int>(png_data.size())) return std::string(); std::vector<std::string> argv; argv.push_back("xdg-icon-resource"); argv.push_back("install"); // Always install in user mode, even if someone runs the browser as root // (people do that). argv.push_back("--mode"); argv.push_back("user"); argv.push_back("--size"); argv.push_back(IntToString(shortcut_info_.favicon.width())); argv.push_back(temp_file_path.value()); std::string icon_name = temp_file_path.BaseName().RemoveExtension().value(); argv.push_back(icon_name); LaunchXdgUtility(argv); return icon_name; } void CreateOnDesktop(const FilePath& shortcut_filename, const std::string& contents) { // TODO(phajdan.jr): Report errors from this function, possibly as infobars. // Make sure that we will later call openat in a secure way. DCHECK_EQ(shortcut_filename.BaseName().value(), shortcut_filename.value()); FilePath desktop_path; if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_path)) return; int desktop_fd = open(desktop_path.value().c_str(), O_RDONLY | O_DIRECTORY); if (desktop_fd < 0) return; int fd = openat(desktop_fd, shortcut_filename.value().c_str(), O_CREAT | O_EXCL | O_WRONLY, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); if (fd < 0) { HANDLE_EINTR(close(desktop_fd)); return; } ssize_t bytes_written = file_util::WriteFileDescriptor(fd, contents.data(), contents.length()); HANDLE_EINTR(close(fd)); if (bytes_written != static_cast<ssize_t>(contents.length())) { // Delete the file. No shortuct is better than corrupted one. Use unlinkat // to make sure we're deleting the file in the directory we think we are. // Even if an attacker manager to put something other at // |shortcut_filename| we'll just undo his action. unlinkat(desktop_fd, shortcut_filename.value().c_str(), 0); } HANDLE_EINTR(close(desktop_fd)); } void CreateInApplicationsMenu(const FilePath& shortcut_filename, const std::string& contents) { // TODO(phajdan.jr): Report errors from this function, possibly as infobars. ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDir()) return; FilePath temp_file_path = temp_dir.path().Append(shortcut_filename); int bytes_written = file_util::WriteFile(temp_file_path, contents.data(), contents.length()); if (bytes_written != static_cast<int>(contents.length())) return; std::vector<std::string> argv; argv.push_back("xdg-desktop-menu"); argv.push_back("install"); // Always install in user mode, even if someone runs the browser as root // (people do that). argv.push_back("--mode"); argv.push_back("user"); argv.push_back(temp_file_path.value()); LaunchXdgUtility(argv); } const ShellIntegration::ShortcutInfo shortcut_info_; DISALLOW_COPY_AND_ASSIGN(CreateDesktopShortcutTask); }; } // namespace // We delegate the difficulty of setting the default browser in Linux desktop // environments to a new xdg utility, xdg-settings. We have to include a copy of // it for this to work, obviously, but that's actually the suggested approach // for xdg utilities anyway. bool ShellIntegration::SetAsDefaultBrowser() { std::vector<std::string> argv; argv.push_back("xdg-settings"); argv.push_back("set"); argv.push_back("default-web-browser"); argv.push_back(GetDesktopName()); return LaunchXdgUtility(argv); } ShellIntegration::DefaultBrowserState ShellIntegration::IsDefaultBrowser() { std::vector<std::string> argv; argv.push_back("xdg-settings"); argv.push_back("check"); argv.push_back("default-web-browser"); argv.push_back(GetDesktopName()); std::string reply; if (!base::GetAppOutput(CommandLine(argv), &reply)) { // xdg-settings failed: we can't determine or set the default browser. return UNKNOWN_DEFAULT_BROWSER; } // Allow any reply that starts with "yes". return (reply.find("yes") == 0) ? IS_DEFAULT_BROWSER : NOT_DEFAULT_BROWSER; } bool ShellIntegration::IsFirefoxDefaultBrowser() { std::vector<std::string> argv; argv.push_back("xdg-settings"); argv.push_back("get"); argv.push_back("default-web-browser"); std::string browser; // We don't care about the return value here. base::GetAppOutput(CommandLine(argv), &browser); return browser.find("irefox") != std::string::npos; } FilePath ShellIntegration::GetDesktopShortcutFilename(const GURL& url) { // Use a prefix, because xdg-desktop-menu requires it. std::wstring filename_wide = std::wstring(chrome::kBrowserProcessExecutableName) + L"-" + UTF8ToWide(url.spec()); file_util::ReplaceIllegalCharacters(&filename_wide, '_'); FilePath desktop_path; if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_path)) return FilePath(); FilePath filepath = desktop_path.Append( FilePath::FromWStringHack(filename_wide)); FilePath alternative_filepath(filepath.value() + ".desktop"); for (size_t i = 1; i < 100; ++i) { if (file_util::PathExists(FilePath(alternative_filepath))) { alternative_filepath = FilePath(filepath.value() + "_" + IntToString(i) + ".desktop"); } else { return FilePath(alternative_filepath).BaseName(); } } return FilePath(); } std::string ShellIntegration::GetDesktopFileContents( const std::string& template_contents, const GURL& url, const string16& title, const std::string& icon_name) { // See http://standards.freedesktop.org/desktop-entry-spec/latest/ // Although not required by the spec, Nautilus on Ubuntu Karmic creates its // launchers with an xdg-open shebang. Follow that convention. std::string output_buffer("#!/usr/bin/env xdg-open\n"); StringTokenizer tokenizer(template_contents, "\n"); while (tokenizer.GetNext()) { if (tokenizer.token().substr(0, 5) == "Exec=") { std::string exec_path = tokenizer.token().substr(5); StringTokenizer exec_tokenizer(exec_path, " "); std::string final_path; while (exec_tokenizer.GetNext()) { if (exec_tokenizer.token() != "%U") final_path += exec_tokenizer.token() + " "; } std::string switches; CPB_GetCommandLineArgumentsCommon(url.spec().c_str(), &switches); output_buffer += std::string("Exec=") + final_path + switches + "\n"; } else if (tokenizer.token().substr(0, 5) == "Name=") { std::string final_title = UTF16ToUTF8(title); // Make sure no endline characters can slip in and possibly introduce // additional lines (like Exec, which makes it a security risk). Also // use the URL as a default when the title is empty. if (final_title.empty() || final_title.find("\n") != std::string::npos || final_title.find("\r") != std::string::npos) { final_title = url.spec(); } output_buffer += StringPrintf("Name=%s\n", final_title.c_str()); } else if (tokenizer.token().substr(0, 11) == "GenericName" || tokenizer.token().substr(0, 7) == "Comment" || tokenizer.token().substr(0, 1) == "#") { // Skip comment lines. } else if (tokenizer.token().substr(0, 5) == "Icon=" && !icon_name.empty()) { output_buffer += StringPrintf("Icon=%s\n", icon_name.c_str()); } else { output_buffer += tokenizer.token() + "\n"; } } return output_buffer; } void ShellIntegration::CreateDesktopShortcut( const ShortcutInfo& shortcut_info) { g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, new CreateDesktopShortcutTask(shortcut_info)); } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <nlohmann/json.hpp> #include <vector> #include "DatatypeEnum.hpp" #include "RawBuffer.hpp" namespace dai { /// RawCameraControl structure struct RawCameraControl : public RawBuffer { enum class Command : uint8_t { START_STREAM = 1, STOP_STREAM = 2, STILL_CAPTURE = 3, MOVE_LENS = 4, /* [1] lens position: 0-255 */ AF_TRIGGER = 5, AE_MANUAL = 6, /* [1] exposure time [us] * [2] sensitivity [iso] * [3] frame duration [us] */ AE_AUTO = 7, AWB_MODE = 8, /* [1] awb_mode: AutoWhiteBalanceMode */ SCENE_MODE = 9, /* [1] scene_mode: SceneMode */ ANTIBANDING_MODE = 10, /* [1] antibanding_mode: AntiBandingMode */ EXPOSURE_COMPENSATION = 11, /* [1] value */ AE_LOCK = 13, /* [1] ae_lock_mode: bool */ AE_TARGET_FPS_RANGE = 14, /* [1] min_fps * [2] max_fps */ AWB_LOCK = 16, /* [1] awb_lock_mode: bool */ CAPTURE_INTENT = 17, /* [1] capture_intent_mode: CaptureIntent */ CONTROL_MODE = 18, /* [1] control_mode: ControlMode */ FRAME_DURATION = 21, /* [1] frame_duration */ SENSITIVITY = 23, /* [1] iso_val */ EFFECT_MODE = 24, /* [1] effect_mode: EffectMode */ AF_MODE = 26, /* [1] af_mode: AutoFocusMode */ NOISE_REDUCTION_STRENGTH = 27, /* [1] value */ SATURATION = 28, /* [1] value */ BRIGHTNESS = 31, /* [1] value */ STREAM_FORMAT = 33, /* [1] format */ RESOLUTION = 34, /* [1] width * [2] height */ SHARPNESS = 35, /* [1] value */ CUSTOM_USECASE = 40, /* [1] value */ CUSTOM_CAPT_MODE = 41, /* [1] value */ CUSTOM_EXP_BRACKETS = 42, /* [1] val1 * [2] val2 * [3] val3 */ CUSTOM_CAPTURE = 43, /* [1] value */ CONTRAST = 44, /* [1] value */ AE_REGION = 45, /* [1] x * [2] y * [3] width * [4] height * [5] priority */ AF_REGION = 46, /* [1] x * [2] y * [3] width * [4] height * [5] priority */ LUMA_DENOISE = 47, /* [1] value */ CHROMA_DENOISE = 48, /* [1] value */ EXTERNAL_TRIGGER = 50, }; enum class AutoFocusMode : uint8_t { /// Autofocus disabled. Suitable for manual focus OFF = 0, /// Runs autofocus once at startup, and at subsequent trigger commands AUTO, /// TODO MACRO, /// Runs autofocus when the scene is detected as out-of-focus CONTINUOUS_VIDEO, CONTINUOUS_PICTURE, EDOF, }; enum class AutoWhiteBalanceMode : uint8_t { OFF = 0, AUTO, INCANDESCENT, FLUORESCENT, WARM_FLUORESCENT, DAYLIGHT, CLOUDY_DAYLIGHT, TWILIGHT, SHADE, }; enum class SceneMode : uint8_t { UNSUPPORTED = 0, FACE_PRIORITY, ACTION, PORTRAIT, LANDSCAPE, NIGHT, NIGHT_PORTRAIT, THEATRE, BEACH, SNOW, SUNSET, STEADYPHOTO, FIREWORKS, SPORTS, PARTY, CANDLELIGHT, BARCODE, }; enum class AntiBandingMode : uint8_t { OFF = 0, MAINS_50_HZ, MAINS_60_HZ, AUTO, }; enum class CaptureIntent : uint8_t { CUSTOM = 0, PREVIEW, STILL_CAPTURE, VIDEO_RECORD, VIDEO_SNAPSHOT, ZERO_SHUTTER_LAG, }; enum class ControlMode : uint8_t { OFF = 0, AUTO, USE_SCENE_MODE, }; enum class EffectMode : uint8_t { OFF = 0, MONO, NEGATIVE, SOLARIZE, SEPIA, POSTERIZE, WHITEBOARD, BLACKBOARD, AQUA, }; struct ManualExposureParams { uint32_t exposureTimeUs; uint32_t sensitivityIso; uint32_t frameDurationUs; NLOHMANN_DEFINE_TYPE_INTRUSIVE(ManualExposureParams, exposureTimeUs, sensitivityIso, frameDurationUs); }; // AE_REGION / AF_REGION struct RegionParams { uint16_t x; uint16_t y; uint16_t width; uint16_t height; // Set to 1 for now. TODO uint32_t priority; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RegionParams, x, y, width, height, priority); }; uint64_t cmdMask = 0; AutoFocusMode autoFocusMode = AutoFocusMode::CONTINUOUS_VIDEO; /** * Lens/VCM position, range: 0..255. Used with `autoFocusMode = OFF`. * With current IMX378 modules: * - max 255: macro focus, at 8cm distance * - infinite focus at about 120..130 (may vary from module to module) * - lower values lead to out-of-focus (lens too close to the sensor array) */ uint8_t lensPosition = 0; ManualExposureParams expManual; RegionParams aeRegion, afRegion; AutoWhiteBalanceMode awbMode; SceneMode sceneMode; AntiBandingMode antiBandingMode; EffectMode effectMode; bool aeLockMode; bool awbLockMode; int8_t expCompensation; // -9 .. 9 int8_t brightness; // -10 .. 10 int8_t contrast; // -10 .. 10 int8_t saturation; // -10 .. 10 uint8_t sharpness; // 0 .. 4 uint8_t lumaDenoise; // 0 .. 4 uint8_t chromaDenoise; // 0 .. 4 uint8_t lowPowerNumFramesBurst; void setCommand(Command cmd, bool value = true) { uint64_t mask = 1ull << (uint8_t)cmd; if(value) { cmdMask |= mask; } else { cmdMask &= ~mask; } } void clearCommand(Command cmd) { setCommand(cmd, false); } bool getCommand(Command cmd) { return !!(cmdMask & (1ull << (uint8_t)cmd)); } void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override { nlohmann::json j = *this; metadata = nlohmann::json::to_msgpack(j); datatype = DatatypeEnum::CameraControl; }; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawCameraControl, cmdMask, autoFocusMode, lensPosition, expManual, aeRegion, afRegion, awbMode, sceneMode, antiBandingMode, aeLockMode, awbLockMode, effectMode, expCompensation, brightness, contrast, saturation, sharpness, lumaDenoise, chromaDenoise, lowPowerNumFramesBurst); }; } // namespace dai <commit_msg>RawCameraControl: add lowPowerNumFramesDiscard<commit_after>#pragma once #include <cstdint> #include <nlohmann/json.hpp> #include <vector> #include "DatatypeEnum.hpp" #include "RawBuffer.hpp" namespace dai { /// RawCameraControl structure struct RawCameraControl : public RawBuffer { enum class Command : uint8_t { START_STREAM = 1, STOP_STREAM = 2, STILL_CAPTURE = 3, MOVE_LENS = 4, /* [1] lens position: 0-255 */ AF_TRIGGER = 5, AE_MANUAL = 6, /* [1] exposure time [us] * [2] sensitivity [iso] * [3] frame duration [us] */ AE_AUTO = 7, AWB_MODE = 8, /* [1] awb_mode: AutoWhiteBalanceMode */ SCENE_MODE = 9, /* [1] scene_mode: SceneMode */ ANTIBANDING_MODE = 10, /* [1] antibanding_mode: AntiBandingMode */ EXPOSURE_COMPENSATION = 11, /* [1] value */ AE_LOCK = 13, /* [1] ae_lock_mode: bool */ AE_TARGET_FPS_RANGE = 14, /* [1] min_fps * [2] max_fps */ AWB_LOCK = 16, /* [1] awb_lock_mode: bool */ CAPTURE_INTENT = 17, /* [1] capture_intent_mode: CaptureIntent */ CONTROL_MODE = 18, /* [1] control_mode: ControlMode */ FRAME_DURATION = 21, /* [1] frame_duration */ SENSITIVITY = 23, /* [1] iso_val */ EFFECT_MODE = 24, /* [1] effect_mode: EffectMode */ AF_MODE = 26, /* [1] af_mode: AutoFocusMode */ NOISE_REDUCTION_STRENGTH = 27, /* [1] value */ SATURATION = 28, /* [1] value */ BRIGHTNESS = 31, /* [1] value */ STREAM_FORMAT = 33, /* [1] format */ RESOLUTION = 34, /* [1] width * [2] height */ SHARPNESS = 35, /* [1] value */ CUSTOM_USECASE = 40, /* [1] value */ CUSTOM_CAPT_MODE = 41, /* [1] value */ CUSTOM_EXP_BRACKETS = 42, /* [1] val1 * [2] val2 * [3] val3 */ CUSTOM_CAPTURE = 43, /* [1] value */ CONTRAST = 44, /* [1] value */ AE_REGION = 45, /* [1] x * [2] y * [3] width * [4] height * [5] priority */ AF_REGION = 46, /* [1] x * [2] y * [3] width * [4] height * [5] priority */ LUMA_DENOISE = 47, /* [1] value */ CHROMA_DENOISE = 48, /* [1] value */ EXTERNAL_TRIGGER = 50, }; enum class AutoFocusMode : uint8_t { /// Autofocus disabled. Suitable for manual focus OFF = 0, /// Runs autofocus once at startup, and at subsequent trigger commands AUTO, /// TODO MACRO, /// Runs autofocus when the scene is detected as out-of-focus CONTINUOUS_VIDEO, CONTINUOUS_PICTURE, EDOF, }; enum class AutoWhiteBalanceMode : uint8_t { OFF = 0, AUTO, INCANDESCENT, FLUORESCENT, WARM_FLUORESCENT, DAYLIGHT, CLOUDY_DAYLIGHT, TWILIGHT, SHADE, }; enum class SceneMode : uint8_t { UNSUPPORTED = 0, FACE_PRIORITY, ACTION, PORTRAIT, LANDSCAPE, NIGHT, NIGHT_PORTRAIT, THEATRE, BEACH, SNOW, SUNSET, STEADYPHOTO, FIREWORKS, SPORTS, PARTY, CANDLELIGHT, BARCODE, }; enum class AntiBandingMode : uint8_t { OFF = 0, MAINS_50_HZ, MAINS_60_HZ, AUTO, }; enum class CaptureIntent : uint8_t { CUSTOM = 0, PREVIEW, STILL_CAPTURE, VIDEO_RECORD, VIDEO_SNAPSHOT, ZERO_SHUTTER_LAG, }; enum class ControlMode : uint8_t { OFF = 0, AUTO, USE_SCENE_MODE, }; enum class EffectMode : uint8_t { OFF = 0, MONO, NEGATIVE, SOLARIZE, SEPIA, POSTERIZE, WHITEBOARD, BLACKBOARD, AQUA, }; struct ManualExposureParams { uint32_t exposureTimeUs; uint32_t sensitivityIso; uint32_t frameDurationUs; NLOHMANN_DEFINE_TYPE_INTRUSIVE(ManualExposureParams, exposureTimeUs, sensitivityIso, frameDurationUs); }; // AE_REGION / AF_REGION struct RegionParams { uint16_t x; uint16_t y; uint16_t width; uint16_t height; // Set to 1 for now. TODO uint32_t priority; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RegionParams, x, y, width, height, priority); }; uint64_t cmdMask = 0; AutoFocusMode autoFocusMode = AutoFocusMode::CONTINUOUS_VIDEO; /** * Lens/VCM position, range: 0..255. Used with `autoFocusMode = OFF`. * With current IMX378 modules: * - max 255: macro focus, at 8cm distance * - infinite focus at about 120..130 (may vary from module to module) * - lower values lead to out-of-focus (lens too close to the sensor array) */ uint8_t lensPosition = 0; ManualExposureParams expManual; RegionParams aeRegion, afRegion; AutoWhiteBalanceMode awbMode; SceneMode sceneMode; AntiBandingMode antiBandingMode; EffectMode effectMode; bool aeLockMode; bool awbLockMode; int8_t expCompensation; // -9 .. 9 int8_t brightness; // -10 .. 10 int8_t contrast; // -10 .. 10 int8_t saturation; // -10 .. 10 uint8_t sharpness; // 0 .. 4 uint8_t lumaDenoise; // 0 .. 4 uint8_t chromaDenoise; // 0 .. 4 uint8_t lowPowerNumFramesBurst; uint8_t lowPowerNumFramesDiscard; void setCommand(Command cmd, bool value = true) { uint64_t mask = 1ull << (uint8_t)cmd; if(value) { cmdMask |= mask; } else { cmdMask &= ~mask; } } void clearCommand(Command cmd) { setCommand(cmd, false); } bool getCommand(Command cmd) { return !!(cmdMask & (1ull << (uint8_t)cmd)); } void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override { nlohmann::json j = *this; metadata = nlohmann::json::to_msgpack(j); datatype = DatatypeEnum::CameraControl; }; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawCameraControl, cmdMask, autoFocusMode, lensPosition, expManual, aeRegion, afRegion, awbMode, sceneMode, antiBandingMode, aeLockMode, awbLockMode, effectMode, expCompensation, brightness, contrast, saturation, sharpness, lumaDenoise, chromaDenoise, lowPowerNumFramesBurst, lowPowerNumFramesDiscard); }; } // namespace dai <|endoftext|>
<commit_before>/* MIT License Copyright (c) 2018-2019 HolyWu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cmath> #include <string> #include <VapourSynth.h> #include <VSHelper.h> #include <w2xconv.h> struct Waifu2xData { VSNodeRef * node; VSVideoInfo vi; int noise, scale, block; int iterTimesTwiceScaling; float * srcInterleaved, * dstInterleaved; W2XConv * conv; }; static bool isPowerOf2(const int i) noexcept { return i && !(i & (i - 1)); } static bool filter(const VSFrameRef * src, VSFrameRef * dst, Waifu2xData * const VS_RESTRICT d, const VSAPI * vsapi) noexcept { const int width = vsapi->getFrameWidth(src, 0); const int height = vsapi->getFrameHeight(src, 0); const int srcStride = vsapi->getStride(src, 0) / sizeof(float); const int dstStride = vsapi->getStride(dst, 0) / sizeof(float); const float * srcpR = reinterpret_cast<const float *>(vsapi->getReadPtr(src, 0)); const float * srcpG = reinterpret_cast<const float *>(vsapi->getReadPtr(src, 1)); const float * srcpB = reinterpret_cast<const float *>(vsapi->getReadPtr(src, 2)); float * VS_RESTRICT dstpR = reinterpret_cast<float *>(vsapi->getWritePtr(dst, 0)); float * VS_RESTRICT dstpG = reinterpret_cast<float *>(vsapi->getWritePtr(dst, 1)); float * VS_RESTRICT dstpB = reinterpret_cast<float *>(vsapi->getWritePtr(dst, 2)); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { const int pos = (width * y + x) * 3; d->srcInterleaved[pos + 0] = srcpR[x]; d->srcInterleaved[pos + 1] = srcpG[x]; d->srcInterleaved[pos + 2] = srcpB[x]; } srcpR += srcStride; srcpG += srcStride; srcpB += srcStride; } if (w2xconv_convert_rgb_f32(d->conv, reinterpret_cast<unsigned char *>(d->dstInterleaved), d->vi.width * 3 * sizeof(float), reinterpret_cast<unsigned char *>(d->srcInterleaved), width * 3 * sizeof(float), width, height, d->noise, d->scale, d->block) < 0) return false; for (int y = 0; y < d->vi.height; y++) { for (int x = 0; x < d->vi.width; x++) { const int pos = (d->vi.width * y + x) * 3; dstpR[x] = d->dstInterleaved[pos + 0]; dstpG[x] = d->dstInterleaved[pos + 1]; dstpB[x] = d->dstInterleaved[pos + 2]; } dstpR += dstStride; dstpG += dstStride; dstpB += dstStride; } return true; } static void VS_CC waifu2xInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) { Waifu2xData * d = static_cast<Waifu2xData *>(*instanceData); vsapi->setVideoInfo(&d->vi, 1, node); } static const VSFrameRef *VS_CC waifu2xGetFrame(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) { Waifu2xData * d = static_cast<Waifu2xData *>(*instanceData); if (activationReason == arInitial) { vsapi->requestFrameFilter(n, d->node, frameCtx); } else if (activationReason == arAllFramesReady) { const VSFrameRef * src = vsapi->getFrameFilter(n, d->node, frameCtx); VSFrameRef * dst = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, src, core); if (!filter(src, dst, d, vsapi)) { char * error = w2xconv_strerror(&d->conv->last_error); vsapi->setFilterError((std::string{ "Waifu2x-w2xc: " } + error).c_str(), frameCtx); w2xconv_free(error); vsapi->freeFrame(src); vsapi->freeFrame(dst); return nullptr; } vsapi->freeFrame(src); return dst; } return nullptr; } static void VS_CC waifu2xFree(void *instanceData, VSCore *core, const VSAPI *vsapi) { Waifu2xData * d = static_cast<Waifu2xData *>(instanceData); vsapi->freeNode(d->node); delete[] d->srcInterleaved; delete[] d->dstInterleaved; w2xconv_fini(d->conv); delete d; } static void VS_CC waifu2xCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) { Waifu2xData d{}; int err; d.node = vsapi->propGetNode(in, "clip", 0, nullptr); d.vi = *vsapi->getVideoInfo(d.node); try { if (!isConstantFormat(&d.vi) || d.vi.format->colorFamily != cmRGB || d.vi.format->sampleType != stFloat || d.vi.format->bitsPerSample != 32) throw std::string{ "only constant RGB format and 32 bit float input supported" }; d.noise = int64ToIntS(vsapi->propGetInt(in, "noise", 0, &err)); d.scale = int64ToIntS(vsapi->propGetInt(in, "scale", 0, &err)); if (err) d.scale = 2; d.block = int64ToIntS(vsapi->propGetInt(in, "block", 0, &err)); if (err) d.block = 512; const bool photo = !!vsapi->propGetInt(in, "photo", 0, &err); W2XConvGPUMode gpu = static_cast<W2XConvGPUMode>(int64ToIntS(vsapi->propGetInt(in, "gpu", 0, &err))); if (err) gpu = W2XCONV_GPU_AUTO; int processor = int64ToIntS(vsapi->propGetInt(in, "processor", 0, &err)); if (err) processor = -1; const bool log = !!vsapi->propGetInt(in, "log", 0, &err); size_t numProcessors; const W2XConvProcessor * processors = w2xconv_get_processor_list(&numProcessors); if (d.noise < -1 || d.noise > 3) throw std::string{ "noise must be -1, 0, 1, 2, or 3" }; if (d.scale < 1 || !isPowerOf2(d.scale)) throw std::string{ "scale must be greater than or equal to 1 and be a power of 2" }; if (d.block < 1) throw std::string{ "block must be greater than or equal to 1" }; if (gpu < 0 || gpu > 2) throw std::string{ "gpu must be 0, 1, or 2" }; if (processor >= static_cast<int>(numProcessors)) throw std::string{ "the specified processor is not available" }; if (!!vsapi->propGetInt(in, "list_proc", 0, &err)) { std::string text; for (size_t i = 0; i < numProcessors; i++) { const W2XConvProcessor * p = &processors[i]; const char * type; switch (p->type) { case W2XCONV_PROC_HOST: switch (p->sub_type) { case W2XCONV_PROC_HOST_FMA: type = "FMA"; break; case W2XCONV_PROC_HOST_AVX: type = "AVX"; break; case W2XCONV_PROC_HOST_SSE3: type = "SSE3"; break; default: type = "OpenCV"; } break; case W2XCONV_PROC_CUDA: type = "CUDA"; break; case W2XCONV_PROC_OPENCL: type = "OpenCL"; break; default: type = "unknown"; } text += std::to_string(i) + ": " + p->dev_name + " (" + type + ")\n"; } VSMap * args = vsapi->createMap(); vsapi->propSetNode(args, "clip", d.node, paReplace); vsapi->freeNode(d.node); vsapi->propSetData(args, "text", text.c_str(), -1, paReplace); VSMap * ret = vsapi->invoke(vsapi->getPluginById("com.vapoursynth.text", core), "Text", args); if (vsapi->getError(ret)) { vsapi->setError(out, vsapi->getError(ret)); vsapi->freeMap(args); vsapi->freeMap(ret); return; } d.node = vsapi->propGetNode(ret, "clip", 0, nullptr); vsapi->freeMap(args); vsapi->freeMap(ret); vsapi->propSetNode(out, "clip", d.node, paReplace); vsapi->freeNode(d.node); return; } if (d.noise == -1 && d.scale == 1) { vsapi->propSetNode(out, "clip", d.node, paReplace); vsapi->freeNode(d.node); return; } if (d.scale != 1) { d.vi.width *= d.scale; d.vi.height *= d.scale; d.iterTimesTwiceScaling = static_cast<int>(std::log2(d.scale)); } d.srcInterleaved = new (std::nothrow) float[vsapi->getVideoInfo(d.node)->width * vsapi->getVideoInfo(d.node)->height * 3]; d.dstInterleaved = new (std::nothrow) float[d.vi.width * d.vi.height * 3]; if (!d.srcInterleaved || !d.dstInterleaved) throw std::string{ "malloc failure (srcInterleaved/dstInterleaved)" }; const int numThreads = vsapi->getCoreInfo(core)->numThreads; if (processor > -1) d.conv = w2xconv_init_with_processor(processor, numThreads, log); else d.conv = w2xconv_init(gpu, numThreads, log); const std::string pluginPath{ vsapi->getPluginPath(vsapi->getPluginById("com.holywu.waifu2x-w2xc", core)) }; std::string modelPath{ pluginPath.substr(0, pluginPath.find_last_of('/')) }; if (photo) modelPath += "/models/photo"; else modelPath += "/models/anime_style_art_rgb"; if (w2xconv_load_models(d.conv, modelPath.c_str()) < 0) { char * error = w2xconv_strerror(&d.conv->last_error); vsapi->setError(out, (std::string{ "Waifu2x-w2xc: " } + error).c_str()); w2xconv_free(error); vsapi->freeNode(d.node); w2xconv_fini(d.conv); return; } } catch (const std::string & error) { vsapi->setError(out, ("Waifu2x-w2xc: " + error).c_str()); vsapi->freeNode(d.node); return; } Waifu2xData * data = new Waifu2xData{ d }; vsapi->createFilter(in, out, "Waifu2x-w2xc", waifu2xInit, waifu2xGetFrame, waifu2xFree, fmParallelRequests, 0, data, core); } ////////////////////////////////////////// // Init VS_EXTERNAL_API(void) VapourSynthPluginInit(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin *plugin) { configFunc("com.holywu.waifu2x-w2xc", "w2xc", "Image Super-Resolution using Deep Convolutional Neural Networks", VAPOURSYNTH_API_VERSION, 1, plugin); registerFunc("Waifu2x", "clip:clip;" "noise:int:opt;" "scale:int:opt;" "block:int:opt;" "photo:int:opt;" "gpu:int:opt;" "processor:int:opt;" "list_proc:int:opt;" "log:int:opt;", waifu2xCreate, nullptr, plugin); } <commit_msg>Define HAVE_OPENCV before including w2xconv.h<commit_after>/* MIT License Copyright (c) 2018-2019 HolyWu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cmath> #include <string> #include <VapourSynth.h> #include <VSHelper.h> #define HAVE_OPENCV #include <w2xconv.h> struct Waifu2xData { VSNodeRef * node; VSVideoInfo vi; int noise, scale, block; int iterTimesTwiceScaling; float * srcInterleaved, * dstInterleaved; W2XConv * conv; }; static bool isPowerOf2(const int i) noexcept { return i && !(i & (i - 1)); } static bool filter(const VSFrameRef * src, VSFrameRef * dst, Waifu2xData * const VS_RESTRICT d, const VSAPI * vsapi) noexcept { const int width = vsapi->getFrameWidth(src, 0); const int height = vsapi->getFrameHeight(src, 0); const int srcStride = vsapi->getStride(src, 0) / sizeof(float); const int dstStride = vsapi->getStride(dst, 0) / sizeof(float); const float * srcpR = reinterpret_cast<const float *>(vsapi->getReadPtr(src, 0)); const float * srcpG = reinterpret_cast<const float *>(vsapi->getReadPtr(src, 1)); const float * srcpB = reinterpret_cast<const float *>(vsapi->getReadPtr(src, 2)); float * VS_RESTRICT dstpR = reinterpret_cast<float *>(vsapi->getWritePtr(dst, 0)); float * VS_RESTRICT dstpG = reinterpret_cast<float *>(vsapi->getWritePtr(dst, 1)); float * VS_RESTRICT dstpB = reinterpret_cast<float *>(vsapi->getWritePtr(dst, 2)); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { const int pos = (width * y + x) * 3; d->srcInterleaved[pos + 0] = srcpR[x]; d->srcInterleaved[pos + 1] = srcpG[x]; d->srcInterleaved[pos + 2] = srcpB[x]; } srcpR += srcStride; srcpG += srcStride; srcpB += srcStride; } if (w2xconv_convert_rgb_f32(d->conv, reinterpret_cast<unsigned char *>(d->dstInterleaved), d->vi.width * 3 * sizeof(float), reinterpret_cast<unsigned char *>(d->srcInterleaved), width * 3 * sizeof(float), width, height, d->noise, d->scale, d->block) < 0) return false; for (int y = 0; y < d->vi.height; y++) { for (int x = 0; x < d->vi.width; x++) { const int pos = (d->vi.width * y + x) * 3; dstpR[x] = d->dstInterleaved[pos + 0]; dstpG[x] = d->dstInterleaved[pos + 1]; dstpB[x] = d->dstInterleaved[pos + 2]; } dstpR += dstStride; dstpG += dstStride; dstpB += dstStride; } return true; } static void VS_CC waifu2xInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) { Waifu2xData * d = static_cast<Waifu2xData *>(*instanceData); vsapi->setVideoInfo(&d->vi, 1, node); } static const VSFrameRef *VS_CC waifu2xGetFrame(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) { Waifu2xData * d = static_cast<Waifu2xData *>(*instanceData); if (activationReason == arInitial) { vsapi->requestFrameFilter(n, d->node, frameCtx); } else if (activationReason == arAllFramesReady) { const VSFrameRef * src = vsapi->getFrameFilter(n, d->node, frameCtx); VSFrameRef * dst = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, src, core); if (!filter(src, dst, d, vsapi)) { char * error = w2xconv_strerror(&d->conv->last_error); vsapi->setFilterError((std::string{ "Waifu2x-w2xc: " } + error).c_str(), frameCtx); w2xconv_free(error); vsapi->freeFrame(src); vsapi->freeFrame(dst); return nullptr; } vsapi->freeFrame(src); return dst; } return nullptr; } static void VS_CC waifu2xFree(void *instanceData, VSCore *core, const VSAPI *vsapi) { Waifu2xData * d = static_cast<Waifu2xData *>(instanceData); vsapi->freeNode(d->node); delete[] d->srcInterleaved; delete[] d->dstInterleaved; w2xconv_fini(d->conv); delete d; } static void VS_CC waifu2xCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) { Waifu2xData d{}; int err; d.node = vsapi->propGetNode(in, "clip", 0, nullptr); d.vi = *vsapi->getVideoInfo(d.node); try { if (!isConstantFormat(&d.vi) || d.vi.format->colorFamily != cmRGB || d.vi.format->sampleType != stFloat || d.vi.format->bitsPerSample != 32) throw std::string{ "only constant RGB format and 32 bit float input supported" }; d.noise = int64ToIntS(vsapi->propGetInt(in, "noise", 0, &err)); d.scale = int64ToIntS(vsapi->propGetInt(in, "scale", 0, &err)); if (err) d.scale = 2; d.block = int64ToIntS(vsapi->propGetInt(in, "block", 0, &err)); if (err) d.block = 512; const bool photo = !!vsapi->propGetInt(in, "photo", 0, &err); W2XConvGPUMode gpu = static_cast<W2XConvGPUMode>(int64ToIntS(vsapi->propGetInt(in, "gpu", 0, &err))); if (err) gpu = W2XCONV_GPU_AUTO; int processor = int64ToIntS(vsapi->propGetInt(in, "processor", 0, &err)); if (err) processor = -1; const bool log = !!vsapi->propGetInt(in, "log", 0, &err); size_t numProcessors; const W2XConvProcessor * processors = w2xconv_get_processor_list(&numProcessors); if (d.noise < -1 || d.noise > 3) throw std::string{ "noise must be -1, 0, 1, 2, or 3" }; if (d.scale < 1 || !isPowerOf2(d.scale)) throw std::string{ "scale must be greater than or equal to 1 and be a power of 2" }; if (d.block < 1) throw std::string{ "block must be greater than or equal to 1" }; if (gpu < 0 || gpu > 2) throw std::string{ "gpu must be 0, 1, or 2" }; if (processor >= static_cast<int>(numProcessors)) throw std::string{ "the specified processor is not available" }; if (!!vsapi->propGetInt(in, "list_proc", 0, &err)) { std::string text; for (size_t i = 0; i < numProcessors; i++) { const W2XConvProcessor * p = &processors[i]; const char * type; switch (p->type) { case W2XCONV_PROC_HOST: switch (p->sub_type) { case W2XCONV_PROC_HOST_FMA: type = "FMA"; break; case W2XCONV_PROC_HOST_AVX: type = "AVX"; break; case W2XCONV_PROC_HOST_SSE3: type = "SSE3"; break; default: type = "OpenCV"; } break; case W2XCONV_PROC_CUDA: type = "CUDA"; break; case W2XCONV_PROC_OPENCL: type = "OpenCL"; break; default: type = "unknown"; } text += std::to_string(i) + ": " + p->dev_name + " (" + type + ")\n"; } VSMap * args = vsapi->createMap(); vsapi->propSetNode(args, "clip", d.node, paReplace); vsapi->freeNode(d.node); vsapi->propSetData(args, "text", text.c_str(), -1, paReplace); VSMap * ret = vsapi->invoke(vsapi->getPluginById("com.vapoursynth.text", core), "Text", args); if (vsapi->getError(ret)) { vsapi->setError(out, vsapi->getError(ret)); vsapi->freeMap(args); vsapi->freeMap(ret); return; } d.node = vsapi->propGetNode(ret, "clip", 0, nullptr); vsapi->freeMap(args); vsapi->freeMap(ret); vsapi->propSetNode(out, "clip", d.node, paReplace); vsapi->freeNode(d.node); return; } if (d.noise == -1 && d.scale == 1) { vsapi->propSetNode(out, "clip", d.node, paReplace); vsapi->freeNode(d.node); return; } if (d.scale != 1) { d.vi.width *= d.scale; d.vi.height *= d.scale; d.iterTimesTwiceScaling = static_cast<int>(std::log2(d.scale)); } d.srcInterleaved = new (std::nothrow) float[vsapi->getVideoInfo(d.node)->width * vsapi->getVideoInfo(d.node)->height * 3]; d.dstInterleaved = new (std::nothrow) float[d.vi.width * d.vi.height * 3]; if (!d.srcInterleaved || !d.dstInterleaved) throw std::string{ "malloc failure (srcInterleaved/dstInterleaved)" }; const int numThreads = vsapi->getCoreInfo(core)->numThreads; if (processor > -1) d.conv = w2xconv_init_with_processor(processor, numThreads, log); else d.conv = w2xconv_init(gpu, numThreads, log); const std::string pluginPath{ vsapi->getPluginPath(vsapi->getPluginById("com.holywu.waifu2x-w2xc", core)) }; std::string modelPath{ pluginPath.substr(0, pluginPath.find_last_of('/')) }; if (photo) modelPath += "/models/photo"; else modelPath += "/models/anime_style_art_rgb"; if (w2xconv_load_models(d.conv, modelPath.c_str()) < 0) { char * error = w2xconv_strerror(&d.conv->last_error); vsapi->setError(out, (std::string{ "Waifu2x-w2xc: " } + error).c_str()); w2xconv_free(error); vsapi->freeNode(d.node); w2xconv_fini(d.conv); return; } } catch (const std::string & error) { vsapi->setError(out, ("Waifu2x-w2xc: " + error).c_str()); vsapi->freeNode(d.node); return; } Waifu2xData * data = new Waifu2xData{ d }; vsapi->createFilter(in, out, "Waifu2x-w2xc", waifu2xInit, waifu2xGetFrame, waifu2xFree, fmParallelRequests, 0, data, core); } ////////////////////////////////////////// // Init VS_EXTERNAL_API(void) VapourSynthPluginInit(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin *plugin) { configFunc("com.holywu.waifu2x-w2xc", "w2xc", "Image Super-Resolution using Deep Convolutional Neural Networks", VAPOURSYNTH_API_VERSION, 1, plugin); registerFunc("Waifu2x", "clip:clip;" "noise:int:opt;" "scale:int:opt;" "block:int:opt;" "photo:int:opt;" "gpu:int:opt;" "processor:int:opt;" "list_proc:int:opt;" "log:int:opt;", waifu2xCreate, nullptr, plugin); } <|endoftext|>
<commit_before>/********************************************************************************* * Copyright (c) 2013 David D. Marshall <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David D. Marshall - initial code and implementation ********************************************************************************/ #ifndef eli_mutil_nls_iterative_root_system_method_hpp #define eli_mutil_nls_iterative_root_system_method_hpp #ifdef Success // X11 #define collides with Eigen #undef Success #endif #include "Eigen/Eigen" #include "eli/mutil/nls/iterative_root_base.hpp" namespace eli { namespace mutil { namespace nls { template<typename data__, size_t N__, size_t NSOL__> class iterative_system_root_base : public iterative_root_base<data__> { public: typedef Eigen::Matrix<data__, N__, NSOL__> solution_matrix; typedef Eigen::Matrix<data__, N__, N__> jacobian_matrix; enum system_norm_type { L1=100, // for vectors this is sum of maxes, for matrices this is maximum absolute column sum L2=200, // for vectors this is sqrt of sum of squares, for matrices this will be equivalent to the Frobenius norm Linf=300, // for vectors this is the largest (in magnitude) terms, for matrices this is maximum abolute row sum max_norm=400, // for vectors this is equivalent to Linf, for matrices it is the largest element in matrix Frobenius_norm=500 // for vectors this is L2, for matrices this is the sqrt of sum of squares of each term }; public: iterative_system_root_base() : iterative_root_base<data__>(), norm_type(iterative_system_root_base<data__, N__, NSOL__>::max_norm) { } iterative_system_root_base(const iterative_system_root_base<data__, N__, NSOL__>& isrb) : iterative_root_base<data__>(isrb), norm_type(isrb.norm_type) { } ~iterative_system_root_base() { } system_norm_type get_norm_type() const { return norm_type; } void set_norm_type(system_norm_type snt) { norm_type = snt; } protected: data__ calculate_norm(const solution_matrix &mat) const { // handle the cases that do not need to distinguish between vectors and matrices switch (get_norm_type()) { case(L1): // for vectors this is sum of maxes, for matrices this is maximum absolute column sum { data__ rtn_val(-1), tmp; for (typename solution_matrix::Index nc=0; nc<mat.cols(); ++nc) { tmp=mat.col(nc).cwiseAbs().sum(); if (tmp>rtn_val) rtn_val=tmp; } return rtn_val; break; } case(Linf): // for vectors this is the largest (in magnitude) terms, for matrices this is maximum absolute row sum { data__ rtn_val(-1), tmp; for (typename solution_matrix::Index nr=0; nr<mat.rows(); ++nr) { tmp=mat.row(nr).cwiseAbs().sum(); if (tmp>rtn_val) rtn_val=tmp; } return rtn_val; break; } case(max_norm): // for vectors this is equivalent to Linf, for matrices it is the largest element in matrix { return std::abs(mat.maxCoeff()); break; } case(L2): // for vectors this is sqrt of sum of squares, for matrices this will be equivalent to the Frobenius norm case(Frobenius_norm): // for vectors this is L2, for matrices this is the sqrt of sum of squares of each term { data__ rtn_val(0); for (typename solution_matrix::Index nc=0; nc<mat.cols(); ++nc) rtn_val+=mat.col(nc).squaredNorm(); return std::sqrt(rtn_val); break; } default: { // unknown norm type assert(false); return static_cast<data__>(-1); } } return static_cast<data__>(-1); } private: system_norm_type norm_type; }; } } } #endif <commit_msg>Matrix inf norm was calculated wrong.<commit_after>/********************************************************************************* * Copyright (c) 2013 David D. Marshall <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David D. Marshall - initial code and implementation ********************************************************************************/ #ifndef eli_mutil_nls_iterative_root_system_method_hpp #define eli_mutil_nls_iterative_root_system_method_hpp #ifdef Success // X11 #define collides with Eigen #undef Success #endif #include "Eigen/Eigen" #include "eli/mutil/nls/iterative_root_base.hpp" namespace eli { namespace mutil { namespace nls { template<typename data__, size_t N__, size_t NSOL__> class iterative_system_root_base : public iterative_root_base<data__> { public: typedef Eigen::Matrix<data__, N__, NSOL__> solution_matrix; typedef Eigen::Matrix<data__, N__, N__> jacobian_matrix; enum system_norm_type { L1=100, // for vectors this is sum of maxes, for matrices this is maximum absolute column sum L2=200, // for vectors this is sqrt of sum of squares, for matrices this will be equivalent to the Frobenius norm Linf=300, // for vectors this is the largest (in magnitude) terms, for matrices this is maximum abolute row sum max_norm=400, // for vectors this is equivalent to Linf, for matrices it is the largest element in matrix Frobenius_norm=500 // for vectors this is L2, for matrices this is the sqrt of sum of squares of each term }; public: iterative_system_root_base() : iterative_root_base<data__>(), norm_type(iterative_system_root_base<data__, N__, NSOL__>::max_norm) { } iterative_system_root_base(const iterative_system_root_base<data__, N__, NSOL__>& isrb) : iterative_root_base<data__>(isrb), norm_type(isrb.norm_type) { } ~iterative_system_root_base() { } system_norm_type get_norm_type() const { return norm_type; } void set_norm_type(system_norm_type snt) { norm_type = snt; } protected: data__ calculate_norm(const solution_matrix &mat) const { // handle the cases that do not need to distinguish between vectors and matrices switch (get_norm_type()) { case(L1): // for vectors this is sum of maxes, for matrices this is maximum absolute column sum { data__ rtn_val(-1), tmp; for (typename solution_matrix::Index nc=0; nc<mat.cols(); ++nc) { tmp=mat.col(nc).cwiseAbs().sum(); if (tmp>rtn_val) rtn_val=tmp; } return rtn_val; break; } case(Linf): // for vectors this is the largest (in magnitude) terms, for matrices this is maximum absolute row sum { data__ rtn_val(-1), tmp; for (typename solution_matrix::Index nr=0; nr<mat.rows(); ++nr) { tmp=mat.row(nr).cwiseAbs().sum(); if (tmp>rtn_val) rtn_val=tmp; } return rtn_val; break; } case(max_norm): // for vectors this is equivalent to Linf, for matrices it is the largest element in matrix { data__ maxval = std::abs(mat.maxCoeff()); data__ minval = std::abs(mat.minCoeff()); if( maxval > minval ) return maxval; else return minval; // The following should work, but it throws an error: Expected expression. // return mat.lpNorm<Eigen::Infinity>(); break; } case(L2): // for vectors this is sqrt of sum of squares, for matrices this will be equivalent to the Frobenius norm case(Frobenius_norm): // for vectors this is L2, for matrices this is the sqrt of sum of squares of each term { data__ rtn_val(0); for (typename solution_matrix::Index nc=0; nc<mat.cols(); ++nc) rtn_val+=mat.col(nc).squaredNorm(); return std::sqrt(rtn_val); break; } default: { // unknown norm type assert(false); return static_cast<data__>(-1); } } return static_cast<data__>(-1); } private: system_norm_type norm_type; }; } } } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2007 Alp Toker <[email protected]> * Copyright (C) 2007 Apple Inc. * * 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; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "PrintContext.h" #include "GraphicsContext.h" #include "Frame.h" #include "RenderView.h" using namespace WebCore; namespace WebCore { PrintContext::PrintContext(Frame* frame) : m_frame(frame) { } PrintContext::~PrintContext() { m_pageRects.clear(); } int PrintContext::pageCount() const { return m_pageRects.size(); } void PrintContext::computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight) { m_pageRects.clear(); outPageHeight = 0; if (!m_frame->document() || !m_frame->view() || !m_frame->document()->renderer()) return; RenderView* root = static_cast<RenderView*>(m_frame->document()->renderer()); if (!root) { LOG_ERROR("document to be printed has no renderer"); return; } if (userScaleFactor <= 0) { LOG_ERROR("userScaleFactor has bad value %.2f", userScaleFactor); return; } float ratio = printRect.height() / printRect.width(); float pageWidth = (float)root->docWidth(); float pageHeight = pageWidth * ratio; outPageHeight = pageHeight; // this is the height of the page adjusted by margins pageHeight -= headerHeight + footerHeight; if (pageHeight <= 0) { LOG_ERROR("pageHeight has bad value %.2f", pageHeight); return; } float currPageHeight = pageHeight / userScaleFactor; float docHeight = root->layer()->height(); float currPageWidth = pageWidth / userScaleFactor; // always return at least one page, since empty files should print a blank page float printedPagesHeight = 0.0; do { float proposedBottom = std::min(docHeight, printedPagesHeight + pageHeight); m_frame->adjustPageHeight(&proposedBottom, printedPagesHeight, proposedBottom, printedPagesHeight); currPageHeight = max(1.0f, proposedBottom - printedPagesHeight); m_pageRects.append(IntRect(0, (int)printedPagesHeight, (int)currPageWidth, (int)currPageHeight)); printedPagesHeight += currPageHeight; } while (printedPagesHeight < docHeight); } void PrintContext::begin(float width) { // By imaging to a width a little wider than the available pixels, // thin pages will be scaled down a little, matching the way they // print in IE and Camino. This lets them use fewer sheets than they // would otherwise, which is presumably why other browsers do this. // Wide pages will be scaled down more than this. const float PrintingMinimumShrinkFactor = 1.25f; // This number determines how small we are willing to reduce the page content // in order to accommodate the widest line. If the page would have to be // reduced smaller to make the widest line fit, we just clip instead (this // behavior matches MacIE and Mozilla, at least) const float PrintingMaximumShrinkFactor = 2.0f; float minLayoutWidth = width * PrintingMinimumShrinkFactor; float maxLayoutWidth = width * PrintingMaximumShrinkFactor; // FIXME: This will modify the rendering of the on-screen frame. // Could lead to flicker during printing. m_frame->setPrinting(true, minLayoutWidth, maxLayoutWidth, true); } void PrintContext::spoolPage(GraphicsContext& ctx, int pageNumber, float width) { IntRect pageRect = m_pageRects[pageNumber]; float scale = width / pageRect.width(); ctx.save(); ctx.scale(FloatSize(scale, scale)); ctx.translate(-pageRect.x(), -pageRect.y()); ctx.clip(pageRect); m_frame->paint(&ctx, pageRect); ctx.restore(); } void PrintContext::end() { m_frame->setPrinting(false, 0, 0, true); } } <commit_msg>Fix Qt bustage.<commit_after>/* * Copyright (C) 2007 Alp Toker <[email protected]> * Copyright (C) 2007 Apple Inc. * * 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; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "PrintContext.h" #include "GraphicsContext.h" #include "Frame.h" #include "RenderView.h" using namespace WebCore; namespace WebCore { PrintContext::PrintContext(Frame* frame) : m_frame(frame) { } PrintContext::~PrintContext() { m_pageRects.clear(); } int PrintContext::pageCount() const { return m_pageRects.size(); } void PrintContext::computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight) { m_pageRects.clear(); outPageHeight = 0; if (!m_frame->document() || !m_frame->view() || !m_frame->document()->renderer()) return; RenderView* root = static_cast<RenderView*>(m_frame->document()->renderer()); if (!root) { LOG_ERROR("document to be printed has no renderer"); return; } if (userScaleFactor <= 0) { LOG_ERROR("userScaleFactor has bad value %.2f", userScaleFactor); return; } float ratio = printRect.height() / printRect.width(); float pageWidth = (float)root->docWidth(); float pageHeight = pageWidth * ratio; outPageHeight = pageHeight; // this is the height of the page adjusted by margins pageHeight -= headerHeight + footerHeight; if (pageHeight <= 0) { LOG_ERROR("pageHeight has bad value %.2f", pageHeight); return; } float currPageHeight = pageHeight / userScaleFactor; float docHeight = root->layer()->height(); float currPageWidth = pageWidth / userScaleFactor; // always return at least one page, since empty files should print a blank page float printedPagesHeight = 0.0; do { float proposedBottom = std::min(docHeight, printedPagesHeight + pageHeight); m_frame->adjustPageHeight(&proposedBottom, printedPagesHeight, proposedBottom, printedPagesHeight); currPageHeight = max(1.0f, proposedBottom - printedPagesHeight); m_pageRects.append(IntRect(0, (int)printedPagesHeight, (int)currPageWidth, (int)currPageHeight)); printedPagesHeight += currPageHeight; } while (printedPagesHeight < docHeight); } void PrintContext::begin(float width) { // By imaging to a width a little wider than the available pixels, // thin pages will be scaled down a little, matching the way they // print in IE and Camino. This lets them use fewer sheets than they // would otherwise, which is presumably why other browsers do this. // Wide pages will be scaled down more than this. const float PrintingMinimumShrinkFactor = 1.25f; // This number determines how small we are willing to reduce the page content // in order to accommodate the widest line. If the page would have to be // reduced smaller to make the widest line fit, we just clip instead (this // behavior matches MacIE and Mozilla, at least) const float PrintingMaximumShrinkFactor = 2.0f; float minLayoutWidth = width * PrintingMinimumShrinkFactor; float maxLayoutWidth = width * PrintingMaximumShrinkFactor; // FIXME: This will modify the rendering of the on-screen frame. // Could lead to flicker during printing. m_frame->setPrinting(true, minLayoutWidth, maxLayoutWidth, true); } void PrintContext::spoolPage(GraphicsContext& ctx, int pageNumber, float width) { IntRect pageRect = m_pageRects[pageNumber]; float scale = width / pageRect.width(); ctx.save(); ctx.scale(FloatSize(scale, scale)); ctx.translate(-pageRect.x(), -pageRect.y()); ctx.clip(pageRect); m_frame->view()->paintContents(&ctx, pageRect); ctx.restore(); } void PrintContext::end() { m_frame->setPrinting(false, 0, 0, true); } } <|endoftext|>