text
stringlengths
54
60.6k
<commit_before>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <crypto++/hmac.h> #include <crypto++/sha.h> #include <algorithm> #include <map> #include <vector> #include <cassert> #include <ctime> #include <cstdio> #include <cstring> #include <cstdlib> #include <cerrno> #include "common.hxx" #include "auth.hxx" #include "realm.hxx" using namespace std; typedef CryptoPP::HMAC<CryptoPP::SHA256> Hmac; class HmacCkecker { vector<byte> key; public: HmacCkecker() { FILE* in = fopen(SHARED_SECRET_FILE, "rb"); if (!in) { fprintf(stderr, "Unable to open %s: %s\n", SHARED_SECRET_FILE, strerror(errno)); exit(1); } byte buffer[4096]; size_t read; do { read = fread(buffer, 1, sizeof(buffer), in); key.insert(key.end(), buffer, buffer+read); } while (read == sizeof(buffer)); if (ferror(in)) { fprintf(stderr, "Error reading %s: %s\n", SHARED_SECRET_FILE, strerror(errno)); exit(1); } fclose(in); } bool operator()(const byte* data, size_t datasz, const byte* digest) { Hmac hmac; hmac.SetKey(&key[0], key.size()); return hmac.VerifyDigest(digest, data, datasz); } } static checkHmac; //"map" timestamps to ids (this allows us to easily track the pairs, and to //quickly remove out-of-date ranges) static realmed<multimap<unsigned,unsigned> > recentTimestamps; static unsigned truncatedTime() { return (unsigned)(time(NULL) & 0xFFFFFFFF); } bool authenticate(const Realm* realm, unsigned id, unsigned timestamp, const char* name, const byte* hmac) { unsigned now = truncatedTime(); if (timestamp > now || timestamp < now-TIMESTAMP_VARIANCE) return false; //Ensure the timestamp/id pair does not exist pair<multimap<unsigned,unsigned>::iterator, multimap<unsigned,unsigned>::iterator> bounds = recentTimestamps[realm].equal_range(timestamp); if (bounds.second != find(bounds.first, bounds.second, pair<const unsigned,unsigned>(timestamp,id))) //Already seen return false; vector<byte> data(2*4 + strlen(name)); memcpy(&data[0], &id, 4); memcpy(&data[4], &timestamp, 4); memcpy(&data[8], name, strlen(name)); //Ensure little-endian assert(data[0] == (id & 0xFF)); if (checkHmac(&data[0], data.size(), hmac)) { //OK recentTimestamps[realm].insert(make_pair(timestamp,id)); return true; } else { //Invalid HMAC return false; } } void updateAuthentication() { for (realmed<multimap<unsigned,unsigned> >::iterator it = recentTimestamps.begin(); it != recentTimestamps.end(); ++it) it->second.erase(it->second.begin(), it->second.upper_bound( truncatedTime()-TIMESTAMP_VARIANCE)); } <commit_msg>Add client debugging to auth.<commit_after>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <crypto++/hmac.h> #include <crypto++/sha.h> #include <algorithm> #include <map> #include <vector> #include <cassert> #include <ctime> #include <cstdio> #include <cstring> #include <cstdlib> #include <cerrno> #include "common.hxx" #include "auth.hxx" #include "realm.hxx" using namespace std; #ifdef CLIENT_DEBUG #include <iostream> #define debug(str) cerr << str << endl #else #define debug(str) #endif typedef CryptoPP::HMAC<CryptoPP::SHA256> Hmac; class HmacCkecker { vector<byte> key; public: HmacCkecker() { FILE* in = fopen(SHARED_SECRET_FILE, "rb"); if (!in) { fprintf(stderr, "Unable to open %s: %s\n", SHARED_SECRET_FILE, strerror(errno)); exit(1); } byte buffer[4096]; size_t read; do { read = fread(buffer, 1, sizeof(buffer), in); key.insert(key.end(), buffer, buffer+read); } while (read == sizeof(buffer)); if (ferror(in)) { fprintf(stderr, "Error reading %s: %s\n", SHARED_SECRET_FILE, strerror(errno)); exit(1); } fclose(in); } bool operator()(const byte* data, size_t datasz, const byte* digest) { Hmac hmac; hmac.SetKey(&key[0], key.size()); return hmac.VerifyDigest(digest, data, datasz); } } static checkHmac; //"map" timestamps to ids (this allows us to easily track the pairs, and to //quickly remove out-of-date ranges) static realmed<multimap<unsigned,unsigned> > recentTimestamps; static unsigned truncatedTime() { return (unsigned)(time(NULL) & 0xFFFFFFFF); } bool authenticate(const Realm* realm, unsigned id, unsigned timestamp, const char* name, const byte* hmac) { unsigned now = truncatedTime(); if (timestamp > now || timestamp < now-TIMESTAMP_VARIANCE) return false; debug("Auth timestamp OK"); //Ensure the timestamp/id pair does not exist pair<multimap<unsigned,unsigned>::iterator, multimap<unsigned,unsigned>::iterator> bounds = recentTimestamps[realm].equal_range(timestamp); if (bounds.second != find(bounds.first, bounds.second, pair<const unsigned,unsigned>(timestamp,id))) //Already seen return false; debug("Auth timestamp non-dupe"); vector<byte> data(2*4 + strlen(name)); memcpy(&data[0], &id, 4); memcpy(&data[4], &timestamp, 4); memcpy(&data[8], name, strlen(name)); //Ensure little-endian assert(data[0] == (id & 0xFF)); if (checkHmac(&data[0], data.size(), hmac)) { //OK recentTimestamps[realm].insert(make_pair(timestamp,id)); debug("HMAC OK"); return true; } else { //Invalid HMAC debug("HMAC Invalid"); return false; } } void updateAuthentication() { for (realmed<multimap<unsigned,unsigned> >::iterator it = recentTimestamps.begin(); it != recentTimestamps.end(); ++it) it->second.erase(it->second.begin(), it->second.upper_bound( truncatedTime()-TIMESTAMP_VARIANCE)); } <|endoftext|>
<commit_before>#include "ProcessorOpus.h" #include <fstream> //stream output to file ProcessorOpus::ProcessorOpus(std::string name, int opusApplication, int ErrorCode) : AudioProcessor(name) { //how to get audioData Object(SampleRate, ChannelNumber)? //Opus supports this sampleRates: 8000, 12000, 16000, 24000, or 48000. if (audioConfiguration.sampleRate == 8000 || audioConfiguration.sampleRate == 12000 || audioConfiguration.sampleRate == 16000 || audioConfiguration.sampleRate == 24000 || audioConfiguration.sampleRate == 48000) { this->sampleRate = audioConfiguration.sampleRate; } else { std::cout << "SampleRate not supported by Opus! Opus supports this sampleRates: 8000, 12000, 16000, 24000, or 48000." << std::endl; } //Opus supports mono(1 channel) and stereo(2 channels) only. if (audioConfiguration.inputDeviceChannels == 1 || audioConfiguration.inputDeviceChannels == 2) { this->channels = audioConfiguration.inputDeviceChannels; } else { std::cout << "Device Channels not supported by Opus! Opus supports 1 or 2 Device Channels" << std::endl; } // TODO: delete manuall selection of samplerate and channels OpusEncoderObject = opus_encoder_create(48000, 2, opusApplication, &ErrorCode); // TODO: delete manuall selection of samplerate and channels OpusDecoderObject = opus_decoder_create(48000, 2, &ErrorCode); } unsigned int ProcessorOpus::getSupportedAudioFormats() { return AudioConfiguration::AUDIO_FORMAT_SINT16; } unsigned int ProcessorOpus::getSupportedSampleRates() { //Opus supports this sampleRates: 8000, 12000, 16000, 24000, or 48000. = 1001111 binary in the format from configuration.h (every 1 stands for one supported format) = 79 decimal = 0x4F Hex unsigned int SupportedSampleRates = 79; return SupportedSampleRates; } unsigned char *EncodedPacketPointer = new unsigned char[4000]; unsigned int ProcessorOpus::processInputData(void *inputBuffer, const unsigned int inputBufferByteSize, StreamData *userData) { unsigned int lengthEncodedPacketInBytes; std::cout << userData->nBufferFrames << " [processInput]nBufferFrames should be 960" << std::endl; std::cout << userData->maxBufferSize << " [processInput]maxBufferSize" << std::endl; /* std::ofstream fileout("InputBuffer-before-encoding.raw", std::ios::out | std::ios::binary); fileout.write((char *)inputBuffer, userData->nBufferFrames); fileout.close(); */ lengthEncodedPacketInBytes = opus_encode(OpusEncoderObject, (opus_int16 *)inputBuffer, userData->nBufferFrames, (unsigned char *)EncodedPacketPointer, userData->maxBufferSize); /* std::ofstream fileout2("InputBuffer-after-encoding.raw", std::ios::out | std::ios::binary); fileout2.write((char *)EncodedPacketPointer, lengthEncodedPacketInBytes); fileout2.close(); */ std::cout << lengthEncodedPacketInBytes << " [processInput]lengthEncodedPacket" << std::endl; lengthEncodedPacketWorkaround = lengthEncodedPacketInBytes; return lengthEncodedPacketInBytes; } unsigned int ProcessorOpus::processOutputData(void *outputBuffer, const unsigned int outputBufferByteSize, StreamData *userData) { unsigned int numberOfDecodedSamples; // -lengthEncodedPacketInBytes not correctly received, no variable for it // -outputBuffer isnt inputBuffer std::cout << userData->nBufferFrames << " [processOutput]nBufferFrames should be = " << lengthEncodedPacketWorkaround << " lengthEncodedPacket" << std::endl; std::cout << outputBufferByteSize << " [processOutput]outputBufferByteSize" << std::endl; std::cout << userData->maxBufferSize << " [processOutput]maxBufferSize" << std::endl; /* std::ofstream fileout3("outputBuffer-before-decoding.raw", std::ios::out | std::ios::binary); fileout3.write((char *)EncodedPacketPointer, lengthEncodedPacketWorkaround); fileout3.close(); */ //outputBufferByteSize should be in samples numberOfDecodedSamples = opus_decode(OpusDecoderObject, (unsigned char *)EncodedPacketPointer, lengthEncodedPacketWorkaround, (opus_int16 *)outputBuffer, userData->maxBufferSize, 0); std::cout << numberOfDecodedSamples << " [processOutput]numberOfDecodedSamples should be 960" << std::endl; return numberOfDecodedSamples; } ProcessorOpus::~ProcessorOpus() { opus_encoder_destroy(OpusEncoderObject); opus_decoder_destroy(OpusDecoderObject); }<commit_msg>Added alternative encoder/decoder Methode<commit_after>#include "ProcessorOpus.h" #include <fstream> //stream output to file ProcessorOpus::ProcessorOpus(std::string name, int opusApplication, int ErrorCode) : AudioProcessor(name) { //how to get audioData Object(SampleRate, ChannelNumber)? //Opus supports this sampleRates: 8000, 12000, 16000, 24000, or 48000. if (audioConfiguration.sampleRate == 8000 || audioConfiguration.sampleRate == 12000 || audioConfiguration.sampleRate == 16000 || audioConfiguration.sampleRate == 24000 || audioConfiguration.sampleRate == 48000) { this->sampleRate = audioConfiguration.sampleRate; } else { std::cout << "SampleRate not supported by Opus! Opus supports this sampleRates: 8000, 12000, 16000, 24000, or 48000." << std::endl; } //Opus supports mono(1 channel) and stereo(2 channels) only. if (audioConfiguration.inputDeviceChannels == 1 || audioConfiguration.inputDeviceChannels == 2) { this->channels = audioConfiguration.inputDeviceChannels; } else { std::cout << "Device Channels not supported by Opus! Opus supports 1 or 2 Device Channels" << std::endl; } // TODO: delete manuall selection of samplerate and channels OpusEncoderObject = opus_encoder_create(48000, 2, opusApplication, &ErrorCode); // TODO: delete manuall selection of samplerate and channels OpusDecoderObject = opus_decoder_create(48000, 2, &ErrorCode); } unsigned int ProcessorOpus::getSupportedAudioFormats() { return AudioConfiguration::AUDIO_FORMAT_SINT16; } unsigned int ProcessorOpus::getSupportedSampleRates() { //Opus supports this sampleRates: 8000, 12000, 16000, 24000, or 48000. = 1001111 binary in the format from configuration.h (every 1 stands for one supported format) = 79 decimal = 0x4F Hex unsigned int SupportedSampleRates = 79; return SupportedSampleRates; } unsigned char *EncodedPacketPointer = new unsigned char[4000]; unsigned int ProcessorOpus::processInputData(void *inputBuffer, const unsigned int inputBufferByteSize, StreamData *userData) { unsigned int lengthEncodedPacketInBytes; std::cout << userData->nBufferFrames << " [processInput]nBufferFrames should be 960" << std::endl; std::cout << userData->maxBufferSize << " [processInput]maxBufferSize" << std::endl; /* std::ofstream fileout("InputBuffer-before-encoding.raw", std::ios::out | std::ios::binary); fileout.write((char *)inputBuffer, userData->nBufferFrames); fileout.close(); */ lengthEncodedPacketInBytes = opus_encode(OpusEncoderObject, (opus_int16 *)inputBuffer, userData->nBufferFrames, (unsigned char *)EncodedPacketPointer, userData->maxBufferSize); //lengthEncodedPacketInBytes = opus_encode(OpusEncoderObject, (opus_int16 *)inputBuffer, userData->nBufferFrames, (unsigned char *)inputBuffer, userData->maxBufferSize); /* std::ofstream fileout2("InputBuffer-after-encoding.raw", std::ios::out | std::ios::binary); fileout2.write((char *)EncodedPacketPointer, lengthEncodedPacketInBytes); fileout2.close(); */ std::cout << lengthEncodedPacketInBytes << " [processInput]lengthEncodedPacket" << std::endl; lengthEncodedPacketWorkaround = lengthEncodedPacketInBytes; return lengthEncodedPacketInBytes; } unsigned int ProcessorOpus::processOutputData(void *outputBuffer, const unsigned int outputBufferByteSize, StreamData *userData) { unsigned int numberOfDecodedSamples; // -lengthEncodedPacketInBytes not correctly received, no variable for it // -outputBuffer isnt inputBuffer std::cout << userData->nBufferFrames << " [processOutput]nBufferFrames should be = " << lengthEncodedPacketWorkaround << " lengthEncodedPacket" << std::endl; std::cout << outputBufferByteSize << " [processOutput]outputBufferByteSize" << std::endl; std::cout << userData->maxBufferSize << " [processOutput]maxBufferSize" << std::endl; /* std::ofstream fileout3("outputBuffer-before-decoding.raw", std::ios::out | std::ios::binary); fileout3.write((char *)EncodedPacketPointer, lengthEncodedPacketWorkaround); fileout3.close(); */ //outputBufferByteSize should be in samples numberOfDecodedSamples = opus_decode(OpusDecoderObject, (unsigned char *)EncodedPacketPointer, lengthEncodedPacketWorkaround, (opus_int16 *)outputBuffer, userData->maxBufferSize, 0); //numberOfDecodedSamples = opus_decode(OpusDecoderObject, (unsigned char *)outputBuffer, userData->nBufferFrames, (opus_int16 *)outputBuffer, userData->maxBufferSize, 0); std::cout << numberOfDecodedSamples << " [processOutput]numberOfDecodedSamples should be 960" << std::endl; return numberOfDecodedSamples; } ProcessorOpus::~ProcessorOpus() { opus_encoder_destroy(OpusEncoderObject); opus_decoder_destroy(OpusDecoderObject); }<|endoftext|>
<commit_before>#include "pch.h" #include "WaitingLayer.h" #include "RoomScene.h" #define GET_CONNECT_LABEL dynamic_cast<Label*>(this->getChildByName("ConnectLabel")) bool WaitingLayer::init() { if (!LayerColor::initWithColor(Color4B::BLACK)) //검은색 세팅 { return false; } this->setOpacity(240); auto winSize = Director::getInstance()->getWinSize(); auto label = Label::create("다른 플레이어를 기다리는 중...", "Arial", 50); label->setPosition(Vec2(winSize.width/2, winSize.height/2)); this->addChild(label, 1, "ConnectLabel"); return true; } void WaitingLayer::GameStart() { auto winSize = Director::getInstance()->getWinSize(); auto label1 = GET_CONNECT_LABEL; if (label1 != nullptr) { label1->setString("게임을 시작합니다."); label1->setPositionY(winSize.height * 3 / 4); } auto label2 = Label::create("", "Arial", 100); label2->setPosition(Vec2(winSize.width / 2, winSize.height / 2)); this->addChild(label2); auto action0 = CallFunc::create(CC_CALLBACK_0(Label::setString, label2, "3")); auto action1 = DelayTime::create(1.0f); auto action2 = CallFunc::create(CC_CALLBACK_0(Label::setString, label2, "2")); auto action4 = CallFunc::create(CC_CALLBACK_0(Label::setString, label2, "1")); auto action6 = CallFunc::create(CC_CALLBACK_0(RoomScene::GameStartComplete, dynamic_cast<RoomScene*>(this->getParent()))); auto action = Sequence::create(action0, action1, action2, action1, action4, action1, action6, NULL); label2->runAction(action); } <commit_msg>[C] PlayAgain할 시에 WaitingLayer곂치는 문제 해결<commit_after>#include "pch.h" #include "WaitingLayer.h" #include "RoomScene.h" #define GET_CONNECT_LABEL dynamic_cast<Label*>(this->getChildByName("ConnectLabel")) #define GET_ROOM_SCENE dynamic_cast<RoomScene*>(this->getParent()) bool WaitingLayer::init() { if (!LayerColor::initWithColor(Color4B::BLACK)) //검은색 세팅 { return false; } this->setOpacity(240); auto winSize = Director::getInstance()->getWinSize(); auto label = Label::create("다른 플레이어를 기다리는 중...", "Arial", 50); label->setPosition(Vec2(winSize.width / 2, winSize.height * 3 / 4)); this->addChild(label, 1, "ConnectLabel"); return true; } void WaitingLayer::GameStart() { auto winSize = Director::getInstance()->getWinSize(); auto label1 = GET_CONNECT_LABEL; if (label1 != nullptr) { label1->setString("게임을 시작합니다."); label1->setPositionY(winSize.height * 3 / 4); } auto label2 = Label::create("", "Arial", 100); label2->setPosition(Vec2(winSize.width / 2, winSize.height / 2)); this->addChild(label2); auto action0 = CallFunc::create(CC_CALLBACK_0(Label::setString, label2, "3")); auto action1 = DelayTime::create(1.0f); auto action2 = CallFunc::create(CC_CALLBACK_0(Label::setString, label2, "2")); auto action3 = CallFunc::create(CC_CALLBACK_0(Label::setString, label2, "1")); auto action4 = CallFunc::create(CC_CALLBACK_0(RoomScene::GameStartComplete, GET_ROOM_SCENE)); auto action5 = CallFunc::create(CC_CALLBACK_0(Label::setString, label1, "다른 플레이어를 기다리는 중...")); auto action6 = CallFunc::create(CC_CALLBACK_0(Label::setString, label2, " ")); auto action = Sequence::create(action0, action1, action2, action1, action3, action1, action4, action5, action6, NULL); label2->runAction(action); } <|endoftext|>
<commit_before>//===- ScalarEvolutionNormalization.cpp - See below -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements utilities for working with "normalized" expressions. // See the comments at the top of ScalarEvolutionNormalization.h for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/Analysis/ScalarEvolutionNormalization.h" using namespace llvm; namespace { /// TransformKind - Different types of transformations that /// TransformForPostIncUse can do. enum TransformKind { /// Normalize - Normalize according to the given loops. Normalize, /// Denormalize - Perform the inverse transform on the expression with the /// given loop set. Denormalize }; /// Hold the state used during post-inc expression transformation, including a /// map of transformed expressions. class PostIncTransform { TransformKind Kind; Optional<NormalizePredTy> Pred; const PostIncLoopSet &Loops; ScalarEvolution &SE; DenseMap<const SCEV*, const SCEV*> Transformed; public: PostIncTransform(TransformKind kind, Optional<NormalizePredTy> Pred, const PostIncLoopSet &loops, ScalarEvolution &se) : Kind(kind), Pred(Pred), Loops(loops), SE(se) {} const SCEV *TransformSubExpr(const SCEV *S); protected: const SCEV *TransformImpl(const SCEV *S); }; } // namespace /// Implement post-inc transformation for all valid expression types. const SCEV *PostIncTransform::TransformImpl(const SCEV *S) { if (const SCEVCastExpr *X = dyn_cast<SCEVCastExpr>(S)) { const SCEV *O = X->getOperand(); const SCEV *N = TransformSubExpr(O); if (O != N) switch (S->getSCEVType()) { case scZeroExtend: return SE.getZeroExtendExpr(N, S->getType()); case scSignExtend: return SE.getSignExtendExpr(N, S->getType()); case scTruncate: return SE.getTruncateExpr(N, S->getType()); default: llvm_unreachable("Unexpected SCEVCastExpr kind!"); } return S; } if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { // An addrec. This is the interesting part. SmallVector<const SCEV *, 8> Operands; const Loop *L = AR->getLoop(); transform(AR->operands(), std::back_inserter(Operands), [&](const SCEV *Op) { return TransformSubExpr(Op); }); // Conservatively use AnyWrap until/unless we need FlagNW. const SCEV *Result = SE.getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); switch (Kind) { case Normalize: // We want to normalize step expression, because otherwise we might not be // able to denormalize to the original expression. // // Here is an example what will happen if we don't normalize step: // ORIGINAL ISE: // {(100 /u {1,+,1}<%bb16>),+,(100 /u {1,+,1}<%bb16>)}<%bb25> // NORMALIZED ISE: // {((-1 * (100 /u {1,+,1}<%bb16>)) + (100 /u {0,+,1}<%bb16>)),+, // (100 /u {0,+,1}<%bb16>)}<%bb25> // DENORMALIZED BACK ISE: // {((2 * (100 /u {1,+,1}<%bb16>)) + (-1 * (100 /u {2,+,1}<%bb16>))),+, // (100 /u {1,+,1}<%bb16>)}<%bb25> // Note that the initial value changes after normalization + // denormalization, which isn't correct. if ((Pred && (*Pred)(AR)) || (!Pred && Loops.count(L))) { const SCEV *TransformedStep = TransformSubExpr(AR->getStepRecurrence(SE)); Result = SE.getMinusSCEV(Result, TransformedStep); } #if 0 // See the comment on the assert above. assert(S == TransformSubExpr(Result, User, OperandValToReplace) && "SCEV normalization is not invertible!"); #endif break; case Denormalize: // Here we want to normalize step expressions for the same reasons, as // stated above. if (Loops.count(L)) { const SCEV *TransformedStep = TransformSubExpr(AR->getStepRecurrence(SE)); Result = SE.getAddExpr(Result, TransformedStep); } break; } return Result; } if (const SCEVNAryExpr *X = dyn_cast<SCEVNAryExpr>(S)) { SmallVector<const SCEV *, 8> Operands; bool Changed = false; // Transform each operand. for (SCEVNAryExpr::op_iterator I = X->op_begin(), E = X->op_end(); I != E; ++I) { const SCEV *O = *I; const SCEV *N = TransformSubExpr(O); Changed |= N != O; Operands.push_back(N); } // If any operand actually changed, return a transformed result. if (Changed) switch (S->getSCEVType()) { case scAddExpr: return SE.getAddExpr(Operands); case scMulExpr: return SE.getMulExpr(Operands); case scSMaxExpr: return SE.getSMaxExpr(Operands); case scUMaxExpr: return SE.getUMaxExpr(Operands); default: llvm_unreachable("Unexpected SCEVNAryExpr kind!"); } return S; } if (const SCEVUDivExpr *X = dyn_cast<SCEVUDivExpr>(S)) { const SCEV *LO = X->getLHS(); const SCEV *RO = X->getRHS(); const SCEV *LN = TransformSubExpr(LO); const SCEV *RN = TransformSubExpr(RO); if (LO != LN || RO != RN) return SE.getUDivExpr(LN, RN); return S; } llvm_unreachable("Unexpected SCEV kind!"); } /// Manage recursive transformation across an expression DAG. Revisiting /// expressions would lead to exponential recursion. const SCEV *PostIncTransform::TransformSubExpr(const SCEV *S) { if (isa<SCEVConstant>(S) || isa<SCEVUnknown>(S)) return S; const SCEV *Result = Transformed.lookup(S); if (Result) return Result; Result = TransformImpl(S); Transformed[S] = Result; return Result; } /// Top level driver for transforming an expression DAG into its requested /// post-inc form (either "Normalized" or "Denormalized"). static const SCEV *TransformForPostIncUse(TransformKind Kind, const SCEV *S, Optional<NormalizePredTy> Pred, const PostIncLoopSet &Loops, ScalarEvolution &SE) { PostIncTransform Transform(Kind, Pred, Loops, SE); return Transform.TransformSubExpr(S); } const SCEV *llvm::normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE) { return TransformForPostIncUse(Normalize, S, None, Loops, SE); } const SCEV *llvm::normalizeForPostIncUseIf(const SCEV *S, NormalizePredTy Pred, ScalarEvolution &SE) { PostIncLoopSet Empty; return TransformForPostIncUse(Normalize, S, Pred, Empty, SE); } const SCEV *llvm::denormalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE) { return TransformForPostIncUse(Denormalize, S, None, Loops, SE); } <commit_msg>Simplify PostIncTransform further; NFC<commit_after>//===- ScalarEvolutionNormalization.cpp - See below -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements utilities for working with "normalized" expressions. // See the comments at the top of ScalarEvolutionNormalization.h for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/Analysis/ScalarEvolutionNormalization.h" using namespace llvm; namespace { /// TransformKind - Different types of transformations that /// TransformForPostIncUse can do. enum TransformKind { /// Normalize - Normalize according to the given loops. Normalize, /// Denormalize - Perform the inverse transform on the expression with the /// given loop set. Denormalize }; /// Hold the state used during post-inc expression transformation, including a /// map of transformed expressions. class PostIncTransform { TransformKind Kind; NormalizePredTy Pred; ScalarEvolution &SE; DenseMap<const SCEV*, const SCEV*> Transformed; public: PostIncTransform(TransformKind kind, NormalizePredTy Pred, ScalarEvolution &se) : Kind(kind), Pred(Pred), SE(se) {} const SCEV *TransformSubExpr(const SCEV *S); protected: const SCEV *TransformImpl(const SCEV *S); }; } // namespace /// Implement post-inc transformation for all valid expression types. const SCEV *PostIncTransform::TransformImpl(const SCEV *S) { if (const SCEVCastExpr *X = dyn_cast<SCEVCastExpr>(S)) { const SCEV *O = X->getOperand(); const SCEV *N = TransformSubExpr(O); if (O != N) switch (S->getSCEVType()) { case scZeroExtend: return SE.getZeroExtendExpr(N, S->getType()); case scSignExtend: return SE.getSignExtendExpr(N, S->getType()); case scTruncate: return SE.getTruncateExpr(N, S->getType()); default: llvm_unreachable("Unexpected SCEVCastExpr kind!"); } return S; } if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { // An addrec. This is the interesting part. SmallVector<const SCEV *, 8> Operands; transform(AR->operands(), std::back_inserter(Operands), [&](const SCEV *Op) { return TransformSubExpr(Op); }); // Conservatively use AnyWrap until/unless we need FlagNW. const SCEV *Result = SE.getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagAnyWrap); switch (Kind) { case Normalize: // We want to normalize step expression, because otherwise we might not be // able to denormalize to the original expression. // // Here is an example what will happen if we don't normalize step: // ORIGINAL ISE: // {(100 /u {1,+,1}<%bb16>),+,(100 /u {1,+,1}<%bb16>)}<%bb25> // NORMALIZED ISE: // {((-1 * (100 /u {1,+,1}<%bb16>)) + (100 /u {0,+,1}<%bb16>)),+, // (100 /u {0,+,1}<%bb16>)}<%bb25> // DENORMALIZED BACK ISE: // {((2 * (100 /u {1,+,1}<%bb16>)) + (-1 * (100 /u {2,+,1}<%bb16>))),+, // (100 /u {1,+,1}<%bb16>)}<%bb25> // Note that the initial value changes after normalization + // denormalization, which isn't correct. if (Pred(AR)) { const SCEV *TransformedStep = TransformSubExpr(AR->getStepRecurrence(SE)); Result = SE.getMinusSCEV(Result, TransformedStep); } #if 0 // See the comment on the assert above. assert(S == TransformSubExpr(Result, User, OperandValToReplace) && "SCEV normalization is not invertible!"); #endif break; case Denormalize: // Here we want to normalize step expressions for the same reasons, as // stated above. if (Pred(AR)) { const SCEV *TransformedStep = TransformSubExpr(AR->getStepRecurrence(SE)); Result = SE.getAddExpr(Result, TransformedStep); } break; } return Result; } if (const SCEVNAryExpr *X = dyn_cast<SCEVNAryExpr>(S)) { SmallVector<const SCEV *, 8> Operands; bool Changed = false; // Transform each operand. for (SCEVNAryExpr::op_iterator I = X->op_begin(), E = X->op_end(); I != E; ++I) { const SCEV *O = *I; const SCEV *N = TransformSubExpr(O); Changed |= N != O; Operands.push_back(N); } // If any operand actually changed, return a transformed result. if (Changed) switch (S->getSCEVType()) { case scAddExpr: return SE.getAddExpr(Operands); case scMulExpr: return SE.getMulExpr(Operands); case scSMaxExpr: return SE.getSMaxExpr(Operands); case scUMaxExpr: return SE.getUMaxExpr(Operands); default: llvm_unreachable("Unexpected SCEVNAryExpr kind!"); } return S; } if (const SCEVUDivExpr *X = dyn_cast<SCEVUDivExpr>(S)) { const SCEV *LO = X->getLHS(); const SCEV *RO = X->getRHS(); const SCEV *LN = TransformSubExpr(LO); const SCEV *RN = TransformSubExpr(RO); if (LO != LN || RO != RN) return SE.getUDivExpr(LN, RN); return S; } llvm_unreachable("Unexpected SCEV kind!"); } /// Manage recursive transformation across an expression DAG. Revisiting /// expressions would lead to exponential recursion. const SCEV *PostIncTransform::TransformSubExpr(const SCEV *S) { if (isa<SCEVConstant>(S) || isa<SCEVUnknown>(S)) return S; const SCEV *Result = Transformed.lookup(S); if (Result) return Result; Result = TransformImpl(S); Transformed[S] = Result; return Result; } /// Top level driver for transforming an expression DAG into its requested /// post-inc form (either "Normalized" or "Denormalized"). static const SCEV *TransformForPostIncUse(TransformKind Kind, const SCEV *S, NormalizePredTy Pred, ScalarEvolution &SE) { PostIncTransform Transform(Kind, Pred, SE); return Transform.TransformSubExpr(S); } const SCEV *llvm::normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE) { auto Pred = [&](const SCEVAddRecExpr *AR) { return Loops.count(AR->getLoop()); }; return TransformForPostIncUse(Normalize, S, Pred, SE); } const SCEV *llvm::normalizeForPostIncUseIf(const SCEV *S, NormalizePredTy Pred, ScalarEvolution &SE) { return TransformForPostIncUse(Normalize, S, Pred, SE); } const SCEV *llvm::denormalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE) { auto Pred = [&](const SCEVAddRecExpr *AR) { return Loops.count(AR->getLoop()); }; return TransformForPostIncUse(Denormalize, S, Pred, SE); } <|endoftext|>
<commit_before>#ifndef BARE_ALLOC_HPP #define BARE_ALLOC_HPP #include "bare_memory.hpp" namespace bare { template<class T> class allocator { public: typedef T value_type; typedef T* pointer; allocator(memory_block& blk) : block(&blk) {} pointer allocate(size_t n) { } protected: memory_block* block; }; }; #endif <commit_msg>bare::allocator wip<commit_after>#ifndef BARE_ALLOC_HPP #define BARE_ALLOC_HPP #include <cassert> #include <bitset> #include "bare_memory.hpp" namespace bare { /** * It implements the Allocator concept over * ExAllocatePoolWithTag. * * Unlike STL it do not throws but returns nullptr instead. * It also uses tag to find memory leaks easily. */ template< class T, std::uint32_t blk_size_bytes = 1ULL << 10 > class allocator { public: typedef T value_type; typedef T* pointer; typedef decltype(blk_size_bytes) size_type; typedef std::uint32_t tag_type; template<class U> struct rebind { typedef allocator<U, pool_type> other; }; tag_type tag; allocator(tag_type a_tag) : tag(a_tag) {} template<class U> allocator(const allocator<U>& o) : tag(o.tag) {} //! Allocates n * sizeof(T) bytes //! If it fails thows std::bad_alloc. pointer allocate(size_type n) { assert(n > 0); //NB sizeof(T) > 0 for any T assert(2 ** 32 / sizeof(T) > n); return (pointer) ExAllocatePoolWithTag (pool_type, n * sizeof(T), tag); } //! Deallocates the storage referenced by the pointer p, //! which must be a pointer obtained by an earlier call //! to allocate(). Uses ExFreePoolWithTag. //! Prereq: IRQL <= DISPATCH_LEVEL, see ExFreePoolWithTag. //! @param n is not used, //! its just for compatibility with the Allocator concept. void deallocate(pointer p, size_type size) { ASSERT(p); ASSERT(size == sizeof(T)); if (is_paged<pool_type>::value) PAGED_CODE(); ExFreePoolWithTag(p, tag); } //! Constructs an object of type T //! in allocated uninitialized storage pointed to by p, //! using placement-new //! @param args are constructor argumets template<class U, class... Args> void construct(U* p, Args&&... args) { ASSERT(p != nullptr); if (is_paged<pool_type>::value) PAGED_CODE(); ::new((void*)p) U(forward<Args>(args)...); } //! Calls the destructor of the object pointed to by p template<class U> void destroy(U* p) { ASSERT(p != nullptr); if (is_paged<pool_type>::value) PAGED_CODE(); static_assert (!__has_virtual_destructor(U), "the argument of pool::allocator::destroy(U*) " "must not have a virtual destructor"); p->U::~U(); } protected: static constexpr size_type storage_size_bytes = blk_size_bytes; static constexpr std::uint8_t word_size_bytes = 8; static constexpr size_type element_size_words = std::min(1, sizeof(T) / min_cell_size_bytes); static constexpr std::uint8_t cell_size_bytes = element_size_words * word_size_bytes; static constexpr size_type storage_size_cells = storage_size_bytes / (element_size_words * words_size_bytes); // 0 is free cell, 1 is used cell std::bitset<storage_size_cells> map; memory_block<T, storage_size_bytes / sizeof(T)>* storage; }; } // bare #endif <|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <sstream> // StdAir #include <stdair/basic/BasConst_BookingClass.hpp> #include <stdair/basic/BasConst_Inventory.hpp> #include <stdair/bom/LegCabin.hpp> namespace stdair { // //////////////////////////////////////////////////////////////////// LegCabin::LegCabin() : _key (DEFAULT_CABIN_CODE), _parent (NULL) { assert (false); } // //////////////////////////////////////////////////////////////////// LegCabin::LegCabin (const LegCabin&) : _key (DEFAULT_CABIN_CODE), _parent (NULL) { assert (false); } // //////////////////////////////////////////////////////////////////// LegCabin::LegCabin (const Key_T& iKey) : _key (iKey), _parent (NULL), _offeredCapacity (DEFAULT_CABIN_CAPACITY), _physicalCapacity (DEFAULT_CABIN_CAPACITY), _soldSeat (DEFAULT_CLASS_NB_OF_BOOKINGS), _committedSpace (DEFAULT_COMMITTED_SPACE), _availabilityPool (DEFAULT_AVAILABILITY), _availability (DEFAULT_AVAILABILITY), _bidPriceVector (DEFAULT_BID_PRICE_VECTOR), _currentBidPrice (DEFAULT_BID_PRICE) { } // //////////////////////////////////////////////////////////////////// LegCabin::~LegCabin() { } // //////////////////////////////////////////////////////////////////// std::string LegCabin::toString() const { std::ostringstream oStr; oStr << describeKey(); return oStr.str(); } // //////////////////////////////////////////////////////////////////// void LegCabin::updateFromReservation (const NbOfBookings_T& iNbOfBookings) { _committedSpace += iNbOfBookings; _availabilityPool = _offeredCapacity - _committedSpace; } } <commit_msg>[StdAir][Dev] Fixed a compilation warning.<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <sstream> // StdAir #include <stdair/basic/BasConst_BookingClass.hpp> #include <stdair/basic/BasConst_Inventory.hpp> #include <stdair/bom/LegCabin.hpp> namespace stdair { // //////////////////////////////////////////////////////////////////// LegCabin::LegCabin() : _key (DEFAULT_CABIN_CODE), _parent (NULL) { assert (false); } // //////////////////////////////////////////////////////////////////// LegCabin::LegCabin (const LegCabin&) : _key (DEFAULT_CABIN_CODE), _parent (NULL) { assert (false); } // //////////////////////////////////////////////////////////////////// LegCabin::LegCabin (const Key_T& iKey) : _key (iKey), _parent (NULL), _offeredCapacity (DEFAULT_CABIN_CAPACITY), _physicalCapacity (DEFAULT_CABIN_CAPACITY), _soldSeat (DEFAULT_CLASS_NB_OF_BOOKINGS), _committedSpace (DEFAULT_COMMITTED_SPACE), _availabilityPool (DEFAULT_AVAILABILITY), _availability (DEFAULT_AVAILABILITY), _currentBidPrice (DEFAULT_BID_PRICE), _bidPriceVector (DEFAULT_BID_PRICE_VECTOR) { } // //////////////////////////////////////////////////////////////////// LegCabin::~LegCabin() { } // //////////////////////////////////////////////////////////////////// std::string LegCabin::toString() const { std::ostringstream oStr; oStr << describeKey(); return oStr.str(); } // //////////////////////////////////////////////////////////////////// void LegCabin::updateFromReservation (const NbOfBookings_T& iNbOfBookings) { _committedSpace += iNbOfBookings; _availabilityPool = _offeredCapacity - _committedSpace; } } <|endoftext|>
<commit_before>/* * Smithsonian Astrophysical Observatory, Cambridge, MA, USA * This code has been modified under the terms listed below and is made * available under the same terms. */ /* * Copyright 1991-2004 George A Howlett. * * 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 <tk.h> extern "C" { Tcl_AppInitProc Tkblt_Init; Tcl_AppInitProc Tkblt_SafeInit; }; Tcl_AppInitProc Blt_VectorCmdInitProc; Tcl_AppInitProc Blt_GraphCmdInitProc; int Tkblt_Init(Tcl_Interp* interp) { Tcl_Namespace *nsPtr; if (Tcl_InitStubs(interp, TCL_PATCH_LEVEL, 0) == NULL) return TCL_ERROR; if (Tk_InitStubs(interp, TK_PATCH_LEVEL, 0) == NULL) return TCL_ERROR; nsPtr = Tcl_FindNamespace(interp, "::blt", (Tcl_Namespace *)NULL, 0); if (nsPtr == NULL) { nsPtr = Tcl_CreateNamespace(interp, "::blt", NULL, NULL); if (nsPtr == NULL) return TCL_ERROR; } if (Blt_VectorCmdInitProc(interp) != TCL_OK) return TCL_ERROR; if (Blt_GraphCmdInitProc(interp) != TCL_OK) return TCL_ERROR; if (Tcl_PkgProvide(interp, PACKAGE_NAME, PACKAGE_VERSION) != TCL_OK) return TCL_ERROR; return TCL_OK; } int Tkblt_SafeInit(Tcl_Interp* interp) { return Tkblt_Init(interp); } <commit_msg>*** empty log message ***<commit_after>/* * Smithsonian Astrophysical Observatory, Cambridge, MA, USA * This code has been modified under the terms listed below and is made * available under the same terms. */ /* * Copyright 1991-2004 George A Howlett. * * 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 <tk.h> #include <iostream> using namespace std; extern "C" { Tcl_AppInitProc Tkblt_Init; Tcl_AppInitProc Tkblt_SafeInit; }; Tcl_AppInitProc Blt_VectorCmdInitProc; Tcl_AppInitProc Blt_GraphCmdInitProc; int Tkblt_Init(Tcl_Interp* interp) { Tcl_Namespace *nsPtr; if (Tcl_InitStubs(interp, TCL_PATCH_LEVEL, 0) == NULL) return TCL_ERROR; if (Tk_InitStubs(interp, TK_PATCH_LEVEL, 0) == NULL) return TCL_ERROR; nsPtr = Tcl_FindNamespace(interp, "::blt", (Tcl_Namespace *)NULL, 0); if (nsPtr == NULL) { nsPtr = Tcl_CreateNamespace(interp, "::blt", NULL, NULL); if (nsPtr == NULL) return TCL_ERROR; } if (Blt_VectorCmdInitProc(interp) != TCL_OK) return TCL_ERROR; if (Blt_GraphCmdInitProc(interp) != TCL_OK) return TCL_ERROR; if (Tcl_PkgProvide(interp, PACKAGE_NAME, PACKAGE_VERSION) != TCL_OK) return TCL_ERROR; return TCL_OK; } int Tkblt_SafeInit(Tcl_Interp* interp) { return Tkblt_Init(interp); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008, 2010 Apple Inc. All Rights Reserved. * Copyright (C) 2009 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "core/workers/Worker.h" #include "bindings/core/v8/ExceptionState.h" #include "core/dom/Document.h" #include "core/events/MessageEvent.h" #include "core/fetch/ResourceFetcher.h" #include "core/inspector/InspectorInstrumentation.h" #include "core/frame/LocalDOMWindow.h" #include "core/frame/UseCounter.h" #include "core/workers/WorkerGlobalScopeProxy.h" #include "core/workers/WorkerGlobalScopeProxyProvider.h" #include "core/workers/WorkerScriptLoader.h" #include "core/workers/WorkerThread.h" #include "wtf/MainThread.h" namespace WebCore { inline Worker::Worker(ExecutionContext* context) : AbstractWorker(context) , m_contextProxy(0) { ScriptWrappable::init(this); } PassRefPtrWillBeRawPtr<Worker> Worker::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState) { ASSERT(isMainThread()); Document* document = toDocument(context); UseCounter::count(context, UseCounter::WorkerStart); if (!document->page()) { exceptionState.throwDOMException(InvalidAccessError, "The context provided is invalid."); return nullptr; } WorkerGlobalScopeProxyProvider* proxyProvider = WorkerGlobalScopeProxyProvider::from(*document->page()); ASSERT(proxyProvider); RefPtrWillBeRawPtr<Worker> worker = adoptRefWillBeRefCountedGarbageCollected(new Worker(context)); worker->suspendIfNeeded(); KURL scriptURL = worker->resolveURL(url, exceptionState); if (scriptURL.isEmpty()) return nullptr; // The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners. worker->setPendingActivity(worker.get()); worker->m_scriptLoader = WorkerScriptLoader::create(); worker->m_scriptLoader->loadAsynchronously(*context, scriptURL, DenyCrossOriginRequests, worker.get()); worker->m_contextProxy = proxyProvider->createWorkerGlobalScopeProxy(worker.get()); return worker.release(); } Worker::~Worker() { ASSERT(isMainThread()); if (!m_contextProxy) return; ASSERT(executionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists. m_contextProxy->workerObjectDestroyed(); } const AtomicString& Worker::interfaceName() const { return EventTargetNames::Worker; } void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState) { ASSERT(m_contextProxy); // Disentangle the port in preparation for sending it to the remote context. OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState); if (exceptionState.hadException()) return; m_contextProxy->postMessageToWorkerGlobalScope(message, channels.release()); } void Worker::terminate() { if (m_contextProxy) m_contextProxy->terminateWorkerGlobalScope(); } void Worker::stop() { terminate(); } bool Worker::hasPendingActivity() const { return (m_contextProxy && m_contextProxy->hasPendingActivity()) || ActiveDOMObject::hasPendingActivity(); } void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse&) { InspectorInstrumentation::didReceiveScriptResponse(executionContext(), identifier); } void Worker::notifyFinished() { if (m_scriptLoader->failed()) { dispatchEvent(Event::createCancelable(EventTypeNames::error)); } else { ASSERT(m_contextProxy); WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart; if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(executionContext())) startMode = PauseWorkerGlobalScopeOnStart; m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), executionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode); InspectorInstrumentation::scriptImported(executionContext(), m_scriptLoader->identifier(), m_scriptLoader->script()); } m_scriptLoader = nullptr; unsetPendingActivity(this); } void Worker::trace(Visitor* visitor) { AbstractWorker::trace(visitor); } } // namespace WebCore <commit_msg>Worker should not use deprecated {,un}setPendingActivity<commit_after>/* * Copyright (C) 2008, 2010 Apple Inc. All Rights Reserved. * Copyright (C) 2009 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "core/workers/Worker.h" #include "bindings/core/v8/ExceptionState.h" #include "core/dom/Document.h" #include "core/events/MessageEvent.h" #include "core/fetch/ResourceFetcher.h" #include "core/inspector/InspectorInstrumentation.h" #include "core/frame/LocalDOMWindow.h" #include "core/frame/UseCounter.h" #include "core/workers/WorkerGlobalScopeProxy.h" #include "core/workers/WorkerGlobalScopeProxyProvider.h" #include "core/workers/WorkerScriptLoader.h" #include "core/workers/WorkerThread.h" #include "wtf/MainThread.h" namespace WebCore { inline Worker::Worker(ExecutionContext* context) : AbstractWorker(context) , m_contextProxy(0) { ScriptWrappable::init(this); } PassRefPtrWillBeRawPtr<Worker> Worker::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState) { ASSERT(isMainThread()); Document* document = toDocument(context); UseCounter::count(context, UseCounter::WorkerStart); if (!document->page()) { exceptionState.throwDOMException(InvalidAccessError, "The context provided is invalid."); return nullptr; } WorkerGlobalScopeProxyProvider* proxyProvider = WorkerGlobalScopeProxyProvider::from(*document->page()); ASSERT(proxyProvider); RefPtrWillBeRawPtr<Worker> worker = adoptRefWillBeRefCountedGarbageCollected(new Worker(context)); worker->suspendIfNeeded(); KURL scriptURL = worker->resolveURL(url, exceptionState); if (scriptURL.isEmpty()) return nullptr; worker->m_scriptLoader = WorkerScriptLoader::create(); worker->m_scriptLoader->loadAsynchronously(*context, scriptURL, DenyCrossOriginRequests, worker.get()); worker->m_contextProxy = proxyProvider->createWorkerGlobalScopeProxy(worker.get()); return worker.release(); } Worker::~Worker() { ASSERT(isMainThread()); if (!m_contextProxy) return; ASSERT(executionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists. m_contextProxy->workerObjectDestroyed(); } const AtomicString& Worker::interfaceName() const { return EventTargetNames::Worker; } void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState) { ASSERT(m_contextProxy); // Disentangle the port in preparation for sending it to the remote context. OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState); if (exceptionState.hadException()) return; m_contextProxy->postMessageToWorkerGlobalScope(message, channels.release()); } void Worker::terminate() { if (m_contextProxy) m_contextProxy->terminateWorkerGlobalScope(); } void Worker::stop() { terminate(); } bool Worker::hasPendingActivity() const { // The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners. return (m_contextProxy && m_contextProxy->hasPendingActivity()) || m_scriptLoader; } void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse&) { InspectorInstrumentation::didReceiveScriptResponse(executionContext(), identifier); } void Worker::notifyFinished() { if (m_scriptLoader->failed()) { dispatchEvent(Event::createCancelable(EventTypeNames::error)); } else { ASSERT(m_contextProxy); WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart; if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(executionContext())) startMode = PauseWorkerGlobalScopeOnStart; m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), executionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode); InspectorInstrumentation::scriptImported(executionContext(), m_scriptLoader->identifier(), m_scriptLoader->script()); } m_scriptLoader = nullptr; } void Worker::trace(Visitor* visitor) { AbstractWorker::trace(visitor); } } // namespace WebCore <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include "highlevel_feature_extractor.h" #include <rcsc/common/server_param.h> #include "agent.h" using namespace rcsc; HighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates, int num_opponents, bool playing_offense) : FeatureExtractor(num_teammates, num_opponents, playing_offense) { assert(numTeammates >= 0); assert(numOpponents >= 0); numFeatures = num_basic_features + features_per_teammate * numTeammates + features_per_opponent * numOpponents; numFeatures++; // action status feature_vec.resize(numFeatures); } HighLevelFeatureExtractor::~HighLevelFeatureExtractor() {} const std::vector<float>& HighLevelFeatureExtractor::ExtractFeatures(const rcsc::WorldModel& wm, bool last_action_status) { featIndx = 0; const ServerParam& SP = ServerParam::i(); const SelfObject& self = wm.self(); const Vector2D& self_pos = self.pos(); const float self_ang = self.body().radian(); const PlayerCont& teammates = wm.teammates(); const PlayerCont& opponents = wm.opponents(); float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength() + SP.pitchHalfWidth() * SP.pitchHalfWidth()); // features about self pos // Allow the agent to go 10% over the playfield in any direction float tolerance_x = .1 * SP.pitchHalfLength(); float tolerance_y = .1 * SP.pitchHalfWidth(); // should this be SP.pitchWidth()? // Feature[0]: X-postion if (playingOffense) { addNormFeature(self_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x); } else { addNormFeature(self_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x); } // Feature[1]: Y-Position addNormFeature(self_pos.y, -SP.pitchHalfWidth() - tolerance_y, SP.pitchHalfWidth() + tolerance_y); // Feature[2]: Self Angle addNormFeature(self_ang, -M_PI, M_PI); float r; float th; // Features about the ball Vector2D ball_pos = wm.ball().pos(); angleDistToPoint(self_pos, ball_pos, th, r); // Feature[3] and [4]: (x,y) postition of the ball if (playingOffense) { addNormFeature(ball_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x); } else { addNormFeature(ball_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x); } addNormFeature(ball_pos.y, -SP.pitchHalfWidth() - tolerance_y, SP.pitchHalfWidth() + tolerance_y); // Feature[5]: Able to kick addNormFeature(self.isKickable(), false, true); // Features about distance to goal center Vector2D goalCenter(SP.pitchHalfLength(), 0); if (!playingOffense) { goalCenter.assign(-SP.pitchHalfLength(), 0); } angleDistToPoint(self_pos, goalCenter, th, r); // Feature[6]: Goal Center Distance addNormFeature(r, 0, maxR); // Feature[7]: Angle to goal center addNormFeature(th, -M_PI, M_PI); // Feature[8]: largest open goal angle addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI); // Feature[9]: Dist to our closest opp if (numOpponents > 0) { calcClosestOpp(wm, self_pos, th, r); addNormFeature(r, 0, maxR); } else { addFeature(FEAT_INVALID); } // Features[9 - 9+T]: teammate's open angle to goal int detected_teammates = 0; for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) { const PlayerObject& teammate = *it; if (valid(teammate) && detected_teammates < numTeammates) { addNormFeature(calcLargestGoalAngle(wm, teammate.pos()), 0, M_PI); detected_teammates++; } } // Add zero features for any missing teammates for (int i=detected_teammates; i<numTeammates; ++i) { addFeature(FEAT_INVALID); } // Features[9+T - 9+2T]: teammates' dists to closest opps if (numOpponents > 0) { detected_teammates = 0; for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) { const PlayerObject& teammate = *it; if (valid(teammate) && detected_teammates < numTeammates) { calcClosestOpp(wm, teammate.pos(), th, r); addNormFeature(r, 0, maxR); detected_teammates++; } } // Add zero features for any missing teammates for (int i=detected_teammates; i<numTeammates; ++i) { addFeature(FEAT_INVALID); } } else { // If no opponents, add invalid features for (int i=0; i<numTeammates; ++i) { addFeature(FEAT_INVALID); } } // Features [9+2T - 9+3T]: open angle to teammates detected_teammates = 0; for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) { const PlayerObject& teammate = *it; if (valid(teammate) && detected_teammates < numTeammates) { addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate.pos()),0,M_PI); detected_teammates++; } } // Add zero features for any missing teammates for (int i=detected_teammates; i<numTeammates; ++i) { addFeature(FEAT_INVALID); } // Features [9+3T - 9+6T]: x, y, unum of teammates detected_teammates = 0; for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) { const PlayerObject& teammate = *it; if (valid(teammate) && detected_teammates < numTeammates) { if (playingOffense) { addNormFeature(teammate.pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x); } else { addNormFeature(teammate.pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x); } addNormFeature(teammate.pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y); addFeature(teammate.unum()); detected_teammates++; } } // Add zero features for any missing teammates for (int i=detected_teammates; i<numTeammates; ++i) { addFeature(FEAT_INVALID); addFeature(FEAT_INVALID); addFeature(FEAT_INVALID); } // Features [9+6T - 9+6T+3O]: x, y, unum of opponents int detected_opponents = 0; for (PlayerCont::const_iterator it = opponents.begin(); it != opponents.end(); ++it) { const PlayerObject& opponent = *it; if (valid(opponent) && detected_opponents < numOpponents) { if (playingOffense) { addNormFeature(opponent.pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x); } else { addNormFeature(opponent.pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x); } addNormFeature(opponent.pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y); addFeature(opponent.unum()); detected_opponents++; } } // Add zero features for any missing opponents for (int i=detected_opponents; i<numOpponents; ++i) { addFeature(FEAT_INVALID); addFeature(FEAT_INVALID); addFeature(FEAT_INVALID); } if (last_action_status) { addFeature(FEAT_MAX); } else { addFeature(FEAT_MIN); } assert(featIndx == numFeatures); // checkFeatures(); return feature_vec; } <commit_msg>Remove question comment<commit_after>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include "highlevel_feature_extractor.h" #include <rcsc/common/server_param.h> #include "agent.h" using namespace rcsc; HighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates, int num_opponents, bool playing_offense) : FeatureExtractor(num_teammates, num_opponents, playing_offense) { assert(numTeammates >= 0); assert(numOpponents >= 0); numFeatures = num_basic_features + features_per_teammate * numTeammates + features_per_opponent * numOpponents; numFeatures++; // action status feature_vec.resize(numFeatures); } HighLevelFeatureExtractor::~HighLevelFeatureExtractor() {} const std::vector<float>& HighLevelFeatureExtractor::ExtractFeatures(const rcsc::WorldModel& wm, bool last_action_status) { featIndx = 0; const ServerParam& SP = ServerParam::i(); const SelfObject& self = wm.self(); const Vector2D& self_pos = self.pos(); const float self_ang = self.body().radian(); const PlayerCont& teammates = wm.teammates(); const PlayerCont& opponents = wm.opponents(); float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength() + SP.pitchHalfWidth() * SP.pitchHalfWidth()); // features about self pos // Allow the agent to go 10% over the playfield in any direction float tolerance_x = .1 * SP.pitchHalfLength(); float tolerance_y = .1 * SP.pitchHalfWidth(); // Feature[0]: X-postion if (playingOffense) { addNormFeature(self_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x); } else { addNormFeature(self_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x); } // Feature[1]: Y-Position addNormFeature(self_pos.y, -SP.pitchHalfWidth() - tolerance_y, SP.pitchHalfWidth() + tolerance_y); // Feature[2]: Self Angle addNormFeature(self_ang, -M_PI, M_PI); float r; float th; // Features about the ball Vector2D ball_pos = wm.ball().pos(); angleDistToPoint(self_pos, ball_pos, th, r); // Feature[3] and [4]: (x,y) postition of the ball if (playingOffense) { addNormFeature(ball_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x); } else { addNormFeature(ball_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x); } addNormFeature(ball_pos.y, -SP.pitchHalfWidth() - tolerance_y, SP.pitchHalfWidth() + tolerance_y); // Feature[5]: Able to kick addNormFeature(self.isKickable(), false, true); // Features about distance to goal center Vector2D goalCenter(SP.pitchHalfLength(), 0); if (!playingOffense) { goalCenter.assign(-SP.pitchHalfLength(), 0); } angleDistToPoint(self_pos, goalCenter, th, r); // Feature[6]: Goal Center Distance addNormFeature(r, 0, maxR); // Feature[7]: Angle to goal center addNormFeature(th, -M_PI, M_PI); // Feature[8]: largest open goal angle addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI); // Feature[9]: Dist to our closest opp if (numOpponents > 0) { calcClosestOpp(wm, self_pos, th, r); addNormFeature(r, 0, maxR); } else { addFeature(FEAT_INVALID); } // Features[9 - 9+T]: teammate's open angle to goal int detected_teammates = 0; for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) { const PlayerObject& teammate = *it; if (valid(teammate) && detected_teammates < numTeammates) { addNormFeature(calcLargestGoalAngle(wm, teammate.pos()), 0, M_PI); detected_teammates++; } } // Add zero features for any missing teammates for (int i=detected_teammates; i<numTeammates; ++i) { addFeature(FEAT_INVALID); } // Features[9+T - 9+2T]: teammates' dists to closest opps if (numOpponents > 0) { detected_teammates = 0; for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) { const PlayerObject& teammate = *it; if (valid(teammate) && detected_teammates < numTeammates) { calcClosestOpp(wm, teammate.pos(), th, r); addNormFeature(r, 0, maxR); detected_teammates++; } } // Add zero features for any missing teammates for (int i=detected_teammates; i<numTeammates; ++i) { addFeature(FEAT_INVALID); } } else { // If no opponents, add invalid features for (int i=0; i<numTeammates; ++i) { addFeature(FEAT_INVALID); } } // Features [9+2T - 9+3T]: open angle to teammates detected_teammates = 0; for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) { const PlayerObject& teammate = *it; if (valid(teammate) && detected_teammates < numTeammates) { addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate.pos()),0,M_PI); detected_teammates++; } } // Add zero features for any missing teammates for (int i=detected_teammates; i<numTeammates; ++i) { addFeature(FEAT_INVALID); } // Features [9+3T - 9+6T]: x, y, unum of teammates detected_teammates = 0; for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) { const PlayerObject& teammate = *it; if (valid(teammate) && detected_teammates < numTeammates) { if (playingOffense) { addNormFeature(teammate.pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x); } else { addNormFeature(teammate.pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x); } addNormFeature(teammate.pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y); addFeature(teammate.unum()); detected_teammates++; } } // Add zero features for any missing teammates for (int i=detected_teammates; i<numTeammates; ++i) { addFeature(FEAT_INVALID); addFeature(FEAT_INVALID); addFeature(FEAT_INVALID); } // Features [9+6T - 9+6T+3O]: x, y, unum of opponents int detected_opponents = 0; for (PlayerCont::const_iterator it = opponents.begin(); it != opponents.end(); ++it) { const PlayerObject& opponent = *it; if (valid(opponent) && detected_opponents < numOpponents) { if (playingOffense) { addNormFeature(opponent.pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x); } else { addNormFeature(opponent.pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x); } addNormFeature(opponent.pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y); addFeature(opponent.unum()); detected_opponents++; } } // Add zero features for any missing opponents for (int i=detected_opponents; i<numOpponents; ++i) { addFeature(FEAT_INVALID); addFeature(FEAT_INVALID); addFeature(FEAT_INVALID); } if (last_action_status) { addFeature(FEAT_MAX); } else { addFeature(FEAT_MIN); } assert(featIndx == numFeatures); // checkFeatures(); return feature_vec; } <|endoftext|>
<commit_before>/** * @file TaskScheduler.hpp * @author Denis Kotov * @date 23 Apr 2018 * @brief Scheduler for starting coroutine Tasks * @copyright Denis Kotov, MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git */ #ifndef ICC_TASHSHEDULER_HPP #define ICC_TASHSHEDULER_HPP #if defined(__cpp_coroutines) && __cpp_coroutines >= 201703 #include <boost/asio/io_service.hpp> #include <icc/Component.hpp> #include "Task.hpp" namespace icc { namespace coroutine { class TaskScheduler : public virtual icc::Component { public: TaskScheduler(); template <typename TService> TaskScheduler(TService * _contextChannel) : icc::Component(_contextChannel) { } TaskScheduler(std::shared_ptr<IContext::IChannel> _contextChannel); virtual ~TaskScheduler(); static TaskScheduler & getDefaultTaskSheduler(std::shared_ptr<IContext::IChannel> _contextChannel); template <typename _R> void startCoroutine(Task<_R> & _task) { _task.setContextChannel(getChannel()); _task.initialStart(); } template <typename _R> void startCoroutine(Task<_R> &&_task) { _task.setContextChannel(getChannel()); _task.initialStart(); } }; } } #endif #endif //ICC_TASHSHEDULER_HPP <commit_msg>Removed useless include to boost io_service<commit_after>/** * @file TaskScheduler.hpp * @author Denis Kotov * @date 23 Apr 2018 * @brief Scheduler for starting coroutine Tasks * @copyright Denis Kotov, MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git */ #ifndef ICC_TASHSHEDULER_HPP #define ICC_TASHSHEDULER_HPP #if defined(__cpp_coroutines) && __cpp_coroutines >= 201703 #include <icc/Component.hpp> #include "Task.hpp" namespace icc { namespace coroutine { class TaskScheduler : public virtual icc::Component { public: TaskScheduler(); template <typename TService> TaskScheduler(TService * _contextChannel) : icc::Component(_contextChannel) { } TaskScheduler(std::shared_ptr<IContext::IChannel> _contextChannel); virtual ~TaskScheduler(); static TaskScheduler & getDefaultTaskSheduler(std::shared_ptr<IContext::IChannel> _contextChannel); template <typename _R> void startCoroutine(Task<_R> & _task) { _task.setContextChannel(getChannel()); _task.initialStart(); } template <typename _R> void startCoroutine(Task<_R> &&_task) { _task.setContextChannel(getChannel()); _task.initialStart(); } }; } } #endif #endif //ICC_TASHSHEDULER_HPP <|endoftext|>
<commit_before>#include "LouvainSimplifier.h" #include <Graph.h> #include <Louvain.h> #include <iostream> using namespace std; bool LouvainSimplifier::updateData(Graph & target_graph, time_t start_time, time_t end_time, float start_sentiment, float end_sentiment, Graph & source_graph, RawStatistics & stats, bool is_first_level, Graph * base_graph) { if (target_graph.getNodeArray().hasTemporalCoverage() && !(end_time > start_time)) { cerr << "invalid time range for updateData: " << start_time << " - " << end_time << endl; return false; } assert(base_graph); auto & sid = source_graph.getNodeArray().getTable()["source"]; auto & soid = source_graph.getNodeArray().getTable()["id"]; auto & user_type = source_graph.getNodeArray().getTable()["type"]; auto & political_party = source_graph.getNodeArray().getTable()["party"]; auto & name_column = source_graph.getNodeArray().getTable()["name"]; auto & uname_column = source_graph.getNodeArray().getTable()["uname"]; auto begin = source_graph.begin_edges(); auto end = source_graph.end_edges(); auto it = begin; if (current_pos == -1) { target_graph.clear(); current_pos = 0; cerr << "restarting update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; } else { cerr << "continuing update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; for (int i = 0; i < current_pos; i++) ++it; } auto & nodes = target_graph.getNodeArray(); unsigned int skipped_count = 0; bool is_changed = false; unsigned int num_edges_processed = 0; for ( ; it != end; ++it, current_pos++) { num_edges_processed++; time_t t = 0; float se = 0; short lang = 0; long long app_id = -1, filter_id = -1; bool is_first = false; assert(it->face != -1); if (it->face != -1) { auto & fd = source_graph.getFaceAttributes(it->face); t = fd.timestamp; se = fd.sentiment; lang = fd.lang; app_id = fd.app_id; filter_id = fd.filter_id; is_first = fd.first_edge == current_pos; } if (it->tail < 0 || it->head < 0 || it->tail >= nodes.size() || it->head >= nodes.size()) { cerr << "invalid values: tail = " << it->tail << ", head = " << it->head << ", t = " << t << ", count = " << nodes.size() << ", n = " << num_edges_processed << endl; assert(0); } if ((!start_time || t >= start_time) && (!end_time || t < end_time) && se >= start_sentiment && se <= end_sentiment) { if (t < min_time || min_time == 0) min_time = t; if (t > max_time) max_time = t; pair<int, int> np(it->tail, it->head); short first_user_sid = sid.getInt(np.first); short target_user_sid = sid.getInt(np.second); long long first_user_soid = soid.getInt64(np.first); long long target_user_soid = soid.getInt64(np.second); auto td1 = base_graph->getNodeTertiaryData(np.first); // data is copied, since the backing array might change auto td2 = base_graph->getNodeTertiaryData(np.second); if (!is_first_level) { if (td1.indegree < target_graph.getMinSignificance()) { skipped_count++; continue; } if (td2.indegree < target_graph.getMinSignificance()) { skipped_count++; continue; } } is_changed = true; auto & target_nd_old = nodes.getNodeData(np.second); NodeType target_type = target_nd_old.type; if (is_first_level && is_first) { stats.addActivity(t, first_user_sid, first_user_soid, lang, app_id, filter_id, PoliticalParty(political_party.getInt(np.first))); } if (is_first_level && !seen_nodes.count(np.second)) { seen_nodes.insert(np.second); UserType ut = UserType(user_type.getInt(np.second)); if (ut != UNKNOWN_TYPE) stats.addUserType(ut); // stats.addPoliticalParty(PoliticalParty(political_party.getInt(np.first))); } if (target_type == NODE_HASHTAG) { stats.addHashtag(name_column.getText(np.second)); num_hashtags++; } else if (target_type == NODE_URL) { stats.addLink(name_column.getText(np.second), uname_column.getText(np.second)); num_links++; } else { if (is_first_level && target_type == NODE_ANY) { stats.addReceivedActivity(t, target_user_sid, target_user_soid, app_id, filter_id); } long long coverage = 0; if (target_graph.getNodeArray().hasTemporalCoverage()) { assert(end_time > start_time); int time_pos = 63LL * (t - start_time) / (end_time - start_time); assert(time_pos >= 0 && time_pos < 64); coverage |= 1 << time_pos; } unordered_map<int, unordered_map<int, int> >::iterator it1; unordered_map<int, int>::iterator it2; if ((it1 = seen_edges.find(np.first)) != seen_edges.end() && (it2 = it1->second.find(np.second)) != it1->second.end()) { #if 0 updateOutdegree(np.first, 1.0f); updateIndegree(np.second, 1.0f); updateNodeSize(np.first); updateNodeSize(np.second); #endif if (target_graph.getNodeArray().hasTemporalCoverage()) { assert(0); auto & ed = target_graph.getEdgeAttributes(it2->second); ed.coverage |= coverage; float new_weight = 0; for (int i = 0; i < 64; i++) { if (ed.coverage & (1 << i)) new_weight += 1.0f; } new_weight /= 64.0f; target_graph.updateEdgeWeight(it2->second, new_weight - ed.weight); } } else { seen_edges[np.first][np.second] = target_graph.addEdge(np.first, np.second, -1, 1.0f / 64.0f, 0, target_graph.getNodeArray().hasTemporalCoverage() ? coverage : 1.0f); #if 0 seen_edges[np.second][np.first] = target_graph.addEdge(np.second, np.first, -1, 1.0f / 64.0f, 0, target_graph.getNodeArray().hasTemporalCoverage() ? coverage : 1.0f); #endif } } } } // cerr << "updated graph data, nodes = " << nodes.size() << ", edges = " << getEdgeCount() << ", min_sig = " << target_graph.getMinSignificance() << ", skipped = " << skipped_count << ", first = " << is_first_level << endl; if (is_first_level) { stats.setTimeRange(min_time, max_time); stats.setNumRawNodes(nodes.size()); stats.setNumRawEdges(source_graph.getEdgeCount()); // stats.setNumPosts(num_posts); // stats.setNumActiveUsers(num_active_users); } if (is_changed) { target_graph.removeAllChildren(); double precision = 0.000001; cerr << "doing Louvain\n"; Louvain c(&target_graph, -1, precision); double mod = target_graph.modularity(); int level = 0; bool is_improved = true; bool is_first = true; for (int level = 1; level <= 1 && is_improved; level++) { is_improved = c.oneLevel(); double new_mod = target_graph.modularity(); level++; cerr << "l " << level << ": size: " << c.size() << ", modularity increase: " << mod << " to " << new_mod << endl; mod = new_mod; } unsigned int visible_nodes = 0, toplevel_nodes = 0; auto end = target_graph.end_visible_nodes(); for (auto it = target_graph.begin_visible_nodes(); it != end; ++it) { visible_nodes++; auto & td = target_graph.getNodeTertiaryData(*it); if (td.parent_node == -1) { toplevel_nodes++; if (td.child_count == 1) { // target_graph.removeChild(td.first_child); } int best_d = 0; int best_node = -1; for (int n = td.first_child; n != -1; ) { auto & ctd = target_graph.getNodeTertiaryData(n); if (best_node == -1 || ctd.indegree > best_d) { best_node = n; best_d = ctd.indegree; } target_graph.setIsGroupLeader(n, false); n = ctd.next_child; } if (best_node != -1) { target_graph.setIsGroupLeader(best_node, true); } } } cerr << "after louvain: visible = " << visible_nodes << ", toplevel = " << toplevel_nodes << endl; } return is_changed; } <commit_msg>add assertion<commit_after>#include "LouvainSimplifier.h" #include <Graph.h> #include <Louvain.h> #include <iostream> using namespace std; bool LouvainSimplifier::updateData(Graph & target_graph, time_t start_time, time_t end_time, float start_sentiment, float end_sentiment, Graph & source_graph, RawStatistics & stats, bool is_first_level, Graph * base_graph) { if (target_graph.getNodeArray().hasTemporalCoverage() && !(end_time > start_time)) { cerr << "invalid time range for updateData: " << start_time << " - " << end_time << endl; return false; } assert(base_graph); auto & sid = source_graph.getNodeArray().getTable()["source"]; auto & soid = source_graph.getNodeArray().getTable()["id"]; auto & user_type = source_graph.getNodeArray().getTable()["type"]; auto & political_party = source_graph.getNodeArray().getTable()["party"]; auto & name_column = source_graph.getNodeArray().getTable()["name"]; auto & uname_column = source_graph.getNodeArray().getTable()["uname"]; auto begin = source_graph.begin_edges(); auto end = source_graph.end_edges(); auto it = begin; if (current_pos == -1) { target_graph.clear(); current_pos = 0; cerr << "restarting update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; } else { cerr << "continuing update, begin = " << begin.get() << ", cp = " << current_pos << ", end = " << end.get() << ", source = " << &source_graph << ", edges = " << source_graph.getEdgeCount() << endl; for (int i = 0; i < current_pos; i++) ++it; } auto & nodes = target_graph.getNodeArray(); unsigned int skipped_count = 0; bool is_changed = false; unsigned int num_edges_processed = 0; for ( ; it != end; ++it, current_pos++) { num_edges_processed++; time_t t = 0; float se = 0; short lang = 0; long long app_id = -1, filter_id = -1; bool is_first = false; assert(it->face != -1); if (it->face != -1) { assert(it->face >= 0 && it->face < source_graph.getFaceCount()); auto & fd = source_graph.getFaceAttributes(it->face); t = fd.timestamp; se = fd.sentiment; lang = fd.lang; app_id = fd.app_id; filter_id = fd.filter_id; is_first = fd.first_edge == current_pos; } if (it->tail < 0 || it->head < 0 || it->tail >= nodes.size() || it->head >= nodes.size()) { cerr << "invalid values: tail = " << it->tail << ", head = " << it->head << ", t = " << t << ", count = " << nodes.size() << ", n = " << num_edges_processed << endl; assert(0); } if ((!start_time || t >= start_time) && (!end_time || t < end_time) && se >= start_sentiment && se <= end_sentiment) { if (t < min_time || min_time == 0) min_time = t; if (t > max_time) max_time = t; pair<int, int> np(it->tail, it->head); short first_user_sid = sid.getInt(np.first); short target_user_sid = sid.getInt(np.second); long long first_user_soid = soid.getInt64(np.first); long long target_user_soid = soid.getInt64(np.second); auto td1 = base_graph->getNodeTertiaryData(np.first); // data is copied, since the backing array might change auto td2 = base_graph->getNodeTertiaryData(np.second); if (!is_first_level) { if (td1.indegree < target_graph.getMinSignificance()) { skipped_count++; continue; } if (td2.indegree < target_graph.getMinSignificance()) { skipped_count++; continue; } } is_changed = true; auto & target_nd_old = nodes.getNodeData(np.second); NodeType target_type = target_nd_old.type; if (is_first_level && is_first) { stats.addActivity(t, first_user_sid, first_user_soid, lang, app_id, filter_id, PoliticalParty(political_party.getInt(np.first))); } if (is_first_level && !seen_nodes.count(np.second)) { seen_nodes.insert(np.second); UserType ut = UserType(user_type.getInt(np.second)); if (ut != UNKNOWN_TYPE) stats.addUserType(ut); // stats.addPoliticalParty(PoliticalParty(political_party.getInt(np.first))); } if (target_type == NODE_HASHTAG) { stats.addHashtag(name_column.getText(np.second)); num_hashtags++; } else if (target_type == NODE_URL) { stats.addLink(name_column.getText(np.second), uname_column.getText(np.second)); num_links++; } else { if (is_first_level && target_type == NODE_ANY) { stats.addReceivedActivity(t, target_user_sid, target_user_soid, app_id, filter_id); } long long coverage = 0; if (target_graph.getNodeArray().hasTemporalCoverage()) { assert(end_time > start_time); int time_pos = 63LL * (t - start_time) / (end_time - start_time); assert(time_pos >= 0 && time_pos < 64); coverage |= 1 << time_pos; } unordered_map<int, unordered_map<int, int> >::iterator it1; unordered_map<int, int>::iterator it2; if ((it1 = seen_edges.find(np.first)) != seen_edges.end() && (it2 = it1->second.find(np.second)) != it1->second.end()) { #if 0 updateOutdegree(np.first, 1.0f); updateIndegree(np.second, 1.0f); updateNodeSize(np.first); updateNodeSize(np.second); #endif if (target_graph.getNodeArray().hasTemporalCoverage()) { assert(0); auto & ed = target_graph.getEdgeAttributes(it2->second); ed.coverage |= coverage; float new_weight = 0; for (int i = 0; i < 64; i++) { if (ed.coverage & (1 << i)) new_weight += 1.0f; } new_weight /= 64.0f; target_graph.updateEdgeWeight(it2->second, new_weight - ed.weight); } } else { seen_edges[np.first][np.second] = target_graph.addEdge(np.first, np.second, -1, 1.0f / 64.0f, 0, target_graph.getNodeArray().hasTemporalCoverage() ? coverage : 1.0f); #if 0 seen_edges[np.second][np.first] = target_graph.addEdge(np.second, np.first, -1, 1.0f / 64.0f, 0, target_graph.getNodeArray().hasTemporalCoverage() ? coverage : 1.0f); #endif } } } } // cerr << "updated graph data, nodes = " << nodes.size() << ", edges = " << getEdgeCount() << ", min_sig = " << target_graph.getMinSignificance() << ", skipped = " << skipped_count << ", first = " << is_first_level << endl; if (is_first_level) { stats.setTimeRange(min_time, max_time); stats.setNumRawNodes(nodes.size()); stats.setNumRawEdges(source_graph.getEdgeCount()); // stats.setNumPosts(num_posts); // stats.setNumActiveUsers(num_active_users); } if (is_changed) { target_graph.removeAllChildren(); double precision = 0.000001; cerr << "doing Louvain\n"; Louvain c(&target_graph, -1, precision); double mod = target_graph.modularity(); int level = 0; bool is_improved = true; bool is_first = true; for (int level = 1; level <= 1 && is_improved; level++) { is_improved = c.oneLevel(); double new_mod = target_graph.modularity(); level++; cerr << "l " << level << ": size: " << c.size() << ", modularity increase: " << mod << " to " << new_mod << endl; mod = new_mod; } unsigned int visible_nodes = 0, toplevel_nodes = 0; auto end = target_graph.end_visible_nodes(); for (auto it = target_graph.begin_visible_nodes(); it != end; ++it) { visible_nodes++; auto & td = target_graph.getNodeTertiaryData(*it); if (td.parent_node == -1) { toplevel_nodes++; if (td.child_count == 1) { // target_graph.removeChild(td.first_child); } int best_d = 0; int best_node = -1; for (int n = td.first_child; n != -1; ) { auto & ctd = target_graph.getNodeTertiaryData(n); if (best_node == -1 || ctd.indegree > best_d) { best_node = n; best_d = ctd.indegree; } target_graph.setIsGroupLeader(n, false); n = ctd.next_child; } if (best_node != -1) { target_graph.setIsGroupLeader(best_node, true); } } } cerr << "after louvain: visible = " << visible_nodes << ", toplevel = " << toplevel_nodes << endl; } return is_changed; } <|endoftext|>
<commit_before>/* * 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 "stdafx.h" #include "MZ3.h" #include "MixiParser.h" #include <set> /// Twitter pp[T namespace twitter { /** * [list] ^CCpp[T * y^CCz * http://twitter.com/statuses/friends_timeline.xml */ bool TwitterFriendsTimelineXmlParser::parse( CMixiDataList& out_, const CHtmlArray& html_ ) { MZ3LOGGER_DEBUG( L"TwitterFriendsTimelineXmlParser.parse() start." ); // html_ ̕ std::vector<TCHAR> text; html_.TranslateToVectorBuffer( text ); // XML xml2stl::Container root; if (!xml2stl::SimpleXmlParser::loadFromText( root, text )) { MZ3LOGGER_ERROR( L"XML ͎s" ); return false; } // dh~p id ꗗ𐶐B std::set<int> id_set; for (size_t i=0; i<out_.size(); i++) { id_set.insert( out_[i].GetID() ); } // status ɑ΂鏈 try { const xml2stl::Node& statuses = root.getNode( L"statuses" ); size_t nChildren = statuses.getChildrenCount(); for (size_t i=0; i<nChildren; i++) { const xml2stl::Node& node = statuses.getNode(i); if (node.getName() != L"status") { continue; } try { const xml2stl::Node& status = node; // IuWFNg CMixiData data; data.SetAccessType( ACCESS_TWITTER_USER ); // text : status/text CString strBody = status.getNode(L"text").getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( strBody ); data.AddBody( strBody ); // source : status/source // qvfƂĒlj CString source = status.getNode(L"source").getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( source ); CMixiData sourceData; sourceData.AddBody( source ); data.AddChild( sourceData ); // name : status/user/screen_name const xml2stl::Node& user = status.getNode( L"user" ); data.SetName( user.getNode(L"screen_name").getTextAll().c_str() ); // author : status/user/name CString strAuthor = user.getNode(L"name").getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( strAuthor ); data.SetAuthor( strAuthor ); // description : status/user/description // title ɓ̂͋̍EEE CString strTitle = user.getNode(L"description").getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( strTitle ); data.SetTitle( strTitle ); // id : status/id int id = _wtoi( status.getNode(L"id").getTextAll().c_str() ); data.SetID( id ); // IDΒljȂB if (id_set.count(id)>0) { continue; } // owner-id : status/user/id data.SetOwnerID( _wtoi( user.getNode(L"id").getTextAll().c_str() ) ); // URL : status/user/url CString url = user.getNode( L"url" ).getTextAll().c_str(); data.SetURL( url ); data.SetBrowseUri( url ); // Image : status/user/profile_image_url CString strImage = user.getNode( L"profile_image_url" ).getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( strImage ); data.AddImage( strImage ); // updated : status/created_at mixi::ParserUtil::ParseDate( status.getNode( L"created_at" ).getTextAll().c_str(), data ); // URL 𒊏oANɂ TwitterFriendsTimelineXmlParser::ExtractLinks( data ); // id ~ɂȂ悤ɒljB { size_t j=0; for (; j<out_.size(); j++) { if (id > out_[j].GetID()) { break; } } out_.insert( out_.begin()+j, data ); } } catch (xml2stl::NodeNotFoundException& e) { MZ3LOGGER_ERROR( util::FormatString( L"some node or property not found... : %s", e.getMessage().c_str()) ); break; } } } catch (xml2stl::NodeNotFoundException& e) { MZ3LOGGER_ERROR( util::FormatString( L"statuses not found... : %s", e.getMessage().c_str()) ); } // ő匏i̗]ȃf[^폜j const size_t LIST_MAX_SIZE = 1000; if (out_.size()>LIST_MAX_SIZE) { out_.erase( out_.begin()+LIST_MAX_SIZE, out_.end() ); } MZ3LOGGER_DEBUG( L"TwitterFriendsTimelineXmlParser.parse() finished." ); return true; } bool TwitterFriendsTimelineXmlParser::ExtractLinks(CMixiData &data_) { // K\̃RpCî݁j static MyRegex reg; if( !util::CompileRegex( reg, L"(h?ttps?://[-_.!~*'()a-zA-Z0-9;/?:@&=+$,%#]+)" ) ) { MZ3LOGGER_FATAL( FAILED_TO_COMPILE_REGEX_MSG ); return false; } CString target; for (u_int i=0; i<data_.GetBodySize(); i++) { target.Append( data_.GetBody(i) ); } for( int i=0; i<100; i++ ) { // 100 ͖[vh~ if( reg.exec(target) == false || reg.results.size() != 2 ) { // BIB break; } // B // URL std::wstring& url = reg.results[1].str; if (!url.empty() && url[0] != 'h') { url.insert( url.begin(), 'h' ); } // f[^ɒlj data_.m_linkList.push_back( CMixiData::Link(url.c_str(), url.c_str()) ); // ^[QbgXVB target = target.Mid( reg.results[0].end ); } return true; } }//namespace twitter <commit_msg>entityデコード調整<commit_after>/* * 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 "stdafx.h" #include "MZ3.h" #include "MixiParser.h" #include <set> /// Twitter pp[T namespace twitter { /** * [list] ^CCpp[T * y^CCz * http://twitter.com/statuses/friends_timeline.xml */ bool TwitterFriendsTimelineXmlParser::parse( CMixiDataList& out_, const CHtmlArray& html_ ) { MZ3LOGGER_DEBUG( L"TwitterFriendsTimelineXmlParser.parse() start." ); // html_ ̕ std::vector<TCHAR> text; html_.TranslateToVectorBuffer( text ); // XML xml2stl::Container root; if (!xml2stl::SimpleXmlParser::loadFromText( root, text )) { MZ3LOGGER_ERROR( L"XML ͎s" ); return false; } // dh~p id ꗗ𐶐B std::set<int> id_set; for (size_t i=0; i<out_.size(); i++) { id_set.insert( out_[i].GetID() ); } // status ɑ΂鏈 try { const xml2stl::Node& statuses = root.getNode( L"statuses" ); size_t nChildren = statuses.getChildrenCount(); for (size_t i=0; i<nChildren; i++) { const xml2stl::Node& node = statuses.getNode(i); if (node.getName() != L"status") { continue; } try { const xml2stl::Node& status = node; // IuWFNg CMixiData data; data.SetAccessType( ACCESS_TWITTER_USER ); // text : status/text CString strBody = status.getNode(L"text").getTextAll().c_str(); while( strBody.Replace(_T("&amp;"), _T("&")) ) ; mixi::ParserUtil::ReplaceEntityReferenceToCharacter( strBody ); data.AddBody( strBody ); // source : status/source // qvfƂĒlj CString source = status.getNode(L"source").getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( source ); CMixiData sourceData; sourceData.AddBody( source ); data.AddChild( sourceData ); // name : status/user/screen_name const xml2stl::Node& user = status.getNode( L"user" ); data.SetName( user.getNode(L"screen_name").getTextAll().c_str() ); // author : status/user/name CString strAuthor = user.getNode(L"name").getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( strAuthor ); data.SetAuthor( strAuthor ); // description : status/user/description // title ɓ̂͋̍EEE CString strTitle = user.getNode(L"description").getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( strTitle ); data.SetTitle( strTitle ); // id : status/id int id = _wtoi( status.getNode(L"id").getTextAll().c_str() ); data.SetID( id ); // IDΒljȂB if (id_set.count(id)>0) { continue; } // owner-id : status/user/id data.SetOwnerID( _wtoi( user.getNode(L"id").getTextAll().c_str() ) ); // URL : status/user/url CString url = user.getNode( L"url" ).getTextAll().c_str(); data.SetURL( url ); data.SetBrowseUri( url ); // Image : status/user/profile_image_url CString strImage = user.getNode( L"profile_image_url" ).getTextAll().c_str(); mixi::ParserUtil::ReplaceEntityReferenceToCharacter( strImage ); data.AddImage( strImage ); // updated : status/created_at mixi::ParserUtil::ParseDate( status.getNode( L"created_at" ).getTextAll().c_str(), data ); // URL 𒊏oANɂ TwitterFriendsTimelineXmlParser::ExtractLinks( data ); // id ~ɂȂ悤ɒljB { size_t j=0; for (; j<out_.size(); j++) { if (id > out_[j].GetID()) { break; } } out_.insert( out_.begin()+j, data ); // for performance tuning /* if (out_.size()==1) { for (int k=0; k<100; k++) { out_.insert( out_.begin()+j, data ); } } */ } } catch (xml2stl::NodeNotFoundException& e) { MZ3LOGGER_ERROR( util::FormatString( L"some node or property not found... : %s", e.getMessage().c_str()) ); break; } } } catch (xml2stl::NodeNotFoundException& e) { MZ3LOGGER_ERROR( util::FormatString( L"statuses not found... : %s", e.getMessage().c_str()) ); } // ő匏i̗]ȃf[^폜j const size_t LIST_MAX_SIZE = 1000; if (out_.size()>LIST_MAX_SIZE) { out_.erase( out_.begin()+LIST_MAX_SIZE, out_.end() ); } MZ3LOGGER_DEBUG( L"TwitterFriendsTimelineXmlParser.parse() finished." ); return true; } bool TwitterFriendsTimelineXmlParser::ExtractLinks(CMixiData &data_) { // K\̃RpCî݁j static MyRegex reg; if( !util::CompileRegex( reg, L"(h?ttps?://[-_.!~*'()a-zA-Z0-9;/?:@&=+$,%#]+)" ) ) { MZ3LOGGER_FATAL( FAILED_TO_COMPILE_REGEX_MSG ); return false; } CString target; for (u_int i=0; i<data_.GetBodySize(); i++) { target.Append( data_.GetBody(i) ); } for( int i=0; i<100; i++ ) { // 100 ͖[vh~ if( reg.exec(target) == false || reg.results.size() != 2 ) { // BIB break; } // B // URL std::wstring& url = reg.results[1].str; if (!url.empty() && url[0] != 'h') { url.insert( url.begin(), 'h' ); } // f[^ɒlj data_.m_linkList.push_back( CMixiData::Link(url.c_str(), url.c_str()) ); // ^[QbgXVB target = target.Mid( reg.results[0].end ); } return true; } }//namespace twitter <|endoftext|>
<commit_before>// GPS Tracker project with Adafruit IO // Author: Martin Spier #include "Arduino_Tracker.h" // Alarm pins const int ledPin = LEAD_PIN; // for the data logging shield, we use digital pin 10 for the SD cs line const int chipSelect = 10; // the logging file File logfile; // FONA instance & configuration SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); // FONA software serial connection. Adafruit_FONA fona = Adafruit_FONA(FONA_RST); // FONA library connection. // Setup the FONA MQTT class by passing in the FONA class and MQTT server and login details. Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); uint8_t txFailures = 0; // Count of how many publish failures have occured in a row. uint8_t mqttFailures = 0; // Count of how many MQTT connect failures have occured in a row. uint8_t gpsFixFailures = 0; // Count of how many GPS fix failures have occured in a row. uint8_t gprsFailures = 0; // Count of how many GPS fix failures have occured in a row. float latitude, longitude, speed_kph, heading, altitude; uint16_t vbat; // Halt function called when an error occurs. Will print an error and stop execution while // doing a fast blink of the LED. If the watchdog is enabled it will reset after 8 seconds. void halt(const __FlashStringHelper *error) { Serial.println(error); Watchdog.enable(8000); Watchdog.reset(); while (1) { digitalWrite(ledPin, LOW); delay(100); digitalWrite(ledPin, HIGH); delay(100); } } // Function to connect and reconnect as necessary to the MQTT server. // Should be called in the loop function and it will take care if connecting. int8_t mqttConnect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { Serial.println(F("MQTT already connected... ")); return 0; } Serial.println(F("Connecting to MQTT... ")); while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected Serial.println(mqtt.connectErrorString(ret)); mqttFailures++; // Reset everything if too many MQTT connect failures occured in a row. if (mqttFailures >= MAX_MQTT_FAILURES) { Serial.println(F("Too many MQTT connect failures, aborting...")); return -1; } Serial.println(F("Retrying MQTT connection in 5 seconds...")); mqtt.disconnect(); delay(5000); // wait 5 seconds } Serial.println(F("MQTT Connected!")); mqttFailures = 0; return 0; } int8_t cellularConnect() { Watchdog.enable(8000); Watchdog.reset(); // Getting out of sleep mode fonaSS.println("AT+CSCLK=0"); // Wait for FONA to connect to cell network (up to 8 seconds, then watchdog reset). Serial.println(F("Checking for network...")); Watchdog.reset(); while (fona.getNetworkStatus() != 1) { fonaSS.println("AT+CSCLK=0"); delay(500); } // Disable GPRS Watchdog.reset(); Serial.println(F("Disabling GPRS")); fona.enableGPRS(false); // Wait a little bit Watchdog.reset(); delay(2000); // Start the GPRS data connection. Serial.println(F("Enabling GPRS")); Watchdog.disable(); while (!fona.enableGPRS(true)) { Serial.println(F("Failed to turn GPRS on...")); gprsFailures++; // Reset everything if too many MQTT connect failures occured in a row. if (gprsFailures >= MAX_GPRS_FAILURES) { Serial.println(F("Failed to turn GPRS on, aborting...")); return -1; } Serial.println(F("Retrying GPRS in 10 seconds...")); delay(10000); // wait 10 seconds } Serial.println(F("Connected to Cellular!")); return 0; } // Serialize the lat, long, altitude to a CSV string that can be published to the specified feed. int8_t mqttLog() { // Initialize a string buffer to hold the data that will be published. char sendbuffer[48]; char *p = sendbuffer; // add speed value dtostrf(speed_kph, 2, 2, p); p += strlen(p); // add vbat value sprintf (p, ":%u", vbat); p += strlen(p); p[0] = ','; p++; // concat latitude dtostrf(latitude, 2, 6, p); p += strlen(p); p[0] = ','; p++; // concat longitude dtostrf(longitude, 3, 6, p); p += strlen(p); p[0] = ','; p++; // concat altitude dtostrf(altitude, 2, 2, p); p += strlen(p); // null terminate p[0] = 0; // Feeds configuration Adafruit_MQTT_Publish publishFeed = Adafruit_MQTT_Publish(&mqtt, AIO_FEED); // Finally publish the string to the feed. Serial.println(F("Publishing tracker information: ")); Serial.println(sendbuffer); if (!publishFeed.publish(sendbuffer)) { Serial.println(F("Publish failed!")); txFailures++; // Reset everything if too many transmit failures occured in a row. if (txFailures >= MAX_TX_FAILURES) { Serial.println(F("Connection lost, aborting...")); return -1; } } else { Serial.println(F("Publish succeeded!")); txFailures = 0; } return 0; } int8_t sdLog() { // initialize the SD card Serial.print(F("Initializing SD card...")); // see if the card is present and can be initialized if (!SD.begin(chipSelect)) { Serial.println(F("Card failed, or not present. Aborting.")); // don't do anything else return -1; } Serial.println(F("SD card initialized.")); // make a string for assembling the data to log: String dataString = ""; // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. logfile = SD.open("datalog.txt", FILE_WRITE); // if the file is available, write to it: if (logfile) { logfile.println(dataString); logfile.close(); // print to the serial port too: Serial.println(dataString); } // if the file isn't open, pop up an error: else { Serial.println(F("Error opening datalog.txt.")); return -1; } return 0; } int8_t getGPSFix() { Serial.println(F("Trying to get a GPS fix... ")); while (!fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude)) { // getGPS will return true for 3D fix Serial.println(F("Waiting for FONA GPS 3D fix...")); gpsFixFailures++; // Reset everything if too many MQTT connect failures occured in a row. if (gpsFixFailures >= MAX_GPS_FIX_FAILURES) { Serial.println(F("Too many GPS fix failures, aborting...")); return -1; } Serial.println(F("Retrying GPS fix in 10 seconds...")); delay(10000); // wait 10 seconds } Serial.println(F("FONA GPS 3D fix acquired!")); gpsFixFailures = 0; // Grab battery reading fona.getBattPercent(&vbat); return 0; } void setup() { // Initialize serial output. Serial.begin(115200); Serial.println(F("Adafruit IO & FONA808 Tracker")); // make sure that the default chip select pin is set to // output, even if you don't use it: pinMode(chipSelect, OUTPUT); // Set alarm components pinMode(ledPin, OUTPUT); // Initialize the FONA module Serial.println(F("Initializing FONA....(may take 10 seconds)")); fonaSS.begin(4800); if (!fona.begin(fonaSS)) { halt(F("Couldn't find FONA")); } fonaSS.println("AT+CMEE=2"); Serial.println(F("FONA is OK")); // Set GPRS network settings. fona.setGPRSNetworkSettings(F(FONA_APN)); // fona.setGPRSNetworkSettings(F(FONA_APN), F(FONA_USERNAME), F(FONA_PASSWORD)); // Wait a little bit to make sure settings are in effect. delay(2000); } void loop() { // Use the watchdog to simplify retry logic and make things more robust. Watchdog.enable(8000); // Enable GPS Watchdog.reset(); fona.enableGPS(true); // Wait a little bit to make sure GPS is enabled. Watchdog.reset(); delay(5000); // Disabling watchdog Watchdog.disable(); // Grab a GPS reading. if (!(getGPSFix() < 0)) { // Log to SD card // sdLog(); // Connect to cellular if (!(cellularConnect() < 0)) { // Connect to MQTT server. if (!(mqttConnect() < 0)) { // Log to MQTT mqttLog(); } } } // Use the watchdog to simplify retry logic and make things more robust. Watchdog.enable(8000); // Disconnect MQTT connection. Watchdog.reset(); mqtt.disconnect(); // Disable GPS. // TODO: Check if it was really disabled Watchdog.reset(); fona.enableGPS(false); // Disable GPRS // TODO: Check if it was really disabled Watchdog.reset(); fona.enableGPRS(false); // Put FONA in sleep module // TODO: Wait for Ok and retry Watchdog.reset(); fonaSS.println("AT+CSCLK=1"); // Disable Watchdog for delay Watchdog.disable(); // Wait 60 seconds delay(PUBLISH_INTERVAL * 60000); } <commit_msg>Logging data to SD card.<commit_after>// GPS Tracker project with Adafruit IO // Author: Martin Spier #include "Arduino_Tracker.h" // Alarm pins const int ledPin = LEAD_PIN; // for the data logging shield, we use digital pin 10 for the SD cs line const int chipSelect = 10; // the logging file File logfile; // FONA instance & configuration SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); // FONA software serial connection. Adafruit_FONA fona = Adafruit_FONA(FONA_RST); // FONA library connection. // Setup the FONA MQTT class by passing in the FONA class and MQTT server and login details. Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); uint8_t txFailures = 0; // Count of how many publish failures have occured in a row. uint8_t mqttFailures = 0; // Count of how many MQTT connect failures have occured in a row. uint8_t gpsFixFailures = 0; // Count of how many GPS fix failures have occured in a row. uint8_t gprsFailures = 0; // Count of how many GPS fix failures have occured in a row. float latitude, longitude, speed_kph, heading, altitude; uint8_t year, month, date, hr, min, sec; uint16_t vbat; // Halt function called when an error occurs. Will print an error and stop execution while // doing a fast blink of the LED. If the watchdog is enabled it will reset after 8 seconds. void halt(const __FlashStringHelper *error) { Serial.println(error); Watchdog.enable(8000); Watchdog.reset(); while (1) { digitalWrite(ledPin, LOW); delay(100); digitalWrite(ledPin, HIGH); delay(100); } } // Function to connect and reconnect as necessary to the MQTT server. // Should be called in the loop function and it will take care if connecting. int8_t mqttConnect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { Serial.println(F("MQTT already connected... ")); return 0; } Serial.println(F("Connecting to MQTT... ")); while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected Serial.println(mqtt.connectErrorString(ret)); mqttFailures++; // Reset everything if too many MQTT connect failures occured in a row. if (mqttFailures >= MAX_MQTT_FAILURES) { Serial.println(F("Too many MQTT connect failures, aborting...")); return -1; } Serial.println(F("Retrying MQTT connection in 5 seconds...")); mqtt.disconnect(); delay(5000); // wait 5 seconds } Serial.println(F("MQTT Connected!")); mqttFailures = 0; return 0; } int8_t cellularConnect() { Watchdog.enable(8000); Watchdog.reset(); // Getting out of sleep mode fonaSS.println("AT+CSCLK=0"); // Wait for FONA to connect to cell network (up to 8 seconds, then watchdog reset). Serial.println(F("Checking for network...")); Watchdog.reset(); while (fona.getNetworkStatus() != 1) { fonaSS.println("AT+CSCLK=0"); delay(500); } // Disable GPRS Watchdog.reset(); Serial.println(F("Disabling GPRS")); fona.enableGPRS(false); // Wait a little bit Watchdog.reset(); delay(2000); // Start the GPRS data connection. Serial.println(F("Enabling GPRS")); Watchdog.disable(); while (!fona.enableGPRS(true)) { Serial.println(F("Failed to turn GPRS on...")); gprsFailures++; // Reset everything if too many MQTT connect failures occured in a row. if (gprsFailures >= MAX_GPRS_FAILURES) { Serial.println(F("Failed to turn GPRS on, aborting...")); return -1; } Serial.println(F("Retrying GPRS in 10 seconds...")); delay(10000); // wait 10 seconds } Serial.println(F("Connected to Cellular!")); return 0; } // Serialize the lat, long, altitude to a CSV string that can be published to the specified feed. int8_t mqttLog() { // Initialize a string buffer to hold the data that will be published. char sendbuffer[48]; char *p = sendbuffer; // add speed value dtostrf(speed_kph, 2, 2, p); p += strlen(p); // add vbat value sprintf (p, ":%u", vbat); p += strlen(p); p[0] = ','; p++; // concat latitude dtostrf(latitude, 2, 6, p); p += strlen(p); p[0] = ','; p++; // concat longitude dtostrf(longitude, 3, 6, p); p += strlen(p); p[0] = ','; p++; // concat altitude dtostrf(altitude, 2, 2, p); p += strlen(p); // null terminate p[0] = 0; // Feeds configuration Adafruit_MQTT_Publish publishFeed = Adafruit_MQTT_Publish(&mqtt, AIO_FEED); // Finally publish the string to the feed. Serial.println(F("Publishing tracker information: ")); Serial.println(sendbuffer); if (!publishFeed.publish(sendbuffer)) { Serial.println(F("Publish failed!")); txFailures++; // Reset everything if too many transmit failures occured in a row. if (txFailures >= MAX_TX_FAILURES) { Serial.println(F("Connection lost, aborting...")); return -1; } } else { Serial.println(F("Publish succeeded!")); txFailures = 0; } return 0; } int8_t sdLog() { // initialize the SD card Serial.print(F("Initializing SD card...")); // see if the card is present and can be initialized if (!SD.begin(chipSelect)) { Serial.println(F("Card failed, or not present. Aborting.")); // don't do anything else return -1; } Serial.println(F("SD card initialized.")); // make a string for assembling the data to log: char dataString[64]; char *p = dataString; // add date and time sprintf (p, "%u-%u-%u %u:%u:%u", year, month, date, hr, min, sec); p += strlen(p); p[0] = ','; p++; // add speed value dtostrf(speed_kph, 2, 2, p); p += strlen(p); // add vbat value sprintf (p, ":%u", vbat); p += strlen(p); p[0] = ','; p++; // concat latitude dtostrf(latitude, 2, 6, p); p += strlen(p); p[0] = ','; p++; // concat longitude dtostrf(longitude, 3, 6, p); p += strlen(p); p[0] = ','; p++; // concat altitude dtostrf(altitude, 2, 2, p); p += strlen(p); // null terminate p[0] = 0; // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. logfile = SD.open("datalog.txt", FILE_WRITE); // if the file is available, write to it: if (logfile) { logfile.println(dataString); logfile.close(); // print to the serial port too: Serial.println(dataString); } // if the file isn't open, pop up an error: else { Serial.println(F("Error opening datalog.txt.")); return -1; } return 0; } int8_t getGPSFix() { Serial.println(F("Trying to get a GPS fix... ")); while (!fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude)) { // getGPS will return true for 3D fix Serial.println(F("Waiting for FONA GPS 3D fix...")); gpsFixFailures++; // Reset everything if too many MQTT connect failures occured in a row. if (gpsFixFailures >= MAX_GPS_FIX_FAILURES) { Serial.println(F("Too many GPS fix failures, aborting...")); return -1; } Serial.println(F("Retrying GPS fix in 10 seconds...")); delay(10000); // wait 10 seconds } Serial.println(F("FONA GPS 3D fix acquired!")); gpsFixFailures = 0; // Grab battery reading fona.getBattPercent(&vbat); // Grab time fona.readRTC(&year, &month, &date, &hr, &min, &sec); return 0; } void setup() { // Initialize serial output. Serial.begin(115200); Serial.println(F("Adafruit IO & FONA808 Tracker")); // make sure that the default chip select pin is set to // output, even if you don't use it: pinMode(chipSelect, OUTPUT); // Set alarm components pinMode(ledPin, OUTPUT); // Initialize the FONA module Serial.println(F("Initializing FONA....(may take 10 seconds)")); fonaSS.begin(4800); if (!fona.begin(fonaSS)) { halt(F("Couldn't find FONA")); } fonaSS.println("AT+CMEE=2"); Serial.println(F("FONA is OK")); // Set GPRS network settings. fona.setGPRSNetworkSettings(F(FONA_APN)); // fona.setGPRSNetworkSettings(F(FONA_APN), F(FONA_USERNAME), F(FONA_PASSWORD)); // Wait a little bit to make sure settings are in effect. delay(2000); } void loop() { // Use the watchdog to simplify retry logic and make things more robust. Watchdog.enable(8000); // Enable GPS Watchdog.reset(); fona.enableGPS(true); // Wait a little bit to make sure GPS is enabled. Watchdog.reset(); delay(5000); // Disabling watchdog Watchdog.disable(); // Grab a GPS reading. if (!(getGPSFix() < 0)) { // Log to SD card // sdLog(); // Connect to cellular if (!(cellularConnect() < 0)) { // Connect to MQTT server. if (!(mqttConnect() < 0)) { // Log to MQTT mqttLog(); } } } // Use the watchdog to simplify retry logic and make things more robust. Watchdog.enable(8000); // Disconnect MQTT connection. Watchdog.reset(); mqtt.disconnect(); // Disable GPS. // TODO: Check if it was really disabled Watchdog.reset(); fona.enableGPS(false); // Disable GPRS // TODO: Check if it was really disabled Watchdog.reset(); fona.enableGPRS(false); // Put FONA in sleep module // TODO: Wait for Ok and retry Watchdog.reset(); fonaSS.println("AT+CSCLK=1"); // Disable Watchdog for delay Watchdog.disable(); // Wait 60 seconds delay(PUBLISH_INTERVAL * 60000); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- Filename: TinyOgre.cpp ----------------------------------------------------------------------------- This source file is part of the ___ __ __ _ _ _ /___\__ _ _ __ ___ / / /\ \ (_) | _(_) // // _` | '__/ _ \ \ \/ \/ / | |/ / | / \_// (_| | | | __/ \ /\ /| | <| | \___/ \__, |_| \___| \/ \/ |_|_|\_\_| |___/ Tutorial Framework http://www.ogre3d.org/tikiwiki/ ----------------------------------------------------------------------------- */ #include "BaseApplication.h" #include "btBulletDynamicsCommon.h" #include <OgreLogManager.h> #include <OgreViewport.h> #include <OgreConfigFile.h> #include <OgreEntity.h> #include <OgreWindowEventUtilities.h> //------------------------------------------------------------------------------------- TinyOgre::TinyOgre(void) : mRoot(0), mCamera(0), mSceneMgr(0), mWindow(0), mResourcesCfg(Ogre::StringUtil::BLANK), mPluginsCfg(Ogre::StringUtil::BLANK) { } //------------------------------------------------------------------------------------- TinyOgre::~TinyOgre(void) { delete mRoot; } bool TinyOgre::go(void) { #ifdef _DEBUG mResourcesCfg = "resources_d.cfg"; mPluginsCfg = "plugins_d.cfg"; #else mResourcesCfg = "resources.cfg"; mPluginsCfg = "plugins.cfg"; #endif // construct Ogre::Root mRoot = new Ogre::Root(mPluginsCfg); //------------------------------------------------------------------------------------- // setup resources // Load resource paths from config file Ogre::ConfigFile cf; cf.load(mResourcesCfg); // Go through all sections & settings in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } //------------------------------------------------------------------------------------- // configure // Show the configuration dialog and initialise the system // You can skip this and use root.restoreConfig() to load configuration // settings if you were sure there are valid ones saved in ogre.cfg if(mRoot->restoreConfig() || mRoot->showConfigDialog()) { // If returned true, user clicked OK so initialise // Here we choose to let the system create a default rendering window by passing 'true' mWindow = mRoot->initialise(true, "TinyOgre Render Window"); } else { return false; } //------------------------------------------------------------------------------------- // choose scenemanager // Get the SceneManager, in this case a generic one mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC); //------------------------------------------------------------------------------------- // create camera // Create the camera mCamera = mSceneMgr->createCamera("PlayerCam"); // Position it at 500 in Z direction mCamera->setPosition(Ogre::Vector3(0,0,80)); // Look back along -Z mCamera->lookAt(Ogre::Vector3(0,0,-300)); mCamera->setNearClipDistance(5); //------------------------------------------------------------------------------------- // create viewports // Create one viewport, entire window Ogre::Viewport* vp = mWindow->addViewport(mCamera); vp->setBackgroundColour(Ogre::ColourValue(0,0,0)); // Alter the camera aspect ratio to match the viewport mCamera->setAspectRatio( Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight())); //------------------------------------------------------------------------------------- // Set default mipmap level (NB some APIs ignore this) Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); //------------------------------------------------------------------------------------- // Create any resource listeners (for loading screens) //createResourceListener(); //------------------------------------------------------------------------------------- // load resources Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); //------------------------------------------------------------------------------------- // Create the scene Ogre::Entity* ogreHead = mSceneMgr->createEntity("Head", "ogrehead.mesh"); Ogre::SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); headNode->attachObject(ogreHead); // Set ambient light mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5)); // Create a light Ogre::Light* l = mSceneMgr->createLight("MainLight"); l->setPosition(20,80,50); //------------------------------------------------------------------------------------- btBroadphaseInterface* broadphase = new btDbvtBroadphase(); btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); dynamicsWorld->setGravity(btVector3(0, -10, 0)); btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1); btCollisionShape* fallShape = new btSphereShape(1); btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0))); btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0)); btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI); dynamicsWorld->addRigidBody(groundRigidBody); btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50, 0))); btScalar mass = 1; btVector3 fallInertia(0, 0, 0); fallShape->calculateLocalInertia(mass, fallInertia); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia); btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI); dynamicsWorld->addRigidBody(fallRigidBody); for (int i = 0; i < 300; i++) { dynamicsWorld->stepSimulation(1 / 60.f, 10); btTransform trans; fallRigidBody->getMotionState()->getWorldTransform(trans); std::cout << "sphere height: " << trans.getOrigin().getY() << std::endl; } dynamicsWorld->removeRigidBody(fallRigidBody); delete fallRigidBody->getMotionState(); delete fallRigidBody; dynamicsWorld->removeRigidBody(groundRigidBody); delete groundRigidBody->getMotionState(); delete groundRigidBody; delete fallShape; delete groundShape; delete dynamicsWorld; delete solver; delete collisionConfiguration; delete dispatcher; delete broadphase; while(true) { // Pump window messages for nice behaviour Ogre::WindowEventUtilities::messagePump(); if(mWindow->isClosed()) { return false; } // Render a frame if(!mRoot->renderOneFrame()) return false; } // We should never be able to reach this corner // but return true to calm down our compiler return true; } #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include "windows.h" #endif #ifdef __cplusplus extern "C" { #endif #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) #else int main(int argc, char *argv[]) #endif { // Create application object TinyOgre app; try { app.go(); } catch( Ogre::Exception& e ) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl; #endif } return 0; } #ifdef __cplusplus } #endif <commit_msg>Removed Windows-specific stuff regarding main()<commit_after>/* ----------------------------------------------------------------------------- Filename: TinyOgre.cpp ----------------------------------------------------------------------------- This source file is part of the ___ __ __ _ _ _ /___\__ _ _ __ ___ / / /\ \ (_) | _(_) // // _` | '__/ _ \ \ \/ \/ / | |/ / | / \_// (_| | | | __/ \ /\ /| | <| | \___/ \__, |_| \___| \/ \/ |_|_|\_\_| |___/ Tutorial Framework http://www.ogre3d.org/tikiwiki/ ----------------------------------------------------------------------------- */ #include "BaseApplication.h" #include "btBulletDynamicsCommon.h" #include <OgreLogManager.h> #include <OgreViewport.h> #include <OgreConfigFile.h> #include <OgreEntity.h> #include <OgreWindowEventUtilities.h> //------------------------------------------------------------------------------------- TinyOgre::TinyOgre(void) : mRoot(0), mCamera(0), mSceneMgr(0), mWindow(0), mResourcesCfg(Ogre::StringUtil::BLANK), mPluginsCfg(Ogre::StringUtil::BLANK) { } //------------------------------------------------------------------------------------- TinyOgre::~TinyOgre(void) { delete mRoot; } bool TinyOgre::go(void) { #ifdef _DEBUG mResourcesCfg = "resources_d.cfg"; mPluginsCfg = "plugins_d.cfg"; #else mResourcesCfg = "resources.cfg"; mPluginsCfg = "plugins.cfg"; #endif // construct Ogre::Root mRoot = new Ogre::Root(mPluginsCfg); //------------------------------------------------------------------------------------- // setup resources // Load resource paths from config file Ogre::ConfigFile cf; cf.load(mResourcesCfg); // Go through all sections & settings in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } //------------------------------------------------------------------------------------- // configure // Show the configuration dialog and initialise the system // You can skip this and use root.restoreConfig() to load configuration // settings if you were sure there are valid ones saved in ogre.cfg if(mRoot->restoreConfig() || mRoot->showConfigDialog()) { // If returned true, user clicked OK so initialise // Here we choose to let the system create a default rendering window by passing 'true' mWindow = mRoot->initialise(true, "TinyOgre Render Window"); } else { return false; } //------------------------------------------------------------------------------------- // choose scenemanager // Get the SceneManager, in this case a generic one mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC); //------------------------------------------------------------------------------------- // create camera // Create the camera mCamera = mSceneMgr->createCamera("PlayerCam"); // Position it at 500 in Z direction mCamera->setPosition(Ogre::Vector3(0,0,80)); // Look back along -Z mCamera->lookAt(Ogre::Vector3(0,0,-300)); mCamera->setNearClipDistance(5); //------------------------------------------------------------------------------------- // create viewports // Create one viewport, entire window Ogre::Viewport* vp = mWindow->addViewport(mCamera); vp->setBackgroundColour(Ogre::ColourValue(0,0,0)); // Alter the camera aspect ratio to match the viewport mCamera->setAspectRatio( Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight())); //------------------------------------------------------------------------------------- // Set default mipmap level (NB some APIs ignore this) Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); //------------------------------------------------------------------------------------- // Create any resource listeners (for loading screens) //createResourceListener(); //------------------------------------------------------------------------------------- // load resources Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); //------------------------------------------------------------------------------------- // Create the scene Ogre::Entity* ogreHead = mSceneMgr->createEntity("Head", "ogrehead.mesh"); Ogre::SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); headNode->attachObject(ogreHead); // Set ambient light mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5)); // Create a light Ogre::Light* l = mSceneMgr->createLight("MainLight"); l->setPosition(20,80,50); //------------------------------------------------------------------------------------- btBroadphaseInterface* broadphase = new btDbvtBroadphase(); btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); dynamicsWorld->setGravity(btVector3(0, -10, 0)); btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1); btCollisionShape* fallShape = new btSphereShape(1); btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0))); btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0)); btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI); dynamicsWorld->addRigidBody(groundRigidBody); btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50, 0))); btScalar mass = 1; btVector3 fallInertia(0, 0, 0); fallShape->calculateLocalInertia(mass, fallInertia); btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia); btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI); dynamicsWorld->addRigidBody(fallRigidBody); for (int i = 0; i < 300; i++) { dynamicsWorld->stepSimulation(1 / 60.f, 10); btTransform trans; fallRigidBody->getMotionState()->getWorldTransform(trans); std::cout << "sphere height: " << trans.getOrigin().getY() << std::endl; } dynamicsWorld->removeRigidBody(fallRigidBody); delete fallRigidBody->getMotionState(); delete fallRigidBody; dynamicsWorld->removeRigidBody(groundRigidBody); delete groundRigidBody->getMotionState(); delete groundRigidBody; delete fallShape; delete groundShape; delete dynamicsWorld; delete solver; delete collisionConfiguration; delete dispatcher; delete broadphase; while(true) { // Pump window messages for nice behaviour Ogre::WindowEventUtilities::messagePump(); if(mWindow->isClosed()) { return false; } // Render a frame if(!mRoot->renderOneFrame()) return false; } // We should never be able to reach this corner // but return true to calm down our compiler return true; } //#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 //#define WIN32_LEAN_AND_MEAN //#include "windows.h" //#endif #ifdef __cplusplus extern "C" { #endif int main(int argc, char *argv[]) { // Create application object TinyOgre app; try { app.go(); } catch( Ogre::Exception& e ) { std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl; } return 0; } #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>#include "Server.h" #include "defines.h" #include "ObjectManager.h" #include "Object.h" #include "Player.h" #include "Client.h" #include "Packet.h" #include "Grid.h" #include "Tools.h" #include "AuthDatabase.h" #include "CharactersDatabase.h" #include "Log.h" #include "debugging.h" //@ Net basic headers #include "Poco/Net/ParallelSocketReactor.h" #include "Poco/Net/SocketReactor.h" #include "Poco/Net/ParallelSocketAcceptor.h" #include "Poco/Net/SocketAcceptor.h" #include "Poco/Net/ServerSocket.h" using Poco::Net::SocketReactor; using Poco::Net::SocketAcceptor; using Poco::Net::ServerSocket; using Poco::Net::ParallelSocketReactor; using Poco::Net::ParallelSocketAcceptor; // Crypting #include <iostream> #include <iomanip> #include <files.h> #include <modes.h> #include <osrng.h> #include <sha.h> #include <aes.h> #include <hmac.h> #include <filters.h> enum HANDLE_IF_TYPE { TYPE_NULL = 0x00, TYPE_NO_HANDLE, TYPE_NOT_LOGGED_SKIP_HMAC, TYPE_NOT_LOGGED, TYPE_LOGGED, TYPE_IN_WORLD, TYPE_ALWAYS }; enum OPCODES { OPCODE_NULL = 0x00, // Server -> Client OPCODE_SC_EHLO = 0x9000, OPCODE_SC_TIME_OUT = 0x3001, OPCODE_SC_LOGIN_RESULT = 0x5101, OPCODE_SC_SEND_CHARACTERS_LIST = 0x5102, OPCODE_SC_SELECT_CHARACTER_RESULT = 0x5103, OPCODE_SC_CREATE_CHARACTER_RESULT = 0x5104, OPCODE_SC_SPAWN_OBJECT = 0x5201, OPCODE_SC_DESPAWN_OBJECT = 0x5202, OPCODE_SC_PLAYER_STATS = 0x5203, // Client -> Server OPCODE_CS_EHLO = 0x9000, OPCODE_CS_KEEP_ALIVE = 0x3000, OPCODE_CS_SEND_LOGIN = 0x3101, OPCODE_CS_REQUEST_CHARACTERS = 0x3102, OPCODE_CS_SELECT_CHARACTER = 0x3103, }; struct OpcodeHandleType { OPCODES Opcode; struct _Handler { bool (Server::*handler)(Client*, Packet*); HANDLE_IF_TYPE HandleIf; } Handler; }; const OpcodeHandleType Server::OpcodeTable[] = { // Client -> Server {OPCODE_CS_EHLO, {&Server::handlePlayerEHLO, TYPE_NOT_LOGGED_SKIP_HMAC }}, {OPCODE_CS_KEEP_ALIVE, {NULL, TYPE_ALWAYS }}, {OPCODE_CS_SEND_LOGIN, {&Server::handlePlayerLogin, TYPE_NOT_LOGGED }}, {OPCODE_CS_REQUEST_CHARACTERS, {&Server::handleRequestCharacters, TYPE_LOGGED }}, {OPCODE_CS_SELECT_CHARACTER, {&Server::handleCharacterSelect, TYPE_LOGGED }}, {OPCODE_NULL, {NULL, TYPE_NULL }}, }; #include <map> typedef std::map<OPCODES, OpcodeHandleType::_Handler> OpcodeHash; typedef std::pair<OPCODES, OpcodeHandleType::_Handler> OpcodeHashInserter; OpcodeHash OpcodesMap; /** * Creates a new Server and binds to the port * * @param port The port where the servers binds */ Server::Server(): _serverRunning(false) { // Create the Opcodes Map for (int i = 0; ; i++) { if (OpcodeTable[i].Opcode == OPCODE_NULL && OpcodeTable[i].Handler.HandleIf == TYPE_NULL && OpcodeTable[i].Handler.handler == NULL) break; OpcodesMap.insert(OpcodeHashInserter(OpcodeTable[i].Opcode, OpcodeTable[i].Handler)); } // Reset all players online state PreparedStatement* stmt = AuthDatabase.getPreparedStatement(QUERY_AUTH_UPDATE_ONLINE_ONSTART); stmt->execute(); } Server::~Server() { } void Server::start(Poco::UInt16 port) { // Create a server socket to listen. ServerSocket svs(port); // Create the reactor SocketReactor reactor(Poco::Timespan(15000000)); // Create a SocketAcceptor SocketAcceptor<Client> acceptor(svs, reactor); // Run the reactor in its own thread so that we can wait for a termination request Thread reactorThread; reactorThread.start(reactor); _serverRunning = true; while (_serverRunning) Thread::sleep(200); reactor.stop(); reactorThread.join(); } // Server -> Client packets void Server::SendPlayerEHLO(Client* client) { CryptoPP::AutoSeededRandomPool rng; Packet* packet = new Packet(OPCODE_SC_EHLO, 27); // 10 HMAC, 1 SEC, 16 AES Key for (Poco::UInt8 i = 0; i < 10; i++) *packet << rng.GenerateByte(); Poco::UInt32 sec = rng.GenerateByte() ; *packet << (Poco::UInt8)(sec & 0xFF); Poco::UInt8* key = client->GetAESKey(); for (Poco::UInt8 i = 0; i < 16; i++) { key[i] = rng.GenerateByte(); *packet << key[i]; } client->SetSecurityByte(sec); client->SetHMACKeyLow(packet->rawdata); client->sendPacket(packet, false, false); } void Server::SendClientDisconnected(Client* client) { Packet* packet = new Packet(OPCODE_SC_TIME_OUT); client->sendPacket(packet); } void Server::UpdateVisibilityOf(Object* from, Object* to) { sLog.out(Message::PRIO_TRACE, "Spawning %s to %s", Poco::NumberFormatter::formatHex(from->GetGUID()).c_str(), Poco::NumberFormatter::formatHex(to->GetGUID()).c_str()); Packet* packet = new Packet(OPCODE_SC_SPAWN_OBJECT, 2048, true); *packet << from->GetLowGUID(); *packet << from->GetHighGUID(); *packet << from->GetPosition().x; *packet << from->GetPosition().z; switch (from->GetHighGUID()) { case HIGH_GUID_CREATURE: case HIGH_GUID_PLAYER: { Character* character = from->ToCharacter(); *packet << character->GetName(); *packet << character->GetSpeed(MOVEMENT_RUN); *packet << character->GetSpeed(MOVEMENT_WALK); *packet << character->MovementTypeSpeed(); if (character->hasFlag(FLAGS_TYPE_MOVEMENT, FLAG_MOVING)) { *packet << Poco::UInt8(0x01); *packet << character->motionMaster.getMovementType(); if (character->motionMaster.getMovementType() == MOVEMENT_TO_POINT) { *packet << character->motionMaster.next().x; *packet << character->motionMaster.next().z; } else if (character->motionMaster.getMovementType() == MOVEMENT_BY_ANGLE) *packet << character->getFacingTo(); } else *packet << Poco::UInt8(0x00); *packet << character->GetMaxHP(); *packet << character->GetHP(); *packet << character->GetMaxMP(); *packet << character->GetMP(); break; } } if (Client* client = to->getClient()) client->sendPacket(packet); } void Server::sendDespawnPacket(Poco::UInt64 GUID, Object* to) { sLog.out(Message::PRIO_TRACE, "Despawning %s to %s", Poco::NumberFormatter::formatHex(GUID).c_str(), Poco::NumberFormatter::formatHex(to->GetGUID()).c_str()); Packet* packet = new Packet(OPCODE_SC_DESPAWN_OBJECT, 8); *packet << LOGUID(GUID); *packet << HIGUID(GUID); if (Client* client = to->getClient()) client->sendPacket(packet); } void Server::sendPlayerStats(Client* client, SharedPtr<Object> object) { // We should send the STR, INT, attack, defense, and private attributes here //@todo: All the params, right now we are only sending the player guid Packet* packet = new Packet(OPCODE_SC_PLAYER_STATS, 8); *packet << object->GetLowGUID(); *packet << object->GetHighGUID(); client->sendPacket(packet, true); } bool Server::parsePacket(Client* client, Packet* packet, Poco::UInt8 securityByte) { sLog.out(Message::PRIO_DEBUG, "[%d]\t[C->S] %.4X", client->GetId(), packet->opcode); OPCODES opcode = (OPCODES)packet->opcode; if (OpcodesMap.find(opcode) == OpcodesMap.end()) return false; // Check packet sec byte (Avoid packet reordering/inserting) if (packet->sec != securityByte) return false; // There are special packets which don't include HMAC (Avoid packet modifying) if (OpcodesMap[opcode].HandleIf != TYPE_NOT_LOGGED_SKIP_HMAC) if (!checkPacketHMAC(client, packet)) return false; if (packet->isEncrypted()) decryptPacket(client, packet); switch (OpcodesMap[opcode].HandleIf) { case TYPE_NULL: // This shouldn't be here return false; case TYPE_NO_HANDLE: return true; case TYPE_NOT_LOGGED_SKIP_HMAC: case TYPE_NOT_LOGGED: if (client->getLogged() || client->getInWorld()) return false; break; case TYPE_LOGGED: if (!client->getLogged() || client->getInWorld()) return false; break; case TYPE_IN_WORLD: if (!client->getInWorld()) return false; break; default: break; } if (!OpcodesMap[opcode].handler) // TODO: Report there's a missing function unless it's KEEP_ALIVE return true; return (this->*OpcodesMap[opcode].handler)(client, packet); } bool Server::checkPacketHMAC(Client* client, Packet* packet) { if (CryptoPP::HMAC<CryptoPP::SHA1>* verifier = client->getHMACVerifier()) return verifier->VerifyDigest(packet->digest, packet->rawdata, packet->getLength()); return false; } void Server::decryptPacket(Client* client, Packet* packet) { packet->len &= 0x5FFF; if (CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption* decryptor = client->getAESDecryptor()) decryptor->ProcessData(packet->rawdata, packet->rawdata, packet->len); } bool Server::handlePlayerEHLO(Client* client, Packet* packet) { client->SetHMACKeyHigh(packet->rawdata); client->SetupSecurity(); return true; } bool Server::handlePlayerLogin(Client* client, Packet* packet) { std::string username; std::string pass; *packet >> username; packet->readAsHex(pass, 16); // 0 1 // u.id, u.online PreparedStatement* stmt = AuthDatabase.getPreparedStatement(QUERY_AUTH_LOGIN); stmt->bindString(0, username); stmt->bindString(1, pass); RecordSet rs = stmt->execute(); Packet* resp = new Packet(OPCODE_SC_LOGIN_RESULT, 1); if (rs.moveFirst()) { client->setLogged(true); if (rs[1].convert<Poco::UInt8>() == 1) *resp << Poco::UInt8(0x02); // Already logged in else { *resp << Poco::UInt8(0x01); client->SetId(rs[0].convert<Poco::UInt32>()); // Set online status stmt = AuthDatabase.getPreparedStatement(QUERY_AUTH_UPDATE_ONLINE); stmt->bindUInt8(0, 0x01); stmt->bindUInt32(1, client->GetId()); stmt->execute(); } } else *resp << Poco::UInt8(0x00); // Write back client->sendPacket(resp); return true; } bool Server::handleRequestCharacters(Client* client, Packet* packet) { Poco::UInt8 request; *packet >> request; switch (request) { case 0x01: return sendCharactersList(client); break; case 0x02: return sendCharacterCreateResult(client, packet); default: return false; } return false; } bool Server::sendCharactersList(Client* client) { client->ClearCharacters(); Packet* resp = new Packet(OPCODE_SC_SEND_CHARACTERS_LIST, 1024, true); // 1 2 3 // c.id, c.model, c.name PreparedStatement* stmt = CharactersDatabase.getPreparedStatement(QUERY_CHARACTERS_SELECT_BASIC_INFORMATION); stmt->bindUInt32(0, client->GetId()); RecordSet rs = stmt->execute(); *resp << Poco::UInt8(rs.rowCount()); if (rs.moveFirst()) { do { Characters character = {rs[0].convert<Poco::UInt32>(), rs[1].convert<Poco::UInt32>(), rs[2].convert<std::string>()}; client->AddCharacter(character); *resp << character.id; *resp << character.model; *resp << character.name; PreparedStatement* stmtItems = CharactersDatabase.getPreparedStatement(QUERY_CHARACTERS_SELECT_VISIBLE_EQUIPMENT); stmtItems->bindUInt32(0, client->GetId()); RecordSet rsItems = stmtItems->execute(); if (rsItems.moveFirst()) { do { *resp << Poco::UInt8(0x01); *resp << rsItems[0].convert<Poco::UInt32>(); } while (rsItems.moveNext()); } *resp << Poco::UInt8(0x00); } while (rs.moveNext()); } client->sendPacket(resp, true); return true; } bool Server::handleCharacterSelect(Client* client, Packet* packet) { Poco::UInt32 characterID; *packet >> characterID; Packet* resp = new Packet(OPCODE_SC_SELECT_CHARACTER_RESULT, 1); Characters* character = client->FindCharacter(characterID); if (character) *resp << Poco::UInt8(0x01); else *resp << Poco::UInt8(0x00); client->sendPacket(resp); if (character) { OnEnterToWorld(client, characterID); return true; } return false; } bool Server::sendCharacterCreateResult(Client* client, Packet* packet) { //Packet* resp = new Packet(OPCODE_SC_SEND_CHARACTERS_LIST, 1024, true); return true; } void Server::OnEnterToWorld(Client* client, Poco::UInt32 characterID) { // Create the player (Object) and add it to the object list SharedPtr<Player> player = client->onEnterToWorld(characterID); if (!player.isNull()) { client->setInWorld(true); // Send player information sendPlayerStats(client, player); // Add the player to the GridLoader system sGridLoader.addObject(player); // Send an spawn packet of itself UpdateVisibilityOf(player, player); } else { //@todo: Notify player that he can't connect //@todo: time out client } } <commit_msg>Minor: Codestyle<commit_after>#include "Server.h" #include "defines.h" #include "ObjectManager.h" #include "Object.h" #include "Player.h" #include "Client.h" #include "Packet.h" #include "Grid.h" #include "Tools.h" #include "AuthDatabase.h" #include "CharactersDatabase.h" #include "Log.h" #include "debugging.h" //@ Net basic headers #include "Poco/Net/ParallelSocketReactor.h" #include "Poco/Net/SocketReactor.h" #include "Poco/Net/ParallelSocketAcceptor.h" #include "Poco/Net/SocketAcceptor.h" #include "Poco/Net/ServerSocket.h" using Poco::Net::SocketReactor; using Poco::Net::SocketAcceptor; using Poco::Net::ServerSocket; using Poco::Net::ParallelSocketReactor; using Poco::Net::ParallelSocketAcceptor; // Crypting #include <iostream> #include <iomanip> #include <files.h> #include <modes.h> #include <osrng.h> #include <sha.h> #include <aes.h> #include <hmac.h> #include <filters.h> enum HANDLE_IF_TYPE { TYPE_NULL = 0x00, TYPE_NO_HANDLE, TYPE_NOT_LOGGED_SKIP_HMAC, TYPE_NOT_LOGGED, TYPE_LOGGED, TYPE_IN_WORLD, TYPE_ALWAYS }; enum OPCODES { OPCODE_NULL = 0x00, // Server -> Client OPCODE_SC_EHLO = 0x9000, OPCODE_SC_TIME_OUT = 0x3001, OPCODE_SC_LOGIN_RESULT = 0x5101, OPCODE_SC_SEND_CHARACTERS_LIST = 0x5102, OPCODE_SC_SELECT_CHARACTER_RESULT = 0x5103, OPCODE_SC_CREATE_CHARACTER_RESULT = 0x5104, OPCODE_SC_SPAWN_OBJECT = 0x5201, OPCODE_SC_DESPAWN_OBJECT = 0x5202, OPCODE_SC_PLAYER_STATS = 0x5203, // Client -> Server OPCODE_CS_EHLO = 0x9000, OPCODE_CS_KEEP_ALIVE = 0x3000, OPCODE_CS_SEND_LOGIN = 0x3101, OPCODE_CS_REQUEST_CHARACTERS = 0x3102, OPCODE_CS_SELECT_CHARACTER = 0x3103, }; struct OpcodeHandleType { OPCODES Opcode; struct _Handler { bool (Server::*handler)(Client*, Packet*); HANDLE_IF_TYPE HandleIf; } Handler; }; const OpcodeHandleType Server::OpcodeTable[] = { // Client -> Server {OPCODE_CS_EHLO, {&Server::handlePlayerEHLO, TYPE_NOT_LOGGED_SKIP_HMAC }}, {OPCODE_CS_KEEP_ALIVE, {NULL, TYPE_ALWAYS }}, {OPCODE_CS_SEND_LOGIN, {&Server::handlePlayerLogin, TYPE_NOT_LOGGED }}, {OPCODE_CS_REQUEST_CHARACTERS, {&Server::handleRequestCharacters, TYPE_LOGGED }}, {OPCODE_CS_SELECT_CHARACTER, {&Server::handleCharacterSelect, TYPE_LOGGED }}, {OPCODE_NULL, {NULL, TYPE_NULL }}, }; #include <map> typedef std::map<OPCODES, OpcodeHandleType::_Handler> OpcodeHash; typedef std::pair<OPCODES, OpcodeHandleType::_Handler> OpcodeHashInserter; OpcodeHash OpcodesMap; /** * Creates a new Server and binds to the port * * @param port The port where the servers binds */ Server::Server(): _serverRunning(false) { // Create the Opcodes Map for (int i = 0; ; i++) { if (OpcodeTable[i].Opcode == OPCODE_NULL && OpcodeTable[i].Handler.HandleIf == TYPE_NULL && OpcodeTable[i].Handler.handler == NULL) break; OpcodesMap.insert(OpcodeHashInserter(OpcodeTable[i].Opcode, OpcodeTable[i].Handler)); } // Reset all players online state PreparedStatement* stmt = AuthDatabase.getPreparedStatement(QUERY_AUTH_UPDATE_ONLINE_ONSTART); stmt->execute(); } Server::~Server() { } void Server::start(Poco::UInt16 port) { // Create a server socket to listen. ServerSocket svs(port); // Create the reactor SocketReactor reactor(Poco::Timespan(15000000)); // Create a SocketAcceptor SocketAcceptor<Client> acceptor(svs, reactor); // Run the reactor in its own thread so that we can wait for a termination request Thread reactorThread; reactorThread.start(reactor); _serverRunning = true; while (_serverRunning) Thread::sleep(200); reactor.stop(); reactorThread.join(); } // Server -> Client packets void Server::SendPlayerEHLO(Client* client) { CryptoPP::AutoSeededRandomPool rng; Packet* packet = new Packet(OPCODE_SC_EHLO, 27); // 10 HMAC, 1 SEC, 16 AES Key for (Poco::UInt8 i = 0; i < 10; i++) *packet << rng.GenerateByte(); Poco::UInt32 sec = rng.GenerateByte(); *packet << (Poco::UInt8)(sec & 0xFF); Poco::UInt8* key = client->GetAESKey(); for (Poco::UInt8 i = 0; i < 16; i++) { key[i] = rng.GenerateByte(); *packet << key[i]; } client->SetSecurityByte(sec); client->SetHMACKeyLow(packet->rawdata); client->sendPacket(packet, false, false); } void Server::SendClientDisconnected(Client* client) { Packet* packet = new Packet(OPCODE_SC_TIME_OUT); client->sendPacket(packet); } void Server::UpdateVisibilityOf(Object* from, Object* to) { sLog.out(Message::PRIO_TRACE, "Spawning %s to %s", Poco::NumberFormatter::formatHex(from->GetGUID()).c_str(), Poco::NumberFormatter::formatHex(to->GetGUID()).c_str()); Packet* packet = new Packet(OPCODE_SC_SPAWN_OBJECT, 2048, true); *packet << from->GetLowGUID(); *packet << from->GetHighGUID(); *packet << from->GetPosition().x; *packet << from->GetPosition().z; switch (from->GetHighGUID()) { case HIGH_GUID_CREATURE: case HIGH_GUID_PLAYER: { Character* character = from->ToCharacter(); *packet << character->GetName(); *packet << character->GetSpeed(MOVEMENT_RUN); *packet << character->GetSpeed(MOVEMENT_WALK); *packet << character->MovementTypeSpeed(); if (character->hasFlag(FLAGS_TYPE_MOVEMENT, FLAG_MOVING)) { *packet << Poco::UInt8(0x01); *packet << character->motionMaster.getMovementType(); if (character->motionMaster.getMovementType() == MOVEMENT_TO_POINT) { *packet << character->motionMaster.next().x; *packet << character->motionMaster.next().z; } else if (character->motionMaster.getMovementType() == MOVEMENT_BY_ANGLE) *packet << character->getFacingTo(); } else *packet << Poco::UInt8(0x00); *packet << character->GetMaxHP(); *packet << character->GetHP(); *packet << character->GetMaxMP(); *packet << character->GetMP(); break; } } if (Client* client = to->getClient()) client->sendPacket(packet); } void Server::sendDespawnPacket(Poco::UInt64 GUID, Object* to) { sLog.out(Message::PRIO_TRACE, "Despawning %s to %s", Poco::NumberFormatter::formatHex(GUID).c_str(), Poco::NumberFormatter::formatHex(to->GetGUID()).c_str()); Packet* packet = new Packet(OPCODE_SC_DESPAWN_OBJECT, 8); *packet << LOGUID(GUID); *packet << HIGUID(GUID); if (Client* client = to->getClient()) client->sendPacket(packet); } void Server::sendPlayerStats(Client* client, SharedPtr<Object> object) { // We should send the STR, INT, attack, defense, and private attributes here //@todo: All the params, right now we are only sending the player guid Packet* packet = new Packet(OPCODE_SC_PLAYER_STATS, 8); *packet << object->GetLowGUID(); *packet << object->GetHighGUID(); client->sendPacket(packet, true); } bool Server::parsePacket(Client* client, Packet* packet, Poco::UInt8 securityByte) { sLog.out(Message::PRIO_DEBUG, "[%d]\t[C->S] %.4X", client->GetId(), packet->opcode); OPCODES opcode = (OPCODES)packet->opcode; if (OpcodesMap.find(opcode) == OpcodesMap.end()) return false; // Check packet sec byte (Avoid packet reordering/inserting) if (packet->sec != securityByte) return false; // There are special packets which don't include HMAC (Avoid packet modifying) if (OpcodesMap[opcode].HandleIf != TYPE_NOT_LOGGED_SKIP_HMAC) if (!checkPacketHMAC(client, packet)) return false; if (packet->isEncrypted()) decryptPacket(client, packet); switch (OpcodesMap[opcode].HandleIf) { case TYPE_NULL: // This shouldn't be here return false; case TYPE_NO_HANDLE: return true; case TYPE_NOT_LOGGED_SKIP_HMAC: case TYPE_NOT_LOGGED: if (client->getLogged() || client->getInWorld()) return false; break; case TYPE_LOGGED: if (!client->getLogged() || client->getInWorld()) return false; break; case TYPE_IN_WORLD: if (!client->getInWorld()) return false; break; default: break; } if (!OpcodesMap[opcode].handler) // TODO: Report there's a missing function unless it's KEEP_ALIVE return true; return (this->*OpcodesMap[opcode].handler)(client, packet); } bool Server::checkPacketHMAC(Client* client, Packet* packet) { if (CryptoPP::HMAC<CryptoPP::SHA1>* verifier = client->getHMACVerifier()) return verifier->VerifyDigest(packet->digest, packet->rawdata, packet->getLength()); return false; } void Server::decryptPacket(Client* client, Packet* packet) { packet->len &= 0x5FFF; if (CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption* decryptor = client->getAESDecryptor()) decryptor->ProcessData(packet->rawdata, packet->rawdata, packet->len); } bool Server::handlePlayerEHLO(Client* client, Packet* packet) { client->SetHMACKeyHigh(packet->rawdata); client->SetupSecurity(); return true; } bool Server::handlePlayerLogin(Client* client, Packet* packet) { std::string username; std::string pass; *packet >> username; packet->readAsHex(pass, 16); // 0 1 // u.id, u.online PreparedStatement* stmt = AuthDatabase.getPreparedStatement(QUERY_AUTH_LOGIN); stmt->bindString(0, username); stmt->bindString(1, pass); RecordSet rs = stmt->execute(); Packet* resp = new Packet(OPCODE_SC_LOGIN_RESULT, 1); if (rs.moveFirst()) { client->setLogged(true); if (rs[1].convert<Poco::UInt8>() == 1) *resp << Poco::UInt8(0x02); // Already logged in else { *resp << Poco::UInt8(0x01); client->SetId(rs[0].convert<Poco::UInt32>()); // Set online status stmt = AuthDatabase.getPreparedStatement(QUERY_AUTH_UPDATE_ONLINE); stmt->bindUInt8(0, 0x01); stmt->bindUInt32(1, client->GetId()); stmt->execute(); } } else *resp << Poco::UInt8(0x00); // Write back client->sendPacket(resp); return true; } bool Server::handleRequestCharacters(Client* client, Packet* packet) { Poco::UInt8 request; *packet >> request; switch (request) { case 0x01: return sendCharactersList(client); break; case 0x02: return sendCharacterCreateResult(client, packet); default: return false; } return false; } bool Server::sendCharactersList(Client* client) { client->ClearCharacters(); Packet* resp = new Packet(OPCODE_SC_SEND_CHARACTERS_LIST, 1024, true); // 1 2 3 // c.id, c.model, c.name PreparedStatement* stmt = CharactersDatabase.getPreparedStatement(QUERY_CHARACTERS_SELECT_BASIC_INFORMATION); stmt->bindUInt32(0, client->GetId()); RecordSet rs = stmt->execute(); *resp << Poco::UInt8(rs.rowCount()); if (rs.moveFirst()) { do { Characters character = {rs[0].convert<Poco::UInt32>(), rs[1].convert<Poco::UInt32>(), rs[2].convert<std::string>()}; client->AddCharacter(character); *resp << character.id; *resp << character.model; *resp << character.name; PreparedStatement* stmtItems = CharactersDatabase.getPreparedStatement(QUERY_CHARACTERS_SELECT_VISIBLE_EQUIPMENT); stmtItems->bindUInt32(0, client->GetId()); RecordSet rsItems = stmtItems->execute(); if (rsItems.moveFirst()) { do { *resp << Poco::UInt8(0x01); *resp << rsItems[0].convert<Poco::UInt32>(); } while (rsItems.moveNext()); } *resp << Poco::UInt8(0x00); } while (rs.moveNext()); } client->sendPacket(resp, true); return true; } bool Server::handleCharacterSelect(Client* client, Packet* packet) { Poco::UInt32 characterID; *packet >> characterID; Packet* resp = new Packet(OPCODE_SC_SELECT_CHARACTER_RESULT, 1); Characters* character = client->FindCharacter(characterID); if (character) *resp << Poco::UInt8(0x01); else *resp << Poco::UInt8(0x00); client->sendPacket(resp); if (character) { OnEnterToWorld(client, characterID); return true; } return false; } bool Server::sendCharacterCreateResult(Client* client, Packet* packet) { //Packet* resp = new Packet(OPCODE_SC_SEND_CHARACTERS_LIST, 1024, true); return true; } void Server::OnEnterToWorld(Client* client, Poco::UInt32 characterID) { // Create the player (Object) and add it to the object list SharedPtr<Player> player = client->onEnterToWorld(characterID); if (!player.isNull()) { client->setInWorld(true); // Send player information sendPlayerStats(client, player); // Add the player to the GridLoader system sGridLoader.addObject(player); // Send an spawn packet of itself UpdateVisibilityOf(player, player); } else { //@todo: Notify player that he can't connect //@todo: time out client } } <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2010 Dreamhost * * This 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. See file COPYING. * */ #include <fcntl.h> #include <iostream> #include <string> #include <sys/stat.h> #include <sys/types.h> #include "mon/AuthMonitor.h" #include "common/ConfUtils.h" #include "common/common_init.h" #include "config.h" #include "include/str_list.h" const char *type = NULL; static void usage() { // TODO: add generic_usage once cerr/derr issues are resolved cerr << "Ceph configuration query tool\n\ \n\ USAGE\n\ cconf <flags> <action>\n\ \n\ ACTIONS\n\ -l|--list-sections <prefix> List sections in prefix\n\ \n\ --lookup <key> [defval] Print a configuration setting to stdout.\n\ If the setting is not defined, and the\n\ optional argument defval is provide, it will\n\ be printed instead. variables in defval are\n\ interpolated.\n\ \n\ FLAGS\n\ -i id Set id\n\ [-s <section>] Add to list of sections to search\n\ \n\ If there is no action given, the action will default to --lookup.\n\ \n\ EXAMPLES\n\ $ cconf -i cconf -c /etc/ceph/ceph.conf -t mon -i 0 'mon addr'\n\ Find out if there is a 'mon addr' defined in /etc/ceph/ceph.conf\n\ \n\ $ cconf -l mon\n\ List sections beginning with 'mon'.\n\ \n\ RETURN CODE\n\ Return code will be 0 on success; error code otherwise.\n\ "; exit(1); } static int list_sections(const char *s) { ConfFile *cf = conf_get_conf_file(); if (!cf) return 2; for (std::list<ConfSection*>::const_iterator p = cf->get_section_list().begin(); p != cf->get_section_list().end(); ++p) { if (strncmp(s, (*p)->get_name().c_str(), strlen(s)) == 0) cout << (*p)->get_name() << std::endl; } return 0; } static int lookup_impl(const deque<const char *> &sections, const char *key, const char *defval) { char *val = NULL; ConfFile *cf = conf_get_conf_file(); if (!cf) return 2; conf_read_key(NULL, key, OPT_STR, (char **)&val, NULL); if (val) { puts(val); free(val); return 0; } for (unsigned int i=0; i<sections.size(); i++) { cf->read(sections[i], key, (char **)&val, NULL); if (val) { puts(val); free(val); return 0; } } if (defval) { val = conf_post_process_val(defval); if (val) { puts(val); free(val); return 0; } } { // TODO: document exactly what we are doing here? std::vector<const char *> empty_args; parse_startup_config_options(empty_args, type); char buf[1024]; memset(buf, 0, sizeof(buf)); if (ceph_def_conf_by_name(key, buf, sizeof(buf))) { cout << buf << std::endl; return 0; } } return 1; } static int lookup(const deque<const char *> &sections, const vector<const char*> &nargs, vector<const char*>::const_iterator n) { const char *key = *n; ++n; if (n == nargs.end()) return lookup_impl(sections, key, NULL); const char *defval = *n; ++n; if (n == nargs.end()) return lookup_impl(sections, key, defval); cerr << "lookup: Too many arguments. Expected only 1 or 2." << std::endl; usage(); return 1; } int main(int argc, const char **argv) { char *section; vector<const char*> args, nargs; deque<const char *> sections; DEFINE_CONF_VARS(usage); argv_to_vec(argc, argv, args); env_to_vec(args); FOR_EACH_ARG(args) { if (CONF_ARG_EQ("type", 't')) { CONF_SAFE_SET_ARG_VAL(&type, OPT_STR); } else if (CONF_ARG_EQ("id", 'i')) { CONF_SAFE_SET_ARG_VAL(&g_conf.id, OPT_STR); } else if (CONF_ARG_EQ("section", 's')) { CONF_SAFE_SET_ARG_VAL(&section, OPT_STR); sections.push_back(section); } else { nargs.push_back(args[i]); } } common_set_defaults(false); common_init(nargs, type, false); set_foreground_logging(); if ((nargs.size() == 1) && (!strcmp(nargs[0], "-h"))) { usage(); } else if ((nargs.size() == 2) && (!strcmp(nargs[0], "--list_sections") || !strcmp(nargs[0], "-l"))) { return list_sections(nargs[1]); } else if ((nargs.size() >= 2) && (!strcmp(nargs[0], "--lookup"))) { vector<const char*>::const_iterator n = nargs.begin(); ++n; return lookup(sections, nargs, n); } else if ((nargs.size() >= 1) && (nargs[0][0] == '-')) { cerr << "Parse error at argument: " << nargs[0] << std::endl; usage(); } else { vector<const char*>::const_iterator n = nargs.begin(); return lookup(sections, nargs, n); } } <commit_msg>cconf: fix usage parsing, add --resolve search<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2010 Dreamhost * * This 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. See file COPYING. * */ #include <fcntl.h> #include <iostream> #include <string> #include <sys/stat.h> #include <sys/types.h> #include "mon/AuthMonitor.h" #include "common/ConfUtils.h" #include "common/common_init.h" #include "config.h" #include "include/str_list.h" const char *type = NULL; static void usage() { // TODO: add generic_usage once cerr/derr issues are resolved cerr << "Ceph configuration query tool\n\ \n\ USAGE\n\ cconf <flags> <action>\n\ \n\ ACTIONS\n\ -l|--list-sections <prefix> List sections in prefix\n\ --lookup <key> [defval] Print a configuration setting to stdout.\n\ If the setting is not defined, and the\n\ optional argument defval is provide, it will\n\ be printed instead. variables in defval are\n\ interpolated.\n\ -r|--resolve-search search for the first file that exists and\n\ can be opened in the resulted comma\n\ delimited search list.\n\ \n\ FLAGS\n\ -i id Set id\n\ [-s <section>] Add to list of sections to search\n\ \n\ If there is no action given, the action will default to --lookup.\n\ \n\ EXAMPLES\n\ $ cconf -i cconf -c /etc/ceph/ceph.conf -t mon -i 0 'mon addr'\n\ Find out if there is a 'mon addr' defined in /etc/ceph/ceph.conf\n\ \n\ $ cconf -l mon\n\ List sections beginning with 'mon'.\n\ \n\ RETURN CODE\n\ Return code will be 0 on success; error code otherwise.\n\ "; } void error_exit() { usage(); exit(1); } static int list_sections(const char *s) { ConfFile *cf = conf_get_conf_file(); if (!cf) return 2; for (std::list<ConfSection*>::const_iterator p = cf->get_section_list().begin(); p != cf->get_section_list().end(); ++p) { if (strncmp(s, (*p)->get_name().c_str(), strlen(s)) == 0) cout << (*p)->get_name() << std::endl; } return 0; } static void print_val(const char *val, bool resolve_search) { if (!resolve_search) { puts(val); } else { string search_path(val); string result; if (ceph_resolve_file_search(search_path, result)) puts(result.c_str()); } } static int lookup_impl(const deque<const char *> &sections, const char *key, const char *defval, bool resolve_search) { char *val = NULL; ConfFile *cf = conf_get_conf_file(); if (!cf) return 2; conf_read_key(NULL, key, OPT_STR, (char **)&val, NULL); if (val) { print_val(val, resolve_search); free(val); return 0; } for (unsigned int i=0; i<sections.size(); i++) { cf->read(sections[i], key, (char **)&val, NULL); if (val) { print_val(val, resolve_search); free(val); return 0; } } if (defval) { val = conf_post_process_val(defval); if (val) { print_val(val, resolve_search); free(val); return 0; } } { // TODO: document exactly what we are doing here? std::vector<const char *> empty_args; parse_startup_config_options(empty_args, type); char buf[1024]; memset(buf, 0, sizeof(buf)); if (ceph_def_conf_by_name(key, buf, sizeof(buf))) { print_val(buf, resolve_search); return 0; } } return 1; } static int lookup(const deque<const char *> &sections, const vector<const char*> &nargs, vector<const char*>::const_iterator n, bool resolve_search) { const char *key = *n; ++n; if (n == nargs.end()) return lookup_impl(sections, key, NULL, resolve_search); const char *defval = *n; ++n; if (n == nargs.end()) return lookup_impl(sections, key, defval, resolve_search); cerr << "lookup: Too many arguments. Expected only 1 or 2." << std::endl; error_exit(); return 1; } int main(int argc, const char **argv) { char *section; vector<const char*> args, nargs; deque<const char *> sections; DEFINE_CONF_VARS(usage); bool resolve_search = false; bool do_help = false; bool do_list = false; bool do_lookup = false; argv_to_vec(argc, argv, args); env_to_vec(args); FOR_EACH_ARG(args) { if (CONF_ARG_EQ("type", 't')) { CONF_SAFE_SET_ARG_VAL(&type, OPT_STR); } else if (CONF_ARG_EQ("id", 'i')) { CONF_SAFE_SET_ARG_VAL(&g_conf.id, OPT_STR); } else if (CONF_ARG_EQ("section", 's')) { CONF_SAFE_SET_ARG_VAL(&section, OPT_STR); sections.push_back(section); } else if (CONF_ARG_EQ("resolve-search", 'r')) { CONF_SAFE_SET_ARG_VAL(&resolve_search, OPT_BOOL); } else if (CONF_ARG_EQ("help", 'h')) { CONF_SAFE_SET_ARG_VAL(&do_help, OPT_BOOL); } else if (CONF_ARG_EQ("list-sections", 'l')) { CONF_SAFE_SET_ARG_VAL(&do_list, OPT_BOOL); } else if (CONF_ARG_EQ("lookup", '\0')) { CONF_SAFE_SET_ARG_VAL(&do_lookup, OPT_BOOL); } else { nargs.push_back(args[i]); } } common_set_defaults(false); common_init(nargs, type, false); set_foreground_logging(); if (do_help) { usage(); exit(0); } if (!do_lookup && !do_list) do_lookup = true; if (do_list) { if (nargs.size() != 1) error_exit(); return list_sections(nargs[0]); } else if (do_lookup) { if (nargs.size() < 1 || nargs.size() > 2) error_exit(); vector<const char*>::const_iterator n = nargs.begin(); return lookup(sections, nargs, n, resolve_search); } else if ((nargs.size() >= 1) && (nargs[0][0] == '-')) { cerr << "Parse error at argument: " << nargs[0] << std::endl; error_exit(); } else { vector<const char*>::const_iterator n = nargs.begin(); return lookup(sections, nargs, n, resolve_search); } } <|endoftext|>
<commit_before>#include "Cell.h" #include <cstdlib> #include <cassert> cigma::Cell::Cell() { nsd = -1; celldim = -1; nno = 0; globverts = NULL; refverts = NULL; ndofs = 0; basis_tab = NULL; basis_jet = NULL; nq = 0; jxw = NULL; qpts = NULL; qwts = NULL; gqpts = NULL; _tabulate = false; } cigma::Cell::~Cell() { } //---------------------------------------------------------------------------- void cigma::Cell::clear(void) { globverts = NULL; } void cigma::Cell::set(int nsd, int celldim, int ndofs) { this->nsd = nsd; this->celldim = celldim; this->ndofs = ndofs; } void cigma::Cell::set_reference_vertices(const double *vertices, int num_vertices) { assert(nsd > 0); assert(celldim > 0); nno = num_vertices; refverts = new double[nno*celldim]; for (int i = 0; i < nno; i++) { for(int j = 0; j < celldim; j++) { int n = celldim*i + j; refverts[n] = vertices[n]; } } } void cigma::Cell::update_vertices(double *vertices, int num_vertices, int nsd) { assert((this->nsd) == nsd); assert(nno == num_vertices); this->globverts = vertices; } void cigma::Cell::set_quadrature(const double *quadpts, const double *quadwts, int num_points) { assert(nsd > 0); nq = num_points; qwts = new double[nq]; qpts = new double[nq*celldim]; gqpts = new double[nq*nsd]; for (int q = 0; q < nq; q++) { qwts[q] = quadwts[q]; for (int i = 0; i < celldim; i++) { int n = celldim*q + i; qpts[n] = quadpts[n]; } } if (basis_tab != NULL) { update_quadrature(); } } void cigma::Cell::update_quadrature(void) { assert(nsd > 0); assert(nq > 0); for (int q = 0; q < nq; q++) uvw2xyz(&qpts[celldim*q], &gqpts[nsd*q]); } //---------------------------------------------------------------------------- double cigma::Cell::jacobian(double *point, double jac[3][3]) { assert(celldim > 0); switch (celldim) { case 3: return jacobian(point[0], point[1], point[2], jac); case 2: return jacobian(point[0], point[1], 0.0, jac); case 1: return jacobian(point[0], 0.0, 0.0, jac); } assert(false); return 0.0; } double cigma::Cell::jacobian(double u, double v, double w, double jac[3][3]) { jac[0][0] = jac[0][1] = jac[0][2] = 0.0; jac[1][0] = jac[1][1] = jac[1][2] = 0.0; jac[2][0] = jac[2][1] = jac[2][2] = 0.0; /* double s[3]; switch (celldim) { case 3: case 2: case 1: default: assert(false); };*/ return 0.0; } /* * \tilde{\phi}(x) = \sum_{i} d_i N_i(\xi(x)) * @param valdim dimension of value points * @param dofs dofs is a rank-2 array of dimension [ndofs x valdim] * @param point point is a rank-1 array of dimension [celldim] * @param value value is a rank-1 array of dimension [valdim] */ void cigma::Cell::interpolate(double *dofs, double *point, double *value, int valdim) { double N[ndofs]; shape(1, point, N); // value[i] = N[0]*dofs[0,i] + N[1]*dofs[1,i] + ... for (int i = 0; i < valdim; i++) { double sum = 0.0; for (int j = 0; j < ndofs; j++) sum += dofs[i + valdim*j] * N[j]; value[i] = sum; } } /* isoparametric reference map */ void cigma::Cell::uvw2xyz(double uvw[3], double xyz[3]) { interpolate(globverts, uvw, xyz, 3); } void cigma::Cell::bbox(double *min, double *max) { minmax(globverts, nno, nsd, min, max); } void cigma::Cell::centroid(double c[3]) { cigma::centroid(globverts, nno, nsd, c); } <commit_msg>Generic cell methods, using shape() and grad_shape() from children classes<commit_after>#include "Cell.h" #include <cstdlib> #include <cassert> cigma::Cell::Cell() { nsd = -1; celldim = -1; nno = 0; globverts = NULL; refverts = NULL; ndofs = 0; basis_tab = NULL; basis_jet = NULL; nq = 0; jxw = NULL; qpts = NULL; qwts = NULL; gqpts = NULL; _tabulate = false; } cigma::Cell::~Cell() { } //---------------------------------------------------------------------------- void cigma::Cell::clear(void) { globverts = NULL; } void cigma::Cell::set(int nsd, int celldim, int ndofs) { this->nsd = nsd; this->celldim = celldim; this->ndofs = ndofs; } void cigma::Cell::set_reference_vertices(const double *vertices, int num_vertices) { assert(nsd > 0); assert(celldim > 0); nno = num_vertices; refverts = new double[nno*celldim]; for (int i = 0; i < nno; i++) { for(int j = 0; j < celldim; j++) { int n = celldim*i + j; refverts[n] = vertices[n]; } } } void cigma::Cell::update_vertices(double *vertices, int num_vertices, int nsd) { assert((this->nsd) == nsd); assert(nno == num_vertices); this->globverts = vertices; } void cigma::Cell::set_quadrature(const double *quadpts, const double *quadwts, int num_points) { assert(nsd > 0); nq = num_points; qwts = new double[nq]; qpts = new double[nq*celldim]; gqpts = new double[nq*nsd]; for (int q = 0; q < nq; q++) { qwts[q] = quadwts[q]; for (int i = 0; i < celldim; i++) { int n = celldim*q + i; qpts[n] = quadpts[n]; } } if (basis_tab != NULL) { update_quadrature(); } } void cigma::Cell::update_quadrature(void) { assert(nsd > 0); assert(nq > 0); for (int q = 0; q < nq; q++) uvw2xyz(&qpts[celldim*q], &gqpts[nsd*q]); } //---------------------------------------------------------------------------- double cigma::Cell::jacobian(double *point, double jac[3][3]) { assert(celldim > 0); switch (celldim) { case 3: return jacobian(point[0], point[1], point[2], jac); case 2: return jacobian(point[0], point[1], 0.0, jac); case 1: return jacobian(point[0], 0.0, 0.0, jac); } assert(false); return 0.0; } double cigma::Cell::jacobian(double u, double v, double w, double jac[3][3]) { jac[0][0] = jac[0][1] = jac[0][2] = 0.0; jac[1][0] = jac[1][1] = jac[1][2] = 0.0; jac[2][0] = jac[2][1] = jac[2][2] = 0.0; #define X(i) globverts[3*(i) + 0] #define Y(i) globverts[3*(i) + 1] #define Z(i) globverts[3*(i) + 2] double uvw[3] = {u,v,w}; double *grad = new double[ndofs*3]; double *s; switch (nsd) { case 3 : grad_shape(1, uvw, grad); for(int i = 0; i < n_nodes(); i++) { s = &grad[3*i]; jac[0][0] += X(i) * s[0]; jac[0][1] += Y(i) * s[0]; jac[0][2] += Z(i) * s[0]; jac[1][0] += X(i) * s[1]; jac[1][1] += Y(i) * s[1]; jac[1][2] += Z(i) * s[1]; jac[2][0] += X(i) * s[2]; jac[2][1] += Y(i) * s[2]; jac[2][2] += Z(i) * s[2]; } return fabs( + jac[0][0] * jac[1][1] * jac[2][2] + jac[0][2] * jac[1][0] * jac[2][1] + jac[0][1] * jac[1][2] * jac[2][0] - jac[0][2] * jac[1][1] * jac[2][0] - jac[0][0] * jac[1][2] * jac[2][1] - jac[0][1] * jac[1][0] * jac[2][2]); case 2 : grad_shape(1, uvw, grad); for(int i = 0; i < n_nodes(); i++) { s = &grad[2*i]; jac[0][0] += X(i) * s[0]; jac[0][1] += Y(i) * s[0]; jac[0][2] += Z(i) * s[0]; jac[1][0] += X(i) * s[1]; jac[1][1] += Y(i) * s[1]; jac[1][2] += Z(i) * s[1]; } { double a[3], b[3], c[3]; a[0]= X(1) - X(0); a[1]= Y(1) - Y(0); a[2]= Z(1) - Z(0); b[0]= X(2) - X(0); b[1]= Y(2) - Y(0); b[2]= Z(2) - Z(0); prodve(a, b, c); jac[2][0] = c[0]; jac[2][1] = c[1]; jac[2][2] = c[2]; } return sqrt(SQR(jac[0][0] * jac[1][1] - jac[0][1] * jac[1][0]) + SQR(jac[0][2] * jac[1][0] - jac[0][0] * jac[1][2]) + SQR(jac[0][1] * jac[1][2] - jac[0][2] * jac[1][1])); case 1: grad_shape(1, uvw, grad); for(int i = 0; i < n_nodes(); i++) { s = &grad[i]; jac[0][0] += X(i) * s[0]; jac[0][1] += Y(i) * s[0]; jac[0][2] += Z(i) * s[0]; } { double a[3], b[3], c[3]; a[0]= X[1] - X(0); a[1]= Y[1] - Y(0); a[2]= Z[1] - Z(0); if((fabs(a[0]) >= fabs(a[1]) && fabs(a[0]) >= fabs(a[2])) || (fabs(a[1]) >= fabs(a[0]) && fabs(a[1]) >= fabs(a[2]))) { b[0] = a[1]; b[1] = -a[0]; b[2] = 0.0; } else { b[0] = 0.0; b[1] = a[2]; b[2] = -a[1]; } prodve(a, b, c); jac[1][0] = b[0]; jac[1][1] = b[1]; jac[1][2] = b[2]; jac[2][0] = c[0]; jac[2][1] = c[1]; jac[2][2] = c[2]; } return sqrt(SQR(jac[0][0])+SQR(jac[0][1])+SQR(jac[0][2])); } #undef X #undef Y #undef Z return 0.0; } /* * \tilde{\phi}(x) = \sum_{i} d_i N_i(\xi(x)) * @param valdim dimension of value points * @param dofs dofs is a rank-2 array of dimension [ndofs x valdim] * @param point point is a rank-1 array of dimension [celldim] * @param value value is a rank-1 array of dimension [valdim] */ void cigma::Cell::interpolate(double *dofs, double *point, double *value, int valdim) { double N[ndofs]; shape(1, point, N); // // value[i] = N[0]*dofs[0,i] + N[1]*dofs[1,i] + ... // for (int i = 0; i < valdim; i++) { double sum = 0.0; for (int j = 0; j < ndofs; j++) sum += dofs[i + valdim*j] * N[j]; value[i] = sum; } } /* * @param dofs is a rank-2 array of dimension [ndofs x valdim] * @param point is a rank-1 array of dimension [celldim] * @param value is a rank-1 array of dimension [valdim] */ void cigma::Cell::interpolate_grad(double *dofs, double *point, double *value, int stride=1, double invjac[3][3]=NULL) { assert(celldim > 0); assert(nno > 0); assert(ndofs > 0); int i, j, k; double dfdu[3] = {0.0, 0.0, 0.0}; double grad[ndofs*3]; double *s; grad_shape(1, point, grad); k = 0; for (int i = 0; i < ndofs; i++) { s = &grad[3*i]; for (j = 0; j < celldim; j++) { dfdu[j] += dofs[k] * s[j] } k += stride; } if (invjac) { matvec(invjac, dNdu, value); } else { double jac[3][3], inv[3][3]; jacobian(point, jac); inv3x3(jac, inv); matvec(inv, dfdu, value); } } /* isoparametric reference map */ void cigma::Cell::uvw2xyz(double uvw[3], double xyz[3]) { interpolate(globverts, uvw, xyz, 3); } void cigma::Cell::bbox(double *min, double *max) { minmax(globverts, nno, nsd, min, max); } void cigma::Cell::centroid(double c[3]) { cigma::centroid(globverts, nno, nsd, c); } <|endoftext|>
<commit_before>/* This source file is part of pairOculus, a student project aiming at creating a simple 3D multiplayer game for the Oculus Rift. Repository can be found here : https://github.com/Target6/pairOculus Copyright (c) 2013 Zykino 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. */ #ifndef CUBE_HPP #define CUBE_HPP #include "Block.hpp" /// Cubic Block. class Cube : public Block { public: /// Constructor Cube( Ogre::ManualObject *man, PrintType print, Real px, Real py, Real pz, Real sx = 100.0, Real sy = 100.0, Real sz = 100.0 ); virtual ~Cube(); /// Show the caracteristical points of the Cube virtual void createBlockPoint(); /// Show the Skeleton of the Cube virtual void createBlockWireframe(); /// Show the solid Cube virtual void createBlockSolid(); protected: private: }; #endif // CUBE_HPP <commit_msg>fixed a comment<commit_after>/* This source file is part of pairOculus, a student project aiming at creating a simple 3D multiplayer game for the Oculus Rift. Repository can be found here : https://github.com/Target6/pairOculus Copyright (c) 2013 Zykino 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. */ #ifndef CUBE_HPP #define CUBE_HPP #include "Block.hpp" /// A Cubic Block. class Cube : public Block { public: /// Constructor Cube( Ogre::ManualObject *man, PrintType print, Real px, Real py, Real pz, Real sx = 100.0, Real sy = 100.0, Real sz = 100.0 ); virtual ~Cube(); /// Show the caracteristical points of the Cube virtual void createBlockPoint(); /// Show the Skeleton of the Cube virtual void createBlockWireframe(); /// Show the solid Cube virtual void createBlockSolid(); protected: private: }; #endif // CUBE_HPP <|endoftext|>
<commit_before>#include "Network.h" void Network::begin(nodeID node) { Serial << F("Network: begin") << endl; this->node = networkStart(node); // setup Light comms Serial1.begin(115200); //start the library, pass in the data details and the name of the serial port. Can be Serial, Serial1, Serial2, etc. this->ET.begin(details(this->state), &Serial1); Serial << F("Network: serial comms with Light module.") << endl; // arise, Cthulu //radio.Wakeup(); // this was crashing startup // check the send time Serial << F("Network: system datagram size (bytes)=") << sizeof(this->state) << endl; // send. match Network::update Send syntax exactly radio.Send(255, (const void*)(&this->state), sizeof(this->state), false, 0); radio.SendWait(); unsigned long tic = micros(); radio.Send(255, (const void*)(&this->state), sizeof(this->state), false, 0); radio.SendWait(); unsigned long toc = micros(); Serial << F("Network: system datagram requires ") << toc - tic << F("us to send.") << endl; // save this, bumped slighly and at least 5ms // this->packetSendInterval = max(5000UL, float(toc - tic) * 1.1); this->packetSendInterval = float(toc - tic) * 1.1; Serial << F("Network: sending system datagram every ") << this->packetSendInterval << F("us.") << endl; this->resendCount = 10; this->sentCount = this->resendCount; Serial << F("Network: will resend new packets x") << this->resendCount << endl; // Get layout int addr = 69; color lightLayout[N_COLORS] = {I_RED, I_GRN, I_BLU, I_YEL}, fireLayout[N_COLORS] = {I_RED, I_GRN, I_BLU, I_YEL}; for ( byte i = 0; i < N_COLORS; i++ ) { lightLayout[i] = (color)EEPROM.read(addr+i); fireLayout[i] = (color)EEPROM.read(addr+i+N_COLORS); } // sanity check this->layout( lightLayout, fireLayout ); // redundant, but I want the print Serial << F("Network: setup complete.") << endl; } void Network::layout(color lightLayout[N_COLORS], color fireLayout[N_COLORS]) { Serial << F("Network: layout:") << endl; // write to EEPROM if there's a change. int addr = 69; // store it for ( byte i = 0; i < N_COLORS; i++ ) { this->lightLayout[i] = lightLayout[i]; Serial << F(" Color ") << i << (" assigned to Tower ") << lightLayout[i] << endl; if( EEPROM.read(addr+i) != (byte)lightLayout[i] ) { Serial << F(" set EEPROM") << endl; EEPROM.write(addr+i, (byte)lightLayout[i]); } this->fireLayout[i] = fireLayout[i]; Serial << F(" Fire ") << i << (" assigned to Tower ") << fireLayout[i] << endl; if( EEPROM.read(addr+i+N_COLORS) != (byte)fireLayout[i] ) { Serial << F(" set EEPROM") << endl; EEPROM.write(addr+i+N_COLORS, (byte)fireLayout[i]); } } } // resends and stuff void Network::update() { // if the sent count exceeds resend count, exit if ( this->sentCount >= this->resendCount ) return; // track send times static unsigned long lastSend = micros(); unsigned long now = micros(); // if this is the first time we've sent, update the packet number if ( this->sentCount == 0 ) { this->state.packetNumber++; // note that the timer check won't be made, so we could be partway through a send. } else { // if the resend interval has not elapsed, exit if( now-lastSend < this->packetSendInterval ) return; } // Radio: send. no ACK, no sleep. this->send(); this->sentCount++; // record last send time lastSend = now; } // makes the network do stuff with your stuff void Network::send(color position, colorInstruction &inst) { this->state.light[position] = inst; this->sentCount = 0; } void Network::send(color position, fireInstruction &inst) { this->state.fire[position] = inst; this->sentCount = 0; } void Network::send(systemMode mode) { this->state.mode = (byte)mode; this->sentCount = 0; } void Network::send(animationInstruction &inst) { this->state.animation = inst; this->sentCount = 0; } // internal dispatcher void Network::send() { // Light: send. handled by dedicated UART hardwre, so will happen in the background. ET.sendData(); // apply physical Tower layout systemState towerState; // copy out invariants towerState.packetNumber = this->state.packetNumber; towerState.mode = this->state.mode; towerState.animation = this->state.animation; for( byte i=0; i<N_COLORS; i++ ) { if( this->lightLayout[i] != N_COLORS ) { // if single tower are handling single colors towerState.light[i] = this->state.light[this->lightLayout[i]]; } else { // towers are handling multiple color instructions this->mergeColor(towerState.light[i]); } if ( this->fireLayout[i] != N_COLORS ) { towerState.fire[i] = this->state.fire[this->fireLayout[i]]; } else { // towers are handling multiple fire instructions this->mergeFire(towerState.fire[i]); } } radio.Send((byte)BROADCAST, (const void*)(&towerState), sizeof(towerState), false, 0); } // we sum up the lighting instructions void Network::mergeColor(colorInstruction &inst) { unsigned long red = 0, green = 0, blue = 0; for ( byte i = 0; i < N_COLORS; i++ ) { // summation red += this->state.light[i].red; green += this->state.light[i].green; blue += this->state.light[i].blue; // maybe maxima would be more appropriate? // red = max( red, this->state.light[i].red ); // green = max( green, this->state.light[i].green ); // blue = max( blue, this->state.light[i].blue ); } inst.red = constrain(red, 0, 255); inst.green = constrain(green, 0, 255); inst.blue = constrain(blue, 0, 255); } // we sum up the fire instructions void Network::mergeFire(fireInstruction &inst) { unsigned long duration = 0, effect = 0; for ( byte i = 0; i < N_COLORS; i++ ) { // summation duration += this->state.fire[i].duration; effect += this->state.fire[i].effect; // maybe maxima would be more appropriate? // duration = max( duration, this->state.fire[i].duration ); // effect = max( effect, this->state.fire[i].effect ); } inst.duration = constrain(duration, 0, 255); inst.effect = constrain(effect, veryRich, veryLean); } // starts the radio nodeID Network::networkStart(nodeID node) { // EEPROM location for radio settings. const byte radioConfigLocation = 42; if ( node == BROADCAST ) { // try to recover settings from EEPROM byte offset = 0; byte node = EEPROM.read(radioConfigLocation + (offset++)); byte groupID = EEPROM.read(radioConfigLocation + (offset++)); byte band = EEPROM.read(radioConfigLocation + (offset++)); Serial << F("Tower: Startup RFM69HW radio module. "); Serial << F(" NodeID: ") << node; Serial << F(" GroupID: ") << groupID; Serial << F(" Band: ") << band; Serial << endl; // radio.Initialize(node, band, groupID, 0, 0x7F); // 38300 bps radio.Initialize(node, band, groupID, 0, 0x02); // 115200 bps Serial << F("Network: RFM12b radio module startup complete. ") << endl; return ( (nodeID)node ); } else { Serial << F("Network: writing EEPROM (bootstrapping).") << endl; // then EEPROM isn't configured correctly. byte offset = 0; EEPROM.write(radioConfigLocation + (offset++), node); EEPROM.write(radioConfigLocation + (offset++), D_GROUP_ID); EEPROM.write(radioConfigLocation + (offset++), RF12_915MHZ); return ( networkStart(BROADCAST) ); // go again after EEPROM save } } Network network; <commit_msg>Network.cpp/send() functions now look for a delta before resetting sentCount. This has the effect of not restarting network resends unless there's a delta. Should reduce unnecessary network traffic?<commit_after>#include "Network.h" void Network::begin(nodeID node) { Serial << F("Network: begin") << endl; this->node = networkStart(node); // setup Light comms Serial1.begin(115200); //start the library, pass in the data details and the name of the serial port. Can be Serial, Serial1, Serial2, etc. this->ET.begin(details(this->state), &Serial1); Serial << F("Network: serial comms with Light module.") << endl; // arise, Cthulu //radio.Wakeup(); // this was crashing startup // check the send time Serial << F("Network: system datagram size (bytes)=") << sizeof(this->state) << endl; // send. match Network::update Send syntax exactly radio.Send(255, (const void*)(&this->state), sizeof(this->state), false, 0); radio.SendWait(); unsigned long tic = micros(); radio.Send(255, (const void*)(&this->state), sizeof(this->state), false, 0); radio.SendWait(); unsigned long toc = micros(); Serial << F("Network: system datagram requires ") << toc - tic << F("us to send.") << endl; // save this, bumped slighly and at least 5ms // this->packetSendInterval = max(5000UL, float(toc - tic) * 1.1); this->packetSendInterval = float(toc - tic) * 1.1; Serial << F("Network: sending system datagram every ") << this->packetSendInterval << F("us.") << endl; this->resendCount = 10; this->sentCount = this->resendCount; Serial << F("Network: will resend new packets x") << this->resendCount << endl; // Get layout int addr = 69; color lightLayout[N_COLORS] = {I_RED, I_GRN, I_BLU, I_YEL}, fireLayout[N_COLORS] = {I_RED, I_GRN, I_BLU, I_YEL}; for ( byte i = 0; i < N_COLORS; i++ ) { lightLayout[i] = (color)EEPROM.read(addr+i); fireLayout[i] = (color)EEPROM.read(addr+i+N_COLORS); } // sanity check this->layout( lightLayout, fireLayout ); // redundant, but I want the print Serial << F("Network: setup complete.") << endl; } void Network::layout(color lightLayout[N_COLORS], color fireLayout[N_COLORS]) { Serial << F("Network: layout:") << endl; // write to EEPROM if there's a change. int addr = 69; // store it for ( byte i = 0; i < N_COLORS; i++ ) { this->lightLayout[i] = lightLayout[i]; Serial << F(" Color ") << i << (" assigned to Tower ") << lightLayout[i] << endl; if( EEPROM.read(addr+i) != (byte)lightLayout[i] ) { Serial << F(" set EEPROM") << endl; EEPROM.write(addr+i, (byte)lightLayout[i]); } this->fireLayout[i] = fireLayout[i]; Serial << F(" Fire ") << i << (" assigned to Tower ") << fireLayout[i] << endl; if( EEPROM.read(addr+i+N_COLORS) != (byte)fireLayout[i] ) { Serial << F(" set EEPROM") << endl; EEPROM.write(addr+i+N_COLORS, (byte)fireLayout[i]); } } } // resends and stuff void Network::update() { // if the sent count exceeds resend count, exit if ( this->sentCount >= this->resendCount ) return; // track send times static unsigned long lastSend = micros(); unsigned long now = micros(); // if this is the first time we've sent, update the packet number if ( this->sentCount == 0 ) { this->state.packetNumber++; // note that the timer check won't be made, so we could be partway through a send. } else { // if the resend interval has not elapsed, exit if( now-lastSend < this->packetSendInterval ) return; } // Radio: send. no ACK, no sleep. this->send(); this->sentCount++; // record last send time lastSend = now; } // makes the network do stuff with your stuff void Network::send(color position, colorInstruction &inst) { // change on a delta if ( memcmp((void*)(&inst), (void*)(&this->state.light[position]), sizeof(colorInstruction)) != 0 ) { this->state.light[position] = inst; this->sentCount = 0; } } void Network::send(color position, fireInstruction &inst) { // change on a delta if ( memcmp((void*)(&inst), (void*)(&this->state.fire[position]), sizeof(fireInstruction)) != 0 ) { this->state.fire[position] = inst; this->sentCount = 0; } } void Network::send(systemMode mode) { // change on a delta if ( mode != (byte)state.mode ) { this->state.mode = (byte)mode; this->sentCount = 0; } } void Network::send(animationInstruction &inst) { // change on a delta if ( memcmp((void*)(&inst), (void*)(&this->state.animation), sizeof(animationInstruction)) != 0 ) { this->state.animation = inst; this->sentCount = 0; } } // internal dispatcher void Network::send() { // Light: send. handled by dedicated UART hardwre, so will happen in the background. ET.sendData(); // apply physical Tower layout systemState towerState; // copy out invariants towerState.packetNumber = this->state.packetNumber; towerState.mode = this->state.mode; towerState.animation = this->state.animation; for( byte i=0; i<N_COLORS; i++ ) { if( this->lightLayout[i] != N_COLORS ) { // if single tower are handling single colors towerState.light[i] = this->state.light[this->lightLayout[i]]; } else { // towers are handling multiple color instructions this->mergeColor(towerState.light[i]); } if ( this->fireLayout[i] != N_COLORS ) { towerState.fire[i] = this->state.fire[this->fireLayout[i]]; } else { // towers are handling multiple fire instructions this->mergeFire(towerState.fire[i]); } } radio.Send((byte)BROADCAST, (const void*)(&towerState), sizeof(towerState), false, 0); } // we sum up the lighting instructions void Network::mergeColor(colorInstruction &inst) { unsigned long red = 0, green = 0, blue = 0; for ( byte i = 0; i < N_COLORS; i++ ) { // summation red += this->state.light[i].red; green += this->state.light[i].green; blue += this->state.light[i].blue; // maybe maxima would be more appropriate? // red = max( red, this->state.light[i].red ); // green = max( green, this->state.light[i].green ); // blue = max( blue, this->state.light[i].blue ); } inst.red = constrain(red, 0, 255); inst.green = constrain(green, 0, 255); inst.blue = constrain(blue, 0, 255); } // we sum up the fire instructions void Network::mergeFire(fireInstruction &inst) { unsigned long duration = 0, effect = 0; for ( byte i = 0; i < N_COLORS; i++ ) { // summation duration += this->state.fire[i].duration; effect += this->state.fire[i].effect; // maybe maxima would be more appropriate? // duration = max( duration, this->state.fire[i].duration ); // effect = max( effect, this->state.fire[i].effect ); } inst.duration = constrain(duration, 0, 255); inst.effect = constrain(effect, veryRich, veryLean); } // starts the radio nodeID Network::networkStart(nodeID node) { // EEPROM location for radio settings. const byte radioConfigLocation = 42; if ( node == BROADCAST ) { // try to recover settings from EEPROM byte offset = 0; byte node = EEPROM.read(radioConfigLocation + (offset++)); byte groupID = EEPROM.read(radioConfigLocation + (offset++)); byte band = EEPROM.read(radioConfigLocation + (offset++)); Serial << F("Tower: Startup RFM69HW radio module. "); Serial << F(" NodeID: ") << node; Serial << F(" GroupID: ") << groupID; Serial << F(" Band: ") << band; Serial << endl; // radio.Initialize(node, band, groupID, 0, 0x7F); // 38300 bps radio.Initialize(node, band, groupID, 0, 0x02); // 115200 bps Serial << F("Network: RFM12b radio module startup complete. ") << endl; return ( (nodeID)node ); } else { Serial << F("Network: writing EEPROM (bootstrapping).") << endl; // then EEPROM isn't configured correctly. byte offset = 0; EEPROM.write(radioConfigLocation + (offset++), node); EEPROM.write(radioConfigLocation + (offset++), D_GROUP_ID); EEPROM.write(radioConfigLocation + (offset++), RF12_915MHZ); return ( networkStart(BROADCAST) ); // go again after EEPROM save } } Network network; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unomailmerge.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:15:44 $ * * 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 * ************************************************************************/ #ifndef _UNOMAILMERGE_HXX_ #define _UNOMAILMERGE_HXX_ #include <functional> #ifndef _CPPUHELPER_IMPLBASE5_HXX_ #include <cppuhelper/implbase5.hxx> // WeakImplHelper4 #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> // OMultiTypeInterfaceContainerHelperVar #endif #ifndef _UTL_CONFIGITEM_HXX_ #include <unotools/configitem.hxx> // !! needed for OMultiTypeInterfaceContainerHelperVar !! #endif #ifndef _COM_SUN_STAR_TASK_XJOB_HPP_ #include <com/sun/star/task/XJob.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYCHANGEEVENT_HPP_ #include <com/sun/star/beans/PropertyChangeEvent.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XMAILMERGEBROADCASTER_HPP_ #include <com/sun/star/text/XMailMergeBroadcaster.hpp> #endif #ifndef _SFX_ITEMPROP_HXX #include <svtools/itemprop.hxx> #endif #ifndef _SFX_OBJSH_HXX #include <sfx2/objsh.hxx> // SfxObjectShellRef #endif #include <functional> namespace com { namespace sun { namespace star { namespace sdbc { class XResultSet; class XConnection; } namespace frame { class XModel; } namespace lang { class XMultiServiceFactory; } namespace text { class XMailMergeListener; struct MailMergeEvent; } namespace beans{ struct PropertyValue; } }}} namespace rtl { class OUString; } /////////////////////////////////////////////////////////////////////////// // uses templates from <cppuhelper/interfacecontainer.h> // and <unotools/configitem.hxx> // helper function call class struct PropHashType_Impl { size_t operator()(const INT32 &s) const { return s; } }; typedef cppu::OMultiTypeInterfaceContainerHelperVar < INT32, PropHashType_Impl, std::equal_to< INT32 > > OPropertyListenerContainerHelper; //////////////////////////////////////////////////////////// class SwXMailMerge : public cppu::WeakImplHelper5 < com::sun::star::task::XJob, com::sun::star::beans::XPropertySet, com::sun::star::text::XMailMergeBroadcaster, com::sun::star::lang::XComponent, com::sun::star::lang::XServiceInfo > { cppu::OInterfaceContainerHelper aEvtListeners; cppu::OInterfaceContainerHelper aMergeListeners; OPropertyListenerContainerHelper aPropListeners; //SfxItemPropertySet aPropSet; const SfxItemPropertyMap* pMap; SfxObjectShellRef xDocSh; // the document String aTmpFileName; // properties of mail merge service com::sun::star::uno::Sequence< com::sun::star::uno::Any > aSelection; com::sun::star::uno::Reference< com::sun::star::sdbc::XResultSet > xResultSet; com::sun::star::uno::Reference< com::sun::star::sdbc::XConnection > xConnection; com::sun::star::uno::Reference< com::sun::star::frame::XModel > xModel; rtl::OUString aDataSourceName; rtl::OUString aDataCommand; rtl::OUString aFilter; rtl::OUString aDocumentURL; rtl::OUString aOutputURL; rtl::OUString aFileNamePrefix; sal_Int32 nDataCommandType; sal_Int16 nOutputType; sal_Bool bEscapeProcessing; sal_Bool bSinglePrintJobs; sal_Bool bFileNameFromColumn; ::rtl::OUString sInServerPassword; ::rtl::OUString sOutServerPassword; ::rtl::OUString sSubject; ::rtl::OUString sAddressFromColumn; ::rtl::OUString sMailBody; ::rtl::OUString sAttachmentName; ::rtl::OUString sAttachmentFilter; com::sun::star::uno::Sequence< ::rtl::OUString > aCopiesTo; com::sun::star::uno::Sequence< ::rtl::OUString > aBlindCopiesTo; sal_Bool bSendAsHTML; sal_Bool bSendAsAttachment; com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aPrintSettings; sal_Bool bSaveAsSingleFile; ::rtl::OUString sSaveFilter; ::rtl::OUString sSaveFilterOptions; com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSaveFilterData; sal_Bool bDisposing; void launchEvent( const com::sun::star::beans::PropertyChangeEvent &rEvt ) const; // disallow use of copy-constructor and assignment-operator for now SwXMailMerge( const SwXMailMerge & ); SwXMailMerge & operator = ( const SwXMailMerge & ); protected: virtual ~SwXMailMerge(); public: SwXMailMerge(); void LaunchMailMergeEvent( const com::sun::star::text::MailMergeEvent &rData ) const; // XJob virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XMailMergeBroadcaster virtual void SAL_CALL addMailMergeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::text::XMailMergeListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeMailMergeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::text::XMailMergeListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException); }; extern com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL SwXMailMerge_getSupportedServiceNames() throw(); extern rtl::OUString SAL_CALL SwXMailMerge_getImplementationName() throw(); extern com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL SwXMailMerge_createInstance(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw( com::sun::star::uno::Exception ); //////////////////////////////////////////////////////////// #endif <commit_msg>INTEGRATION: CWS changefileheader (1.8.242); FILE MERGED 2008/04/01 15:56:26 thb 1.8.242.3: #i85898# Stripping all external header guards 2008/04/01 12:53:38 thb 1.8.242.2: #i85898# Stripping all external header guards 2008/03/31 16:52:45 rt 1.8.242.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: unomailmerge.hxx,v $ * $Revision: 1.9 $ * * 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. * ************************************************************************/ #ifndef _UNOMAILMERGE_HXX_ #define _UNOMAILMERGE_HXX_ #include <functional> #include <cppuhelper/implbase5.hxx> // WeakImplHelper4 #include <cppuhelper/interfacecontainer.hxx> // OMultiTypeInterfaceContainerHelperVar #include <unotools/configitem.hxx> // !! needed for OMultiTypeInterfaceContainerHelperVar !! #include <com/sun/star/task/XJob.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/beans/PropertyChangeEvent.hpp> #include <com/sun/star/text/XMailMergeBroadcaster.hpp> #include <svtools/itemprop.hxx> #include <sfx2/objsh.hxx> // SfxObjectShellRef #include <functional> namespace com { namespace sun { namespace star { namespace sdbc { class XResultSet; class XConnection; } namespace frame { class XModel; } namespace lang { class XMultiServiceFactory; } namespace text { class XMailMergeListener; struct MailMergeEvent; } namespace beans{ struct PropertyValue; } }}} namespace rtl { class OUString; } /////////////////////////////////////////////////////////////////////////// // uses templates from <cppuhelper/interfacecontainer.h> // and <unotools/configitem.hxx> // helper function call class struct PropHashType_Impl { size_t operator()(const INT32 &s) const { return s; } }; typedef cppu::OMultiTypeInterfaceContainerHelperVar < INT32, PropHashType_Impl, std::equal_to< INT32 > > OPropertyListenerContainerHelper; //////////////////////////////////////////////////////////// class SwXMailMerge : public cppu::WeakImplHelper5 < com::sun::star::task::XJob, com::sun::star::beans::XPropertySet, com::sun::star::text::XMailMergeBroadcaster, com::sun::star::lang::XComponent, com::sun::star::lang::XServiceInfo > { cppu::OInterfaceContainerHelper aEvtListeners; cppu::OInterfaceContainerHelper aMergeListeners; OPropertyListenerContainerHelper aPropListeners; //SfxItemPropertySet aPropSet; const SfxItemPropertyMap* pMap; SfxObjectShellRef xDocSh; // the document String aTmpFileName; // properties of mail merge service com::sun::star::uno::Sequence< com::sun::star::uno::Any > aSelection; com::sun::star::uno::Reference< com::sun::star::sdbc::XResultSet > xResultSet; com::sun::star::uno::Reference< com::sun::star::sdbc::XConnection > xConnection; com::sun::star::uno::Reference< com::sun::star::frame::XModel > xModel; rtl::OUString aDataSourceName; rtl::OUString aDataCommand; rtl::OUString aFilter; rtl::OUString aDocumentURL; rtl::OUString aOutputURL; rtl::OUString aFileNamePrefix; sal_Int32 nDataCommandType; sal_Int16 nOutputType; sal_Bool bEscapeProcessing; sal_Bool bSinglePrintJobs; sal_Bool bFileNameFromColumn; ::rtl::OUString sInServerPassword; ::rtl::OUString sOutServerPassword; ::rtl::OUString sSubject; ::rtl::OUString sAddressFromColumn; ::rtl::OUString sMailBody; ::rtl::OUString sAttachmentName; ::rtl::OUString sAttachmentFilter; com::sun::star::uno::Sequence< ::rtl::OUString > aCopiesTo; com::sun::star::uno::Sequence< ::rtl::OUString > aBlindCopiesTo; sal_Bool bSendAsHTML; sal_Bool bSendAsAttachment; com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aPrintSettings; sal_Bool bSaveAsSingleFile; ::rtl::OUString sSaveFilter; ::rtl::OUString sSaveFilterOptions; com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSaveFilterData; sal_Bool bDisposing; void launchEvent( const com::sun::star::beans::PropertyChangeEvent &rEvt ) const; // disallow use of copy-constructor and assignment-operator for now SwXMailMerge( const SwXMailMerge & ); SwXMailMerge & operator = ( const SwXMailMerge & ); protected: virtual ~SwXMailMerge(); public: SwXMailMerge(); void LaunchMailMergeEvent( const com::sun::star::text::MailMergeEvent &rData ) const; // XJob virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); // XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XMailMergeBroadcaster virtual void SAL_CALL addMailMergeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::text::XMailMergeListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeMailMergeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::text::XMailMergeListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException); }; extern com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL SwXMailMerge_getSupportedServiceNames() throw(); extern rtl::OUString SAL_CALL SwXMailMerge_getImplementationName() throw(); extern com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL SwXMailMerge_createInstance(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw( com::sun::star::uno::Exception ); //////////////////////////////////////////////////////////// #endif <|endoftext|>
<commit_before>#include <vtkSmartPointer.h> #include <vtkImageViewer2.h> #include <vtkTIFFReader.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> int main(int argc, char* argv[]) { //Verify input arguments if ( argc != 2 ) { std::cout << "Usage: " << argv[0] << " Filename(.tif)" << std::endl; return EXIT_FAILURE; } //Read the image vtkSmartPointer<vtkTIFFReader> reader = vtkSmartPointer<vtkTIFFReader>::New(); reader->SetFileName ( argv[1] ); // Visualize vtkSmartPointer<vtkImageViewer2> imageViewer = vtkSmartPointer<vtkImageViewer2>::New(); imageViewer->SetInputConnection(reader->GetOutputPort()); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); imageViewer->SetupInteractor(renderWindowInteractor); imageViewer->Render(); imageViewer->GetRenderer()->ResetCamera(); imageViewer->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } <commit_msg>Update ReadTIFF.cxx<commit_after>#include <vtkSmartPointer.h> #include <vtkImageViewer2.h> #include <vtkTIFFReader.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> int main(int argc, char* argv[]) { //Verify input arguments if ( argc != 2 ) { std::cout << "Usage: " << argv[0] << " Filename(.tif) e.g. ColorCells.tif" << std::endl; return EXIT_FAILURE; } //Read the image vtkSmartPointer<vtkTIFFReader> reader = vtkSmartPointer<vtkTIFFReader>::New(); reader->SetFileName ( argv[1] ); // Visualize vtkSmartPointer<vtkImageViewer2> imageViewer = vtkSmartPointer<vtkImageViewer2>::New(); imageViewer->SetInputConnection(reader->GetOutputPort()); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); imageViewer->SetupInteractor(renderWindowInteractor); imageViewer->Render(); imageViewer->GetRenderer()->ResetCamera(); imageViewer->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "SlidingWindow.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Debug.h" #include "Substitute.h" #include "IRPrinter.h" #include "Simplify.h" #include "Derivative.h" #include "Bounds.h" namespace Halide { namespace Internal { using std::string; using std::map; // Does an expression depend on a particular variable? class ExprDependsOnVar : public IRVisitor { using IRVisitor::visit; void visit(const Variable *op) { if (op->name == var) result = true; } void visit(const Let *op) { op->value.accept(this); // The name might be hidden within the body of the let, in // which case there's no point descending. if (op->name != var) { op->body.accept(this); } } public: bool result; string var; ExprDependsOnVar(string v) : result(false), var(v) { } }; bool expr_depends_on_var(Expr e, string v) { ExprDependsOnVar depends(v); e.accept(&depends); return depends.result; } // Perform sliding window optimization for a function over a // particular serial for loop class SlidingWindowOnFunctionAndLoop : public IRMutator { Function func; string loop_var; Expr loop_min; Scope<Expr> scope; using IRMutator::visit; void visit(const Pipeline *op) { if (op->name != func.name()) { IRMutator::visit(op); } else { // We're interested in the case where exactly one of the // dimensions of the buffer has a min/extent that depends // on the loop_var. string dim = ""; Expr min_produced, extent_produced; debug(3) << "Considering sliding " << func.name() << " along loop variable " << loop_var << "\n" << "Region provided:\n"; for (int i = 0; i < func.dimensions(); i++) { // Look up the region produced over this dimension Expr m = scope.get(func.name() + "." + func.args()[i] + ".min_produced"); Expr e = scope.get(func.name() + "." + func.args()[i] + ".extent_produced"); string min_req_name = func.name() + "." + func.args()[i] + ".min_required"; string extent_req_name = func.name() + "." + func.args()[i] + ".extent_required"; Expr m_r = scope.get(min_req_name); Expr e_r = scope.get(extent_req_name); debug(3) << func.args()[i] << ":" << m << ", " << e << "\n"; if (expr_depends_on_var(m_r, loop_var) || expr_depends_on_var(e_r, loop_var)) { if (!dim.empty()) { dim = ""; min_produced = Expr(); extent_produced = Expr(); break; } else { dim = func.args()[i]; min_produced = substitute(min_req_name, m_r, m); extent_produced = substitute(extent_req_name, e_r, e); } } } Expr loop_var_expr = Variable::make(Int(32), loop_var); bool increasing = true; if (min_produced.defined()) { MonotonicResult m = is_monotonic(min_produced, loop_var); if (m == MonotonicIncreasing || m == Constant) { increasing = true; } else if (m == MonotonicDecreasing) { increasing = false; } else { debug(3) << "Not sliding " << func.name() << " over dimension " << dim << " along loop variable " << loop_var << " because I couldn't prove it moved monotonically along that dimension\n" << "Min is " << min << "\n"; min_produced = Expr(); } } if (min_produced.defined()) { // Ok, we've isolated a function, a dimension to slide along, and loop variable to slide over debug(3) << "Sliding " << func.name() << " over dimension " << dim << " along loop variable " << loop_var << "\n"; Expr new_min, new_extent; Expr min_extent = func.min_extent_produced(dim); Expr min_extent_factor = func.min_extent_updated(dim); // We've sworn to produce from min_produced to // extent_produced, but we can perhaps skip values // already computed if (increasing) { Expr max_plus_one = min_produced + extent_produced; Expr prev_max_plus_one = substitute(loop_var, loop_var_expr - 1, max_plus_one); new_extent = max_plus_one - prev_max_plus_one; // We still need to produce an amount that is a // multiple of the min_extent_factor and is at // least the min_extent. new_extent = Max::make(new_extent, min_extent); new_extent += min_extent_factor - 1; new_extent /= min_extent_factor; new_extent *= min_extent_factor; new_extent = simplify(new_extent); new_min = max_plus_one - new_extent; new_extent = select(loop_var_expr == loop_min, extent_produced, new_extent); new_min = select(loop_var_expr == loop_min, min_produced, new_min); } else { Expr prev_min = substitute(loop_var, loop_var_expr - 1, min_produced); new_extent = prev_min - min_produced; new_extent = Max::make(new_extent, min_extent); new_extent += min_extent_factor - 1; new_extent /= min_extent_factor; new_extent *= min_extent_factor; new_extent = simplify(new_extent); new_extent = select(loop_var_expr == loop_min, extent_produced, new_extent); new_min = min_produced; } new_min = simplify(new_min); new_extent = simplify(new_extent); debug(3) << "Sliding " << func.name() << ", " << dim << "\n" << "Pushing min up from " << min_produced << " to " << new_min << "\n" << "Shrinking extent from " << extent_produced << " to " << new_extent << "\n"; string min_name = func.name() + "." + dim + ".min_produced"; string extent_name = func.name() + "." + dim + ".extent_produced"; stmt = op; stmt = LetStmt::make(min_name, new_min, stmt); stmt = LetStmt::make(extent_name, new_extent, stmt); debug(3) << "new extent: " << new_extent << "\n"; } else { debug(3) << "Could not perform sliding window optimization of " << func.name() << " over " << loop_var << "\n"; stmt = op; } } } void visit(const LetStmt *op) { scope.push(op->name, op->value); Stmt new_body = mutate(op->body); if (new_body.same_as(op->body)) { stmt = op; } else { stmt = LetStmt::make(op->name, op->value, new_body); } scope.pop(op->name); } public: SlidingWindowOnFunctionAndLoop(Function f, string v, Expr v_min) : func(f), loop_var(v), loop_min(v_min) {} }; // Perform sliding window optimization for a particular function class SlidingWindowOnFunction : public IRMutator { Function func; using IRMutator::visit; void visit(const For *op) { Stmt new_body = mutate(op->body); if (op->for_type == For::Serial || op->for_type == For::Unrolled) { new_body = SlidingWindowOnFunctionAndLoop(func, op->name, op->min).mutate(new_body); } if (new_body.same_as(op->body)) { stmt = op; } else { stmt = For::make(op->name, op->min, op->extent, op->for_type, new_body); } } public: SlidingWindowOnFunction(Function f) : func(f) {} }; // Perform sliding window optimization for all functions class SlidingWindow : public IRMutator { const map<string, Function> &env; using IRMutator::visit; void visit(const Realize *op) { // Find the args for this function map<string, Function>::const_iterator iter = env.find(op->name); Stmt new_body = op->body; if (iter != env.end()) { debug(3) << "Doing sliding window analysis on realization of " << op->name << "\n"; new_body = SlidingWindowOnFunction(iter->second).mutate(new_body); } else { assert(false && "Compiler bug: Sliding window found a realization for a function not in the environment\n"); } new_body = mutate(new_body); if (new_body.same_as(op->body)) { stmt = op; } else { stmt = Realize::make(op->name, op->types, op->bounds, new_body); } } public: SlidingWindow(const map<string, Function> &e) : env(e) {} }; Stmt sliding_window(Stmt s, const map<string, Function> &env) { return SlidingWindow(env).mutate(s); } } } <commit_msg>Turn off sliding for reductions.<commit_after>#include "SlidingWindow.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" #include "Debug.h" #include "Substitute.h" #include "IRPrinter.h" #include "Simplify.h" #include "Derivative.h" #include "Bounds.h" namespace Halide { namespace Internal { using std::string; using std::map; // Does an expression depend on a particular variable? class ExprDependsOnVar : public IRVisitor { using IRVisitor::visit; void visit(const Variable *op) { if (op->name == var) result = true; } void visit(const Let *op) { op->value.accept(this); // The name might be hidden within the body of the let, in // which case there's no point descending. if (op->name != var) { op->body.accept(this); } } public: bool result; string var; ExprDependsOnVar(string v) : result(false), var(v) { } }; bool expr_depends_on_var(Expr e, string v) { ExprDependsOnVar depends(v); e.accept(&depends); return depends.result; } // Perform sliding window optimization for a function over a // particular serial for loop class SlidingWindowOnFunctionAndLoop : public IRMutator { Function func; string loop_var; Expr loop_min; Scope<Expr> scope; using IRMutator::visit; void visit(const Pipeline *op) { if (op->name != func.name()) { IRMutator::visit(op); } else { // We're interested in the case where exactly one of the // dimensions of the buffer has a min/extent that depends // on the loop_var. string dim = ""; Expr min_produced, extent_produced; debug(3) << "Considering sliding " << func.name() << " along loop variable " << loop_var << "\n" << "Region provided:\n"; for (int i = 0; i < func.dimensions(); i++) { // Look up the region produced over this dimension Expr m = scope.get(func.name() + "." + func.args()[i] + ".min_produced"); Expr e = scope.get(func.name() + "." + func.args()[i] + ".extent_produced"); string min_req_name = func.name() + "." + func.args()[i] + ".min_required"; string extent_req_name = func.name() + "." + func.args()[i] + ".extent_required"; Expr m_r = scope.get(min_req_name); Expr e_r = scope.get(extent_req_name); debug(3) << func.args()[i] << ":" << m << ", " << e << "\n"; if (expr_depends_on_var(m_r, loop_var) || expr_depends_on_var(e_r, loop_var)) { if (!dim.empty()) { dim = ""; min_produced = Expr(); extent_produced = Expr(); break; } else { dim = func.args()[i]; min_produced = substitute(min_req_name, m_r, m); extent_produced = substitute(extent_req_name, e_r, e); } } } Expr loop_var_expr = Variable::make(Int(32), loop_var); bool increasing = true; if (min_produced.defined()) { MonotonicResult m = is_monotonic(min_produced, loop_var); if (m == MonotonicIncreasing || m == Constant) { increasing = true; } else if (m == MonotonicDecreasing) { increasing = false; } else { debug(3) << "Not sliding " << func.name() << " over dimension " << dim << " along loop variable " << loop_var << " because I couldn't prove it moved monotonically along that dimension\n" << "Min is " << min << "\n"; min_produced = Expr(); } } if (min_produced.defined()) { // Ok, we've isolated a function, a dimension to slide along, and loop variable to slide over debug(3) << "Sliding " << func.name() << " over dimension " << dim << " along loop variable " << loop_var << "\n"; Expr new_min, new_extent; Expr min_extent = func.min_extent_produced(dim); Expr min_extent_factor = func.min_extent_updated(dim); // We've sworn to produce from min_produced to // extent_produced, but we can perhaps skip values // already computed if (increasing) { Expr max_plus_one = min_produced + extent_produced; Expr prev_max_plus_one = substitute(loop_var, loop_var_expr - 1, max_plus_one); new_extent = max_plus_one - prev_max_plus_one; // We still need to produce an amount that is a // multiple of the min_extent_factor and is at // least the min_extent. new_extent = Max::make(new_extent, min_extent); new_extent += min_extent_factor - 1; new_extent /= min_extent_factor; new_extent *= min_extent_factor; new_extent = simplify(new_extent); new_min = max_plus_one - new_extent; new_extent = select(loop_var_expr == loop_min, extent_produced, new_extent); new_min = select(loop_var_expr == loop_min, min_produced, new_min); } else { Expr prev_min = substitute(loop_var, loop_var_expr - 1, min_produced); new_extent = prev_min - min_produced; new_extent = Max::make(new_extent, min_extent); new_extent += min_extent_factor - 1; new_extent /= min_extent_factor; new_extent *= min_extent_factor; new_extent = simplify(new_extent); new_extent = select(loop_var_expr == loop_min, extent_produced, new_extent); new_min = min_produced; } new_min = simplify(new_min); new_extent = simplify(new_extent); debug(3) << "Sliding " << func.name() << ", " << dim << "\n" << "Pushing min up from " << min_produced << " to " << new_min << "\n" << "Shrinking extent from " << extent_produced << " to " << new_extent << "\n"; string min_name = func.name() + "." + dim + ".min_produced"; string extent_name = func.name() + "." + dim + ".extent_produced"; stmt = op; stmt = LetStmt::make(min_name, new_min, stmt); stmt = LetStmt::make(extent_name, new_extent, stmt); debug(3) << "new extent: " << new_extent << "\n"; } else { debug(3) << "Could not perform sliding window optimization of " << func.name() << " over " << loop_var << "\n"; stmt = op; } } } void visit(const LetStmt *op) { scope.push(op->name, op->value); Stmt new_body = mutate(op->body); if (new_body.same_as(op->body)) { stmt = op; } else { stmt = LetStmt::make(op->name, op->value, new_body); } scope.pop(op->name); } public: SlidingWindowOnFunctionAndLoop(Function f, string v, Expr v_min) : func(f), loop_var(v), loop_min(v_min) {} }; // Perform sliding window optimization for a particular function class SlidingWindowOnFunction : public IRMutator { Function func; using IRMutator::visit; void visit(const For *op) { Stmt new_body = mutate(op->body); if (op->for_type == For::Serial || op->for_type == For::Unrolled) { new_body = SlidingWindowOnFunctionAndLoop(func, op->name, op->min).mutate(new_body); } if (new_body.same_as(op->body)) { stmt = op; } else { stmt = For::make(op->name, op->min, op->extent, op->for_type, new_body); } } public: SlidingWindowOnFunction(Function f) : func(f) {} }; // Perform sliding window optimization for all functions class SlidingWindow : public IRMutator { const map<string, Function> &env; using IRMutator::visit; void visit(const Realize *op) { // Find the args for this function map<string, Function>::const_iterator iter = env.find(op->name); assert(iter != env.end() && "Compiler bug: Sliding window found a realization for a function not in the environment\n"); // For now we skip reductions, because the update step of a // reduction may read from the same buffer at points outside // of the region required, which in turn means the // initialization takes place over a larger domain than the // region required, which means that the initialization may // clobber old values that we're relying on to still be // correct. // // In the future we may allow a more nuanced test here. Stmt new_body = op->body; if (!(iter->second.has_reduction_definition())) { debug(3) << "Doing sliding window analysis on realization of " << op->name << "\n"; new_body = SlidingWindowOnFunction(iter->second).mutate(new_body); } new_body = mutate(new_body); if (new_body.same_as(op->body)) { stmt = op; } else { stmt = Realize::make(op->name, op->types, op->bounds, new_body); } } public: SlidingWindow(const map<string, Function> &e) : env(e) {} }; Stmt sliding_window(Stmt s, const map<string, Function> &env) { return SlidingWindow(env).mutate(s); } } } <|endoftext|>
<commit_before>#include "virtualkeyitem.h" #include <QDebug> #include <QGraphicsSceneMouseEvent> #include <QTouchEvent> #include "../osd.h" VirtualKeyItem::VirtualKeyItem(PCKEYsym code, QString pixNormal, QString pixShift, QString pixGrph, QString pixKana, QString pixKanaShift, QString pixKKana, QString pixKKanaShift, bool mouseToggle) : Code(code) , PixNormal(QString(":/res/vkey/key_%1.png").arg(pixNormal)) , PixShift(QString(":/res/vkey/key_%1.png").arg(pixShift)) , PixGrph(QString(":/res/vkey/key_%1.png").arg(pixGrph)) , PixKana(QString(":/res/vkey/key_%1.png").arg(pixKana)) , PixKanaShift(QString(":/res/vkey/key_%1.png").arg(pixKanaShift)) , PixKKana(QString(":/res/vkey/key_%1.png").arg(pixKKana)) , PixKKanaShift(QString(":/res/vkey/key_%1.png").arg(pixKKanaShift)) , MouseToggle(mouseToggle) , ToggleStatus(false) { setPixmap(PixNormal); setAcceptedMouseButtons(Qt::LeftButton); setAcceptTouchEvents(true); } void VirtualKeyItem::changeStatus( bool ON_SHIFT, bool ON_GRAPH, bool ON_KANA, bool ON_KKANA, bool ON_CAPS) { if (ON_KKANA){ if(ON_SHIFT)setPixmap(PixKKanaShift); else setPixmap(PixKKana); } else if (ON_KANA) { if(ON_SHIFT)setPixmap(PixKanaShift); else setPixmap(PixKKana); } else if (ON_GRAPH) { setPixmap(PixGrph); } else if (ON_SHIFT ^ ON_CAPS) { setPixmap(PixShift); } else { setPixmap(PixNormal); } } bool VirtualKeyItem::sceneEvent(QEvent *event) { qDebug() << "sceneEvent accepted:" << event->type(); auto type = event->type(); switch (type){ case QEvent::TouchBegin: case QEvent::TouchEnd: { sendKeyEvent(type == QEvent::TouchBegin ? EV_KEYDOWN : EV_KEYUP, type == QEvent::TouchBegin ? true : false); break; } default:; } return QGraphicsPixmapItem::sceneEvent(event); } void VirtualKeyItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { qDebug() << "mousePressEvent accepted:" << event->type(); // トグルキーの場合はUP,DOWNを交互に送る auto toggle = MouseToggle && ToggleStatus; if (MouseToggle) ToggleStatus = !ToggleStatus; sendKeyEvent(toggle ? EV_KEYUP : EV_KEYDOWN, MouseToggle ? ToggleStatus : true); QGraphicsPixmapItem::mousePressEvent(event); } void VirtualKeyItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { sendKeyEvent(EV_KEYUP, false); QGraphicsPixmapItem::mouseReleaseEvent(event); } void VirtualKeyItem::sendKeyEvent(EventType type, bool state) { Event ev; ev.type = type; ev.key.state = state; ev.key.sym = Code; ev.key.mod = KVM_NONE; ev.key.unicode = 0; /* ev.key.mod = (PCKEYmod)( ( ke->modifiers() & Qt::ShiftModifier ? KVM_SHIFT : KVM_NONE ) | ( ke->modifiers() & Qt::ControlModifier ? KVM_CTRL : KVM_NONE ) | ( ke->modifiers() & Qt::AltModifier ? KVM_ALT : KVM_NONE ) | ( ke->modifiers() & Qt::MetaModifier ? KVM_META : KVM_NONE ) | ( ke->modifiers() & Qt::KeypadModifier ? KVM_NUM : KVM_NONE ) // CAPSLOCKは検出できない? //| ( ke->modifiers() & Qt::caps ? KVM_NUM : KVM_NONE ) ); */ //ev.key.unicode = ke->text().utf16()[0]; //#TODO 押されたら色を変える OSD_PushEvent(ev); } <commit_msg>タッチリリースイベントが拾われなかったのを修正<commit_after>#include "virtualkeyitem.h" #include <QDebug> #include <QGraphicsSceneMouseEvent> #include <QTouchEvent> #include <QMessageBox> #include "../osd.h" VirtualKeyItem::VirtualKeyItem(PCKEYsym code, QString pixNormal, QString pixShift, QString pixGrph, QString pixKana, QString pixKanaShift, QString pixKKana, QString pixKKanaShift, bool mouseToggle) : Code(code) , PixNormal(QString(":/res/vkey/key_%1.png").arg(pixNormal)) , PixShift(QString(":/res/vkey/key_%1.png").arg(pixShift)) , PixGrph(QString(":/res/vkey/key_%1.png").arg(pixGrph)) , PixKana(QString(":/res/vkey/key_%1.png").arg(pixKana)) , PixKanaShift(QString(":/res/vkey/key_%1.png").arg(pixKanaShift)) , PixKKana(QString(":/res/vkey/key_%1.png").arg(pixKKana)) , PixKKanaShift(QString(":/res/vkey/key_%1.png").arg(pixKKanaShift)) , MouseToggle(mouseToggle) , ToggleStatus(false) { setPixmap(PixNormal); setTransformationMode(Qt::SmoothTransformation); setFlags(QGraphicsItem::ItemClipsToShape); setAcceptedMouseButtons(Qt::LeftButton); setAcceptTouchEvents(true); } void VirtualKeyItem::changeStatus( bool ON_SHIFT, bool ON_GRAPH, bool ON_KANA, bool ON_KKANA, bool ON_CAPS) { if (ON_KKANA){ if(ON_SHIFT)setPixmap(PixKKanaShift); else setPixmap(PixKKana); } else if (ON_KANA) { if(ON_SHIFT)setPixmap(PixKanaShift); else setPixmap(PixKKana); } else if (ON_GRAPH) { setPixmap(PixGrph); } else if (ON_SHIFT ^ ON_CAPS) { setPixmap(PixShift); } else { setPixmap(PixNormal); } } bool VirtualKeyItem::sceneEvent(QEvent *event) { qDebug() << "sceneEvent accepted:" << event->type(); auto type = event->type(); switch (type){ case QEvent::TouchBegin: case QEvent::TouchEnd: { sendKeyEvent(type == QEvent::TouchBegin ? EV_KEYDOWN : EV_KEYUP, type == QEvent::TouchBegin ? true : false); return true; } default:; } return QGraphicsPixmapItem::sceneEvent(event); } void VirtualKeyItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { qDebug() << "mousePressEvent accepted:" << event->type(); // トグルキーの場合はUP,DOWNを交互に送る auto toggle = MouseToggle && ToggleStatus; if (MouseToggle) ToggleStatus = !ToggleStatus; sendKeyEvent(toggle ? EV_KEYUP : EV_KEYDOWN, MouseToggle ? ToggleStatus : true); QGraphicsPixmapItem::mousePressEvent(event); } void VirtualKeyItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { sendKeyEvent(EV_KEYUP, false); QGraphicsPixmapItem::mouseReleaseEvent(event); } void VirtualKeyItem::sendKeyEvent(EventType type, bool state) { Event ev; ev.type = type; ev.key.state = state; ev.key.sym = Code; ev.key.mod = KVM_NONE; ev.key.unicode = 0; /* ev.key.mod = (PCKEYmod)( ( ke->modifiers() & Qt::ShiftModifier ? KVM_SHIFT : KVM_NONE ) | ( ke->modifiers() & Qt::ControlModifier ? KVM_CTRL : KVM_NONE ) | ( ke->modifiers() & Qt::AltModifier ? KVM_ALT : KVM_NONE ) | ( ke->modifiers() & Qt::MetaModifier ? KVM_META : KVM_NONE ) | ( ke->modifiers() & Qt::KeypadModifier ? KVM_NUM : KVM_NONE ) // CAPSLOCKは検出できない? //| ( ke->modifiers() & Qt::caps ? KVM_NUM : KVM_NONE ) ); */ //ev.key.unicode = ke->text().utf16()[0]; //#TODO 押されたら色を変える OSD_PushEvent(ev); } <|endoftext|>
<commit_before><?hh //strict namespace hhpack\publisher; use ReflectionClass; use ReflectionMethod; final class SubscribeAgent<T as Message> implements Agent<T> { private SubscriptionMap<T> $subscriptions = Map {}; public function __construct( private Subscribable<T> $receiver ) { $class = new ReflectionClass($receiver); $methods = $class->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $parameters = $method->getParameters(); $parameter = $parameters[0]; $type = $parameter->getClass(); $typeName = $parameter->getClass()->getName(); if ($type->implementsInterface(Message::class) === false) { continue; } $subscriptions = $this->subscriptions->get($typeName); if ($subscriptions === null) { $subscriptions = Vector {}; } $subscriptions->add(new InvokeSubscription( Pair { $this->receiver, $method->getName() })); $this->subscriptions->set($typeName, $subscriptions); } } public function matches(Subscribable<T> $subscriber) : bool { return $this->receiver === $subscriber; } public function receive(T $message) : void { $nameOfType = get_class($message); if ($this->subscriptions->containsKey($nameOfType) === false) { return; } $subscriptions = $this->subscriptions->at($nameOfType); foreach ($subscriptions->items() as $subscription) { $subscription->receive($message); } } } <commit_msg>Rename arguemnts<commit_after><?hh //strict namespace hhpack\publisher; use ReflectionClass; use ReflectionMethod; final class SubscribeAgent<T as Message> implements Agent<T> { private SubscriptionMap<T> $subscriptions = Map {}; public function __construct( private Subscribable<T> $subscriber ) { $class = new ReflectionClass($subscriber); $methods = $class->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $parameters = $method->getParameters(); $parameter = $parameters[0]; $type = $parameter->getClass(); $typeName = $parameter->getClass()->getName(); if ($type->implementsInterface(Message::class) === false) { continue; } $subscriptions = $this->subscriptions->get($typeName); if ($subscriptions === null) { $subscriptions = Vector {}; } $subscriptions->add(new InvokeSubscription( Pair { $this->subscriber, $method->getName() })); $this->subscriptions->set($typeName, $subscriptions); } } public function matches(Subscribable<T> $subscriber) : bool { return $this->subscriber === $subscriber; } public function receive(T $message) : void { $nameOfType = get_class($message); if ($this->subscriptions->containsKey($nameOfType) === false) { return; } $subscriptions = $this->subscriptions->at($nameOfType); foreach ($subscriptions->items() as $subscription) { $subscription->receive($message); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2017 InversePalindrome VariadicPoker - Deck.cpp InversePalindrome.com */ #include "Deck.hpp" Deck::Deck() : deck() { for (int suit = Card::Spade; suit <= Card::Heart; suit++) { for (int rank = Card::Two; rank <= Card::Ace; rank++) { deck.push_back(Card((Card::Suit)suit, (Card::Rank)rank)); } } } Deck::Deck(const std::vector<Card>& deck) : deck(deck) { } std::vector<Card> Deck::getDeck() const { return this->deck; } std::size_t Deck::getSize() const { return this->deck.size(); } Card Deck::dealCard() { Card card(this->deck.back()); this->removeCard(); return card; } void Deck::setDeck(const std::vector<Card>& deck) { this->deck = deck; } void Deck::shuffle() { std::shuffle(this->deck.begin(), this->deck.end(), std::default_random_engine{}); } void Deck::removeCard() { this->deck.pop_back(); } void Deck::removeCard(const Card& card) { this->deck.erase(std::remove(this->deck.begin(), this->deck.end(), card), this->deck.end()); } void Deck::addCard(const Card& card) { this->deck.push_back(card); } <commit_msg>Added utility methods<commit_after>/* Copyright (c) 2017 InversePalindrome VariadicPoker - Deck.cpp InversePalindrome.com */ #include "Deck.hpp" Deck::Deck() : deck() { for (int suit = Card::Spade; suit <= Card::Heart; suit++) { for (int rank = Card::Two; rank <= Card::Ace; rank++) { deck.push_back(Card((Card::Suit)suit, (Card::Rank)rank)); } } } Deck::Deck(const std::vector<Card>& deck) : deck(deck) { } std::vector<Card> Deck::getDeck() const { return this->deck; } std::vector<Card> Deck::getCards(std::size_t numOfCards) const { if (numOfCards > 0 && numOfCards <= this->deck.size()) { return std::vector<Card>(this->deck.end() - numOfCards , this->deck.end()); } return {}; } Card Deck::getCard() const { return this->deck.back(); } std::size_t Deck::getSize() const { return this->deck.size(); } void Deck::setDeck(const std::vector<Card>& deck) { this->deck = deck; } void Deck::shuffle() { std::shuffle(this->deck.begin(), this->deck.end(), std::default_random_engine{}); } void Deck::removeCard(const Card& card) { this->deck.erase(std::remove(this->deck.begin(), this->deck.end(), card), this->deck.end()); } void Deck::removeCards(std::size_t numOfCards) { this->deck.resize(this->deck.size() - numOfCards); } void Deck::clearDeck() { this->deck.clear(); } void Deck::addCard(const Card& card) { this->deck.push_back(card); } void Deck::addCards(const std::vector<Card>& cards) { this->deck.insert(this->deck.begin(), cards.begin(), cards.end()); } bool Deck::hasCards() const { return !this->deck.empty(); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "S3ExtWrapper.cpp" class S3Reader_fake : public S3Reader { public: S3Reader_fake(const char *url); virtual ~S3Reader_fake(); virtual bool Init(int segid, int segnum, int chunksize); virtual bool Destroy(); protected: virtual string getKeyURL(const string &key); virtual bool ValidateURL(); }; S3Reader_fake::S3Reader_fake(const char *url) : S3Reader(url) {} S3Reader_fake::~S3Reader_fake() {} bool S3Reader_fake::Destroy() { // reset filedownloader if (this->filedownloader) { this->filedownloader->destroy(); delete this->filedownloader; } // Free keylist if (this->keylist) { delete this->keylist; } return true; } bool S3Reader_fake::Init(int segid, int segnum, int chunksize) { // set segment id and num this->segid = segid; // fake this->segnum = segnum; // fake this->contentindex = this->segid; this->chunksize = chunksize; // Validate url first if (!this->ValidateURL()) { EXTLOG("validate url fail %s\n", this->url.c_str()); } // TODO: As separated function for generating url this->keylist = ListBucket_FakeHTTP("localhost", this->bucket.c_str()); if (!this->keylist) { return false; } this->getNextDownloader(); return this->filedownloader ? true : false; } string S3Reader_fake::getKeyURL(const string &key) { stringstream sstr; sstr << this->schema << "://" << "localhost/"; sstr << this->bucket << "/" << key; return sstr.str(); } bool S3Reader_fake::ValidateURL() { this->schema = "http"; this->region = "raycom"; int ibegin,iend; ibegin = find_Nth(this->url, 3, "/"); iend = find_Nth(this->url, 4, "/"); if ((iend == string::npos) || (ibegin == string::npos)) { return false; } this->bucket = url.substr(ibegin + 1, iend - ibegin - 1); this->prefix = ""; return true; } void ExtWrapperTest(const char *url, uint64_t buffer_size, const char *md5_str, int segid, int segnum, uint64_t chunksize) { MD5Calc m; S3ExtBase *myData; uint64_t nread = 0; uint64_t buf_len = buffer_size; char *buf = (char *)malloc(buffer_size); ASSERT_NE((void *)NULL, buf); InitLog(); if (strncmp(url, "http://localhost/", 17) == 0) { myData = new S3Reader_fake(url); } else { myData = new S3Reader(url); } ASSERT_NE((void *)NULL, myData); ASSERT_TRUE(myData->Init(segid, segnum, chunksize)); while (1) { nread = buf_len; myData->TransferData(buf, nread); if (nread == 0) break; m.Update(buf, nread); } EXPECT_STREQ(md5_str, m.Get()); delete myData; free(buf); } #ifdef AWSTEST TEST(ExtWrapper, normal) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "138fc555074671912125ba692c678246", 0, 1, 64*1024*1024); } TEST(ExtWrapper, normal_2segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "a861acda78891b48b25a2788e028a740", 0, 2, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "db05de0ec7e0808268e2363d3572dc7f", 1, 2, 64*1024*1024); } TEST(ExtWrapper, normal_3segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "4d9ccad20bca50d2d1bc9c4eb4958e2c", 0, 3, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "561597859d093905e2b21e896259ae79", 1, 3, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "98d4e5348356ceee46d15c4e5f37845b", 2, 3, 64*1024*1024); } TEST(ExtWrapper, normal_4segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "b87b5d79e2bcb8dc1d0fd289fbfa5829", 0, 4, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "4df154611d394c60084bb5b97bdb19be", 1, 4, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "238affbb831ff27df9d09afeeb2e59f9", 2, 4, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "dceb001d03d54d61874d27c9f04596b1", 3, 4, 64*1024*1024); } #endif // AWSTEST TEST(FakeExtWrapper, simple) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "138fc555074671912125ba692c678246", 0, 1, 64*1024*1024); } TEST(FakeExtWrapper, normal_2segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "a861acda78891b48b25a2788e028a740", 0, 2, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "db05de0ec7e0808268e2363d3572dc7f", 1, 2, 64*1024*1024); } TEST(FakeExtWrapper, normal_3segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "4d9ccad20bca50d2d1bc9c4eb4958e2c", 0, 3, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "561597859d093905e2b21e896259ae79", 1, 3, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "98d4e5348356ceee46d15c4e5f37845b", 2, 3, 64*1024*1024); } TEST(FakeExtWrapper, normal_4segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "b87b5d79e2bcb8dc1d0fd289fbfa5829", 0, 4, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "4df154611d394c60084bb5b97bdb19be", 1, 4, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "238affbb831ff27df9d09afeeb2e59f9", 2, 4, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "dceb001d03d54d61874d27c9f04596b1", 3, 4, 64*1024*1024); } TEST(FakeExtWrapper, bigfile) { ExtWrapperTest("http://localhost/bigfile/", 64 * 1024, "83c7ab787e3f1d1e7880dcae954ab4a4", 0, 1, 64*1024*1024); } <commit_msg>fix download test hang<commit_after>#include "gtest/gtest.h" #include "S3ExtWrapper.cpp" class S3Reader_fake : public S3Reader { public: S3Reader_fake(const char *url); virtual ~S3Reader_fake(); virtual bool Init(int segid, int segnum, int chunksize); virtual bool Destroy(); protected: virtual string getKeyURL(const string &key); virtual bool ValidateURL(); }; S3Reader_fake::S3Reader_fake(const char *url) : S3Reader(url) {} S3Reader_fake::~S3Reader_fake() {} bool S3Reader_fake::Destroy() { // reset filedownloader if (this->filedownloader) { this->filedownloader->destroy(); delete this->filedownloader; } // Free keylist if (this->keylist) { delete this->keylist; } return true; } bool S3Reader_fake::Init(int segid, int segnum, int chunksize) { // set segment id and num this->segid = segid; // fake this->segnum = segnum; // fake this->contentindex = this->segid; this->chunksize = chunksize; // Validate url first if (!this->ValidateURL()) { EXTLOG("validate url fail %s\n", this->url.c_str()); } // TODO: As separated function for generating url this->keylist = ListBucket_FakeHTTP("localhost", this->bucket.c_str()); //this->keylist = ListBucket_FakeHTTP("localhost", "metro.pivotal.io"); if (!this->keylist) { return false; } this->getNextDownloader(); return this->filedownloader ? true : false; } string S3Reader_fake::getKeyURL(const string &key) { stringstream sstr; sstr << this->schema << "://" << "localhost/"; sstr << this->bucket << "/" << key; return sstr.str(); } bool S3Reader_fake::ValidateURL() { this->schema = "http"; this->region = "raycom"; int ibegin,iend; ibegin = find_Nth(this->url, 3, "/"); iend = find_Nth(this->url, 4, "/"); if ((iend == string::npos) || (ibegin == string::npos)) { return false; } this->bucket = url.substr(ibegin + 1, iend - ibegin - 1); this->prefix = ""; return true; } void ExtWrapperTest(const char *url, uint64_t buffer_size, const char *md5_str, int segid, int segnum, uint64_t chunksize) { MD5Calc m; S3ExtBase *myData; uint64_t nread = 0; uint64_t buf_len = buffer_size; char *buf = (char *)malloc(buffer_size); ASSERT_NE((void *)NULL, buf); InitLog(); if (strncmp(url, "http://localhost/", 17) == 0) { myData = new S3Reader_fake(url); } else { myData = new S3Reader(url); } ASSERT_NE((void *)NULL, myData); ASSERT_TRUE(myData->Init(segid, segnum, chunksize)); while (1) { nread = buf_len; ASSERT_TRUE(myData->TransferData(buf, nread)); if (nread == 0) break; m.Update(buf, nread); } EXPECT_STREQ(md5_str, m.Get()); delete myData; free(buf); } #ifdef AWSTEST TEST(ExtWrapper, normal) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "138fc555074671912125ba692c678246", 0, 1, 64*1024*1024); } TEST(ExtWrapper, normal_2segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "a861acda78891b48b25a2788e028a740", 0, 2, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "db05de0ec7e0808268e2363d3572dc7f", 1, 2, 64*1024*1024); } TEST(ExtWrapper, normal_3segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "4d9ccad20bca50d2d1bc9c4eb4958e2c", 0, 3, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "561597859d093905e2b21e896259ae79", 1, 3, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "98d4e5348356ceee46d15c4e5f37845b", 2, 3, 64*1024*1024); } TEST(ExtWrapper, normal_4segs) { ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "b87b5d79e2bcb8dc1d0fd289fbfa5829", 0, 4, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "4df154611d394c60084bb5b97bdb19be", 1, 4, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "238affbb831ff27df9d09afeeb2e59f9", 2, 4, 64*1024*1024); ExtWrapperTest("http://s3-us-west-2.amazonaws.com/metro.pivotal.io/data/", 64 * 1024, "dceb001d03d54d61874d27c9f04596b1", 3, 4, 64*1024*1024); } #endif // AWSTEST TEST(FakeExtWrapper, simple) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "138fc555074671912125ba692c678246", 0, 1, 64*1024*1024); } TEST(FakeExtWrapper, normal_2segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "a861acda78891b48b25a2788e028a740", 0, 2, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "db05de0ec7e0808268e2363d3572dc7f", 1, 2, 64*1024*1024); } TEST(FakeExtWrapper, normal_3segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "4d9ccad20bca50d2d1bc9c4eb4958e2c", 0, 3, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "561597859d093905e2b21e896259ae79", 1, 3, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "98d4e5348356ceee46d15c4e5f37845b", 2, 3, 64*1024*1024); } TEST(FakeExtWrapper, normal_4segs) { ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "b87b5d79e2bcb8dc1d0fd289fbfa5829", 0, 4, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "4df154611d394c60084bb5b97bdb19be", 1, 4, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "238affbb831ff27df9d09afeeb2e59f9", 2, 4, 64*1024*1024); ExtWrapperTest("http://localhost/metro.pivotal.io/", 64 * 1024, "dceb001d03d54d61874d27c9f04596b1", 3, 4, 64*1024*1024); } TEST(FakeExtWrapper, bigfile) { ExtWrapperTest("http://localhost/bigfile/", 64 * 1024, "83c7ab787e3f1d1e7880dcae954ab4a4", 0, 1, 64*1024*1024); } <|endoftext|>
<commit_before>#include <QDebug> #include <QMutexLocker> #include <QCoreApplication> #include <sstream> #include <iostream> #include "DownloadManager.h" #include "Util.h" #include "Downloader.h" using namespace efdl; DownloadManager::DownloadManager(bool dryRun, bool connProg) : dryRun{dryRun}, connProg{connProg}, chksum{false}, conns{0}, chunksAmount{0}, chunksFinished{0}, size{0}, offset{0}, bytesDown{0}, hashAlg{QCryptographicHash::Sha3_512}, downloader{nullptr} { } DownloadManager::~DownloadManager() { cleanup(); qDeleteAll(queue); } void DownloadManager::add(Downloader *entry) { queue << entry; } void DownloadManager::setVerifcations(const QList<HashPair> &pairs) { verifyList = pairs; } void DownloadManager::createChecksum(QCryptographicHash::Algorithm hashAlg) { this->hashAlg = hashAlg; chksum = true; } void DownloadManager::start() { next(); } void DownloadManager::next() { static bool first{true}; if (!first) { if (!dryRun) { // Update progress with total download time with no connection // lines. bool tmp{connProg}; connProg = false; lastProgress = QDateTime(); // Force update. updateProgress(); connProg = tmp; if (!verifyList.isEmpty()) { verifyIntegrity(verifyList.takeFirst()); } if (chksum) printChecksum(); } // Separate each download with a newline. if (!queue.isEmpty()) qDebug(); } if (first) first = false; if (queue.isEmpty()) { emit finished(); return; } cleanup(); downloader = queue.dequeue(); qDebug() << "Downloading" << qPrintable(downloader->getUrl().toString(QUrl::FullyEncoded)); connect(downloader, &Downloader::finished, this, &DownloadManager::next); connect(downloader, &Downloader::information, this, &DownloadManager::onInformation); connect(downloader, &Downloader::chunkStarted, this, &DownloadManager::onChunkStarted); connect(downloader, &Downloader::chunkProgress, this, &DownloadManager::onChunkProgress); connect(downloader, &Downloader::chunkFinished, this, &DownloadManager::onChunkFinished); connect(downloader, &Downloader::chunkFailed, this, &DownloadManager::onChunkFailed); downloader->start(); started = QDateTime::currentDateTime(); } void DownloadManager::onInformation(const QString &outputPath, qint64 size, int chunksAmount, int conns, qint64 offset) { this->outputPath = outputPath; this->size = size; this->chunksAmount = chunksAmount; this->conns = conns; this->offset = offset; updateProgress(); } void DownloadManager::onChunkStarted(int num) { QMutexLocker locker{&chunkMutex}; chunkMap[num] = new Chunk{Range{0, 0}, QDateTime::currentDateTime()}; updateChunkMap(); updateProgress(); } void DownloadManager::onChunkProgress(int num, qint64 received, qint64 total) { QMutexLocker locker{&chunkMutex}; Chunk *chunk = chunkMap[num]; bytesDown += received - chunk->range.first; chunk->range = Range{received, total}; updateChunkMap(); updateProgress(); } void DownloadManager::onChunkFinished(int num, Range range) { QMutexLocker locker{&chunkMutex}; chunksFinished++; updateChunkMap(); updateProgress(); } void DownloadManager::onChunkFailed(int num, Range range, int httpCode, QNetworkReply::NetworkError error) { QMutexLocker locker{&chunkMutex}; qCritical() << "Chunk" << num << "failed on range" << range; qCritical() << "HTTP code:" << httpCode; qCritical() << "Error:" << qPrintable(Util::getErrorString(error)); qCritical() << "Aborting.."; cleanup(); QCoreApplication::exit(-1); } void DownloadManager::cleanup() { chunksAmount = chunksFinished = size = offset = bytesDown = 0; qDeleteAll(chunkMap); chunkMap.clear(); if (downloader) { downloader->disconnect(); downloader->deleteLater(); downloader = nullptr; } } void DownloadManager::updateChunkMap() { if (chunkMap.size() <= conns) { return; } bool rem = false; foreach (const auto &key, chunkMap.keys()) { const auto *chunk = chunkMap[key]; if (chunk->isDone()) { rem = true; chunkMap.remove(key); delete chunk; break; } } if (!rem) { delete chunkMap.take(chunkMap.firstKey()); } if (chunkMap.size() > conns) { updateChunkMap(); } } void DownloadManager::updateProgress() { // Only update progress every half second. QDateTime now{QDateTime::currentDateTime()}; if (!lastProgress.isNull() && lastProgress.msecsTo(now) < 500) { return; } lastProgress = now; using namespace std; stringstream sstream; // Set fixed float formatting to one decimal digit. sstream.precision(1); sstream.setf(ios::fixed, ios::floatfield); // Color escape codes. static const string nw{"\033[0;37m"}, // normal, white bw{"\033[1;37m"}; // bold, white sstream << nw << "[ "; if (bytesDown == 0) { sstream << "Starting up download.."; } else { bool done = (bytesDown + offset == size); qint64 secs{started.secsTo(now)}, bytesPrSec{0}, secsLeft{0}; if (secs > 0) { bytesPrSec = bytesDown / secs; if (bytesPrSec > 0) { secsLeft = (!done ? (size - bytesDown - offset) / bytesPrSec : secs); } } float perc = (long double)(bytesDown + offset) / (long double)size * 100.0; sstream << bw << perc << "%" << nw << " | " << (!done ? Util::formatSize(bytesDown + offset, 1).toStdString()+ " / " : "") << Util::formatSize(size, 1).toStdString() << " @ " << bw << Util::formatSize(bytesPrSec, 1).toStdString() << "/s" << nw << " | " << (!done ? QString("chunk %1 / %2").arg(chunksFinished).arg(chunksAmount).toStdString() : QString("%1 chunks").arg(chunksAmount).toStdString()) << " | " << bw << Util::formatTime(secsLeft).toStdString() << " " << nw << (!done ? "left" : "total"); } sstream << " ]"; if (connProg) { foreach (const int &num, chunkMap.keys()) { auto *chunk = chunkMap[num]; qint64 received = chunk->range.first, total = chunk->range.second; bool done = chunk->isDone(); if (done && chunk->ended.isNull()) { chunk->ended = now; } qint64 secs{chunk->started.secsTo(done ? chunk->ended : now)}, bytesPrSec{0}, secsLeft{0}; if (secs > 0) { bytesPrSec = received / secs; if (bytesPrSec > 0) { secsLeft = (!done ? (total - received) / bytesPrSec : secs); } } float perc{0}; if (received > 0 && total > 0) { perc = (long double) received / (long double) total * 100.0; } sstream << "\n{ chunk #" << num << ": " << perc << "% "; if (total > 0) { sstream << "| " << (!done ? Util::formatSize(received, 1).toStdString() + " / " : "") << Util::formatSize(total, 1).toStdString() << " @ " << Util::formatSize(bytesPrSec, 1).toStdString() << "/s | " << Util::formatTime(secsLeft).toStdString() << " " << (!done ? "left" : "total") << " "; } sstream << "}"; } } sstream << '\n'; static int lastLines{0}; string msg{sstream.str()}; // Remove additional lines, if any. for (int i = 0; i < lastLines; i++) { cout << "\033[A" // Go up a line (\033 = ESC, [ = CTRL). << "\033[2K"; // Kill line. } // Rewind to beginning with carriage return and write actual // message. cout << '\r' << msg; cout.flush(); lastLines = QString(msg.c_str()).split("\n").size() - 1; } void DownloadManager::verifyIntegrity(const HashPair &pair) { QString hash{Util::hashFile(outputPath, pair.first)}; if (hash.isEmpty()) return; if (hash == pair.second) { qDebug() << "Verified:" << qPrintable(pair.second); } else { qDebug() << "Failed to verify:" << qPrintable(pair.second); qDebug() << "Was:" << qPrintable(hash); } } void DownloadManager::printChecksum() { QByteArray hash{Util::hashFile(outputPath, hashAlg)}; if (hash.isEmpty()) return; qDebug() << "Checksum:" << qPrintable(hash); } <commit_msg>Use colors when checking integrity.<commit_after>#include <QDebug> #include <QMutexLocker> #include <QCoreApplication> #include <sstream> #include <iostream> #include "DownloadManager.h" #include "Util.h" #include "Downloader.h" using namespace efdl; DownloadManager::DownloadManager(bool dryRun, bool connProg) : dryRun{dryRun}, connProg{connProg}, chksum{false}, conns{0}, chunksAmount{0}, chunksFinished{0}, size{0}, offset{0}, bytesDown{0}, hashAlg{QCryptographicHash::Sha3_512}, downloader{nullptr} { } DownloadManager::~DownloadManager() { cleanup(); qDeleteAll(queue); } void DownloadManager::add(Downloader *entry) { queue << entry; } void DownloadManager::setVerifcations(const QList<HashPair> &pairs) { verifyList = pairs; } void DownloadManager::createChecksum(QCryptographicHash::Algorithm hashAlg) { this->hashAlg = hashAlg; chksum = true; } void DownloadManager::start() { next(); } void DownloadManager::next() { static bool first{true}; if (!first) { if (!dryRun) { // Update progress with total download time with no connection // lines. bool tmp{connProg}; connProg = false; lastProgress = QDateTime(); // Force update. updateProgress(); connProg = tmp; if (!verifyList.isEmpty()) { verifyIntegrity(verifyList.takeFirst()); } if (chksum) printChecksum(); } // Separate each download with a newline. if (!queue.isEmpty()) qDebug(); } if (first) first = false; if (queue.isEmpty()) { emit finished(); return; } cleanup(); downloader = queue.dequeue(); qDebug() << "Downloading" << qPrintable(downloader->getUrl().toString(QUrl::FullyEncoded)); connect(downloader, &Downloader::finished, this, &DownloadManager::next); connect(downloader, &Downloader::information, this, &DownloadManager::onInformation); connect(downloader, &Downloader::chunkStarted, this, &DownloadManager::onChunkStarted); connect(downloader, &Downloader::chunkProgress, this, &DownloadManager::onChunkProgress); connect(downloader, &Downloader::chunkFinished, this, &DownloadManager::onChunkFinished); connect(downloader, &Downloader::chunkFailed, this, &DownloadManager::onChunkFailed); downloader->start(); started = QDateTime::currentDateTime(); } void DownloadManager::onInformation(const QString &outputPath, qint64 size, int chunksAmount, int conns, qint64 offset) { this->outputPath = outputPath; this->size = size; this->chunksAmount = chunksAmount; this->conns = conns; this->offset = offset; updateProgress(); } void DownloadManager::onChunkStarted(int num) { QMutexLocker locker{&chunkMutex}; chunkMap[num] = new Chunk{Range{0, 0}, QDateTime::currentDateTime()}; updateChunkMap(); updateProgress(); } void DownloadManager::onChunkProgress(int num, qint64 received, qint64 total) { QMutexLocker locker{&chunkMutex}; Chunk *chunk = chunkMap[num]; bytesDown += received - chunk->range.first; chunk->range = Range{received, total}; updateChunkMap(); updateProgress(); } void DownloadManager::onChunkFinished(int num, Range range) { QMutexLocker locker{&chunkMutex}; chunksFinished++; updateChunkMap(); updateProgress(); } void DownloadManager::onChunkFailed(int num, Range range, int httpCode, QNetworkReply::NetworkError error) { QMutexLocker locker{&chunkMutex}; qCritical() << "Chunk" << num << "failed on range" << range; qCritical() << "HTTP code:" << httpCode; qCritical() << "Error:" << qPrintable(Util::getErrorString(error)); qCritical() << "Aborting.."; cleanup(); QCoreApplication::exit(-1); } void DownloadManager::cleanup() { chunksAmount = chunksFinished = size = offset = bytesDown = 0; qDeleteAll(chunkMap); chunkMap.clear(); if (downloader) { downloader->disconnect(); downloader->deleteLater(); downloader = nullptr; } } void DownloadManager::updateChunkMap() { if (chunkMap.size() <= conns) { return; } bool rem = false; foreach (const auto &key, chunkMap.keys()) { const auto *chunk = chunkMap[key]; if (chunk->isDone()) { rem = true; chunkMap.remove(key); delete chunk; break; } } if (!rem) { delete chunkMap.take(chunkMap.firstKey()); } if (chunkMap.size() > conns) { updateChunkMap(); } } void DownloadManager::updateProgress() { // Only update progress every half second. QDateTime now{QDateTime::currentDateTime()}; if (!lastProgress.isNull() && lastProgress.msecsTo(now) < 500) { return; } lastProgress = now; using namespace std; stringstream sstream; // Set fixed float formatting to one decimal digit. sstream.precision(1); sstream.setf(ios::fixed, ios::floatfield); // Color escape codes. static const string nw{"\033[0;37m"}, // normal, white bw{"\033[1;37m"}; // bold, white sstream << nw << "[ "; if (bytesDown == 0) { sstream << "Starting up download.."; } else { bool done = (bytesDown + offset == size); qint64 secs{started.secsTo(now)}, bytesPrSec{0}, secsLeft{0}; if (secs > 0) { bytesPrSec = bytesDown / secs; if (bytesPrSec > 0) { secsLeft = (!done ? (size - bytesDown - offset) / bytesPrSec : secs); } } float perc = (long double)(bytesDown + offset) / (long double)size * 100.0; sstream << bw << perc << "%" << nw << " | " << (!done ? Util::formatSize(bytesDown + offset, 1).toStdString()+ " / " : "") << Util::formatSize(size, 1).toStdString() << " @ " << bw << Util::formatSize(bytesPrSec, 1).toStdString() << "/s" << nw << " | " << (!done ? QString("chunk %1 / %2").arg(chunksFinished).arg(chunksAmount).toStdString() : QString("%1 chunks").arg(chunksAmount).toStdString()) << " | " << bw << Util::formatTime(secsLeft).toStdString() << " " << nw << (!done ? "left" : "total"); } sstream << " ]"; if (connProg) { foreach (const int &num, chunkMap.keys()) { auto *chunk = chunkMap[num]; qint64 received = chunk->range.first, total = chunk->range.second; bool done = chunk->isDone(); if (done && chunk->ended.isNull()) { chunk->ended = now; } qint64 secs{chunk->started.secsTo(done ? chunk->ended : now)}, bytesPrSec{0}, secsLeft{0}; if (secs > 0) { bytesPrSec = received / secs; if (bytesPrSec > 0) { secsLeft = (!done ? (total - received) / bytesPrSec : secs); } } float perc{0}; if (received > 0 && total > 0) { perc = (long double) received / (long double) total * 100.0; } sstream << "\n{ chunk #" << num << ": " << perc << "% "; if (total > 0) { sstream << "| " << (!done ? Util::formatSize(received, 1).toStdString() + " / " : "") << Util::formatSize(total, 1).toStdString() << " @ " << Util::formatSize(bytesPrSec, 1).toStdString() << "/s | " << Util::formatTime(secsLeft).toStdString() << " " << (!done ? "left" : "total") << " "; } sstream << "}"; } } sstream << '\n'; static int lastLines{0}; string msg{sstream.str()}; // Remove additional lines, if any. for (int i = 0; i < lastLines; i++) { cout << "\033[A" // Go up a line (\033 = ESC, [ = CTRL). << "\033[2K"; // Kill line. } // Rewind to beginning with carriage return and write actual // message. cout << '\r' << msg; cout.flush(); lastLines = QString(msg.c_str()).split("\n").size() - 1; } void DownloadManager::verifyIntegrity(const HashPair &pair) { QString hash{Util::hashFile(outputPath, pair.first)}; if (hash.isEmpty()) return; if (hash == pair.second) { qDebug() << "\033[1;32mVerified:\033[0;37m" << qPrintable(pair.second); } else { qDebug().nospace() << "\033[1;31mFailed to verify:\033[0;37m " << qPrintable(pair.second) << " (was " << qPrintable(hash) << ")"; } } void DownloadManager::printChecksum() { QByteArray hash{Util::hashFile(outputPath, hashAlg)}; if (hash.isEmpty()) return; qDebug() << "Checksum:" << qPrintable(hash); } <|endoftext|>
<commit_before>#include "Leap.h" #include "util.h" #include "GMod_LeapFrame.h" #include "GMod_LeapHand.h" #include "GMod_LeapFinger.h" #include "GMod_LeapBone.h" using namespace GarrysMod; using namespace Leap; using namespace GModLeap; int LeapFinger::TYPE = 101; //random void LeapFinger::DefineMeta( lua_State *state ) { LUA->CreateMetaTableType( "LeapFinger" , LeapFinger::TYPE ); LUA->Push( -1 ); LUA->SetField( -2 , "__index" ); LUA->PushCFunction( LeapFinger::tostring ); LUA->SetField( -2 , "__tostring" ); LUA->PushString( "LeapFinger" ); LUA->SetField( -2 , "__type" ); LUA->PushCFunction(LeapFinger::Bone); LUA->SetField( -2, "GetBone" ); LUA->PushCFunction( LeapFinger::Direction ); LUA->SetField( -2, "Direction" ); LUA->PushCFunction( LeapFinger::Frame ); LUA->SetField( -2, "GetFrame" ); LUA->PushCFunction( LeapFinger::Hand ); LUA->SetField( -2, "GetHand" ); LUA->PushCFunction( LeapFinger::ID ); LUA->SetField( -2, "ID" ); LUA->PushCFunction( LeapFinger::IsExtended ); LUA->SetField( -2, "IsExtended" ); LUA->PushCFunction( LeapFinger::IsFinger ); LUA->SetField( -2, "IsFinger" ); LUA->PushCFunction( LeapFinger::IsTool ); LUA->SetField( -2, "IsTool" ); LUA->PushCFunction( LeapFinger::IsValid ); LUA->SetField( -2, "IsValid" ); LUA->PushCFunction( LeapFinger::Length ); LUA->SetField( -2, "Length" ); LUA->PushCFunction( LeapFinger::StabilizedTipPosition ); LUA->SetField( -2, "StabilizedTipPosition" ); LUA->PushCFunction( LeapFinger::TimeVisible ); LUA->SetField( -2, "TimeVisible" ); LUA->PushCFunction( LeapFinger::TipPosition ); LUA->SetField( -2, "TipPosition" ); LUA->PushCFunction( LeapFinger::TipVelocity ); LUA->SetField( -2, "TipVelocity" ); LUA->PushCFunction( LeapFinger::TouchDistance ); LUA->SetField( -2, "TouchDistance" ); LUA->PushCFunction( LeapFinger::TouchZone ); LUA->SetField( -2, "TouchZone" ); LUA->PushCFunction( LeapFinger::Type ); LUA->SetField( -2, "Type" ); LUA->PushCFunction( LeapFinger::Width ); LUA->SetField( -2, "Width" ); LUA->Pop(); } Finger *LeapFinger::Get( lua_State *state , int pos ) { if ( !LUA->IsType( pos , LeapFinger::TYPE ) ) return nullptr; Lua::UserData *ud = ( Lua::UserData * ) LUA->GetUserdata(); if ( !ud ) return nullptr; Finger *finger = ( Finger * ) ud->data; if ( !finger ) return nullptr; return finger; } void LeapFinger::Push( lua_State * state, Leap::Finger *finger ) { if ( !finger ) return; Lua::UserData *ud = ( Lua::UserData * )LUA->NewUserdata( sizeof( Lua::UserData ) ); ud->data = finger; ud->type = LeapFinger::TYPE; LUA->CreateMetaTableType( "LeapFinger" , LeapFinger::TYPE ); LUA->SetMetaTable( -2 ); } int LeapFinger::tostring( lua_State *state) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushString( finger->toString().c_str() ); return 1; } int LeapFinger::Bone( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LeapBone::Push( state, new Leap::Bone( finger->bone( ( Bone::Type ) LUA->CheckNumber() ) ) ); return 1; } int LeapFinger::Direction( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; PushSourceVector( state, new Vector( finger->direction() ) ); return 1; } int LeapFinger::Frame( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LeapFrame::Push( state, new Leap::Frame( finger->frame() ) ); return 1; } int LeapFinger::Hand( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LeapHand::Push( state, new Leap::Hand( finger->hand() ) ); return 1; } int LeapFinger::ID( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber( finger->id() ); return 1; } int LeapFinger::IsExtended( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushBool( finger->isExtended() ); return 1; } int LeapFinger::IsFinger( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushBool( finger->isFinger() ); return 1; } int LeapFinger::IsTool( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushBool( finger->isTool() ); return 1; } int LeapFinger::IsValid( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushBool( finger->isValid() ); return 1; } int LeapFinger::Length( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber( finger->length() ); return 1; } int LeapFinger::StabilizedTipPosition( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; PushSourceVector( state, new Vector( finger->stabilizedTipPosition() ) ); return 1; } int LeapFinger::TimeVisible( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber( finger->timeVisible() ); return 1; } int LeapFinger::TipPosition( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; PushSourceVector( state, new Vector( finger->tipPosition() ) ); return 1; } int LeapFinger::TipVelocity( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; PushSourceVector( state, new Vector( finger->tipVelocity() ) ); return 1; } int LeapFinger::TouchDistance( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber( finger->touchDistance() ); return 1; } int LeapFinger::TouchZone( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; //TODO return 1; } int LeapFinger::Type( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; //TODO return 1; } int LeapFinger::Width( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber(finger->width()); return 1; }<commit_msg>fixxx<commit_after>#include "Leap.h" #include "util.h" #include "GMod_LeapFrame.h" #include "GMod_LeapHand.h" #include "GMod_LeapFinger.h" #include "GMod_LeapBone.h" using namespace GarrysMod; using namespace Leap; using namespace GModLeap; int LeapFinger::TYPE = 101; //random void LeapFinger::DefineMeta( lua_State *state ) { LUA->CreateMetaTableType( "LeapFinger" , LeapFinger::TYPE ); LUA->Push( -1 ); LUA->SetField( -2 , "__index" ); LUA->PushCFunction( LeapFinger::tostring ); LUA->SetField( -2 , "__tostring" ); LUA->PushString( "LeapFinger" ); LUA->SetField( -2 , "__type" ); LUA->PushCFunction(LeapFinger::Bone); LUA->SetField( -2, "GetBone" ); LUA->PushCFunction( LeapFinger::Direction ); LUA->SetField( -2, "Direction" ); LUA->PushCFunction( LeapFinger::Frame ); LUA->SetField( -2, "GetFrame" ); LUA->PushCFunction( LeapFinger::Hand ); LUA->SetField( -2, "GetHand" ); LUA->PushCFunction( LeapFinger::ID ); LUA->SetField( -2, "ID" ); LUA->PushCFunction( LeapFinger::IsExtended ); LUA->SetField( -2, "IsExtended" ); LUA->PushCFunction( LeapFinger::IsFinger ); LUA->SetField( -2, "IsFinger" ); LUA->PushCFunction( LeapFinger::IsTool ); LUA->SetField( -2, "IsTool" ); LUA->PushCFunction( LeapFinger::IsValid ); LUA->SetField( -2, "IsValid" ); LUA->PushCFunction( LeapFinger::Length ); LUA->SetField( -2, "Length" ); LUA->PushCFunction( LeapFinger::StabilizedTipPosition ); LUA->SetField( -2, "StabilizedTipPosition" ); LUA->PushCFunction( LeapFinger::TimeVisible ); LUA->SetField( -2, "TimeVisible" ); LUA->PushCFunction( LeapFinger::TipPosition ); LUA->SetField( -2, "TipPosition" ); LUA->PushCFunction( LeapFinger::TipVelocity ); LUA->SetField( -2, "TipVelocity" ); LUA->PushCFunction( LeapFinger::TouchDistance ); LUA->SetField( -2, "TouchDistance" ); LUA->PushCFunction( LeapFinger::TouchZone ); LUA->SetField( -2, "TouchZone" ); LUA->PushCFunction( LeapFinger::Type ); LUA->SetField( -2, "Type" ); LUA->PushCFunction( LeapFinger::Width ); LUA->SetField( -2, "Width" ); LUA->Pop(); } Finger *LeapFinger::Get( lua_State *state , int pos ) { if ( !LUA->IsType( pos , LeapFinger::TYPE ) ) return nullptr; Lua::UserData *ud = ( Lua::UserData * ) LUA->GetUserdata(); if ( !ud ) return nullptr; Finger *finger = ( Finger * ) ud->data; if ( !finger ) return nullptr; return finger; } void LeapFinger::Push( lua_State * state, Leap::Finger *finger ) { if ( !finger ) return; Lua::UserData *ud = ( Lua::UserData * )LUA->NewUserdata( sizeof( Lua::UserData ) ); ud->data = finger; ud->type = LeapFinger::TYPE; LUA->CreateMetaTableType( "LeapFinger" , LeapFinger::TYPE ); LUA->SetMetaTable( -2 ); } int LeapFinger::tostring( lua_State *state) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushString( finger->toString().c_str() ); return 1; } int LeapFinger::Bone( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LeapBone::Push( state, new Leap::Bone( finger->bone( ( Bone::Type ) ( ( int ) LUA->CheckNumber() ) ) ) ); return 1; } int LeapFinger::Direction( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; PushSourceVector( state, new Vector( finger->direction() ) ); return 1; } int LeapFinger::Frame( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LeapFrame::Push( state, new Leap::Frame( finger->frame() ) ); return 1; } int LeapFinger::Hand( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LeapHand::Push( state, new Leap::Hand( finger->hand() ) ); return 1; } int LeapFinger::ID( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber( finger->id() ); return 1; } int LeapFinger::IsExtended( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushBool( finger->isExtended() ); return 1; } int LeapFinger::IsFinger( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushBool( finger->isFinger() ); return 1; } int LeapFinger::IsTool( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushBool( finger->isTool() ); return 1; } int LeapFinger::IsValid( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushBool( finger->isValid() ); return 1; } int LeapFinger::Length( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber( finger->length() ); return 1; } int LeapFinger::StabilizedTipPosition( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; PushSourceVector( state, new Vector( finger->stabilizedTipPosition() ) ); return 1; } int LeapFinger::TimeVisible( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber( finger->timeVisible() ); return 1; } int LeapFinger::TipPosition( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; PushSourceVector( state, new Vector( finger->tipPosition() ) ); return 1; } int LeapFinger::TipVelocity( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; PushSourceVector( state, new Vector( finger->tipVelocity() ) ); return 1; } int LeapFinger::TouchDistance( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber( finger->touchDistance() ); return 1; } int LeapFinger::TouchZone( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; //TODO return 1; } int LeapFinger::Type( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; //TODO return 1; } int LeapFinger::Width( lua_State *state ) { Finger *finger = Get( state ); if ( !finger ) return 0; LUA->PushNumber(finger->width()); return 1; }<|endoftext|>
<commit_before>#include <signal.h> #include <stdio.h> #include <unistd.h> #include <algorithm> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <streambuf> #include <string> #include <tuple> #include <vector> #include "const.hpp" #include "cpu.hpp" #include "cursor.hpp" #include "drawing3D.hpp" #include "drawing3Db.hpp" #include "drawing2D.hpp" #include "output.hpp" #include "printer.hpp" #include "ram.hpp" #include "renderer.hpp" #include "util.hpp" #include "view.hpp" using namespace std; extern "C" { extern volatile sig_atomic_t pleaseExit; void setEnvironment(); void resetEnvironment(); } void startInteractiveMode(); void drawScreen(); void switchBitUnderCursor(); void eraseByteUnderCursor(); char readStdin(bool drawCursor); void sleepAndCheckForKey(); void exec(); void run(); string getFreeFileName(); void saveRamToFile(); void switchDrawing(); void userInput(); void prepareOutput(); bool getBool(char c); void writeInstructionBitToRam(int address, int bitIndex, bool bitValue); void writeDataBitToRam(int address, int bitIndex, bool bitValue); void writeLineToRam(string line, int address); void loadRamFromFileStream(ifstream* fileStream); void checkIfInputIsPiped(); void loadRamIfFileSpecified(int argc, const char* argv[]); ////////////////////////// ////////// VARS ////////// ////////////////////////// // Two global variables. bool interactivieMode; bool executionCanceled = false; // Main components. Printer printer; Ram ram = Ram(printer); Cpu cpu = Cpu(&ram); // Graphic representation of the computer's state. vector<vector<string>> buffer; // Cycle counter. int executionCounter = 0; // Saved state of a ram. Loaded after execution ends. map<AddrSpace, vector<vector<bool>>> savedRamState; // Object for keeping track of, and moving around cursor. Cursor cursor = Cursor(ram); // Two views. View VIEW_3D = View(drawing3D, LIGHTBULB_ON_3D, LIGHTBULB_OFF_3D); View VIEW_3D_B = View(drawing3Db, LIGHTBULB_ON_3D_B, LIGHTBULB_OFF_3D_B); View VIEW_2D = View(drawing2D, LIGHTBULB_ON_2D, LIGHTBULB_OFF_2D); View *selectedView = &VIEW_3D; // Whether next key should be read as a char whose value shall thence be // inserted into ram. bool insertChar = false; ////////////////////////// ////////// MAIN ////////// ////////////////////////// int main(int argc, const char* argv[]) { srand(time(NULL)); checkIfInputIsPiped(); loadRamIfFileSpecified(argc, argv); if (interactivieMode) { startInteractiveMode(); } else { exec(); } } void startInteractiveMode() { setEnvironment(); prepareOutput(); clearScreen(); redrawScreen(); userInput(); } ////////////////////////// /////// FUNCTIONS //////// ////////////////////////// void drawScreen() { buffer = Renderer::renderState(printer, ram, cpu, cursor, *selectedView); int i = 0; for (vector<string> line : buffer) { replaceLine(line, i++); } } void switchBitUnderCursor() { bool bitValue = cursor.getBit(); cursor.setBit(!bitValue); } void eraseByteUnderCursor() { cursor.setWord(Util::getBoolByte(0)); } char readStdin(bool drawCursor) { char c = 0; errno = 0; ssize_t num = read(0, &c, 1); if (num == -1 && errno == EINTR) { // Exits if ctrl-c was pressed. if (pleaseExit) { exit(0); } redrawScreen(); return readStdin(drawCursor); } return c; } /* * Runs every cycle. */ void sleepAndCheckForKey() { usleep(FQ*1000); // Exits if ctrl-c was pressed. if (pleaseExit) { exit(0); } // Pauses execution if a key was hit, and waits for another key hit. if (int keyCode = Util::getKey()) { // If escape was pressed. if (keyCode == 27) { executionCanceled = true; return; } // "Press key to continue." keyCode = readStdin(false); // If esc key was pressed. if (keyCode == 27) { executionCanceled = true; } } } void exec() { while(!executionCanceled) { bool shouldContinue = cpu.step(); if (interactivieMode) { redrawScreen(); } if (!shouldContinue) { return; } if (interactivieMode) { sleepAndCheckForKey(); } } } /* * Saves the state of the ram and starts the execution of a program. * When execution stops, due to it reaching last address or user pressing * 'esc', it loads back the saved state of the ram, and resets the cpu. */ void run() { if (executionCounter > 0) { printer.printEmptyLine(); } savedRamState = ram.state; exec(); // If 'esc' was pressed then it doesn't wait for keypress at the end. if (executionCanceled) { executionCanceled = false; } else { readStdin(false); } ram.state = savedRamState; cpu = Cpu(&ram); redrawScreen(); executionCounter++; } string getFreeFileName() { int i = 0; while (Util::fileExists(SAVE_FILE_NAME + to_string(++i))); return SAVE_FILE_NAME + to_string(i); } void saveRamToFile() { string fileName = getFreeFileName(); ofstream fileStream(fileName); fileStream << ram.getString(); fileStream.close(); } void switchDrawing() { if (*selectedView == VIEW_3D) { selectedView = &VIEW_3D_B; } else if (*selectedView == VIEW_3D_B) { selectedView = &VIEW_2D; } else { selectedView = &VIEW_3D; } prepareOutput(); clearScreen(); redrawScreen(); userInput(); } void userInput() { while(1) { char c = readStdin(true); if (insertChar) { insertChar = false; if (c == 27) { // Esc continue; } cursor.setWord(Util::getBoolByte(c)); cursor.increaseY(); } else { switch (c) { // UP case 107: // k case 65: // A, part of escape seqence of up arrow cursor.decreaseY(); break; // DOWN case 106: // j case 66: // B, part of escape seqence of down arrow cursor.increaseY(); break; // RIGHT case 108: // l case 67: // C, part of escape seqence of rigth arrow cursor.increaseX(); break; // LEFT case 104: // h case 68: // D, part of escape seqence of left arrow cursor.decreaseX(); break; // SWAP UP case 75: // K case 53: // 5, part of escape seqence of page up cursor.moveByteUp(); break; // SWAP DOWN case 74: // J case 54: // 6, part of escape seqence of page down cursor.moveByteDown(); break; // SAVE case 119: // w case 115: // s saveRamToFile(); break; // FLIP case 32: // space switchBitUnderCursor(); break; // DELETE case 51: // 3, part of escape seqence of delete key eraseByteUnderCursor(); break; // SWITCH ADR SPACE case 116: // t case 9: // tab cursor.switchAddressSpace(); break; // RUN case 10: // enter run(); break; case 122: // z switchDrawing(); break; case 105: { // i if (cursor.getAddressSpace() == DATA) { insertChar = true; } break; } case 102: // f cursor.setBit(true); cursor.increaseX(); break; case 100: // d cursor.setBit(false); cursor.increaseX(); break; case 111: // o cursor.increaseY(); cursor.setBitIndex(0); } } redrawScreen(); } } /* * Initializes 'output.cpp' by sending dimensions of a 'drawing' and * a 'drawScreen' callback function, that output.c will use on every * screen redraw. */ void prepareOutput() { setOutput(&drawScreen, selectedView->width, selectedView->height); } bool getBool(char c) { return c == '*'; } void writeInstructionBitToRam(int address, int bitIndex, bool bitValue) { ram.state[CODE].at(address).at(bitIndex) = bitValue; } void writeDataBitToRam(int address, int bitIndex, bool bitValue) { ram.state[DATA].at(address).at(bitIndex) = bitValue; } void writeLineToRam(string line, int address) { int bitIndex = 0; for (char c : line) { if (address < RAM_SIZE) { writeInstructionBitToRam(address, bitIndex, getBool(c)); } else { writeDataBitToRam(address-RAM_SIZE, bitIndex, getBool(c)); } if (++bitIndex >= WORD_SIZE) { return; } } } void loadRamFromFileStream(ifstream* fileStream) { int address = 0; while (!fileStream->eof()) { string line; getline(*fileStream, line); bool lineEmptyOrAComment = line.empty() || line[0] == '#'; if (lineEmptyOrAComment) { continue; } writeLineToRam(line, address); if (++address >= 2*RAM_SIZE) { return; } } } void checkIfInputIsPiped() { interactivieMode = !Util::inputIsPiped(); } void loadRamIfFileSpecified(int argc, const char* argv[]) { if (argc <= 1) { return; } ifstream fileStream; fileStream.open(argv[1]); if (fileStream.fail()) { fprintf(stderr, "Invalid filename '%s'. Aborting ram load.", argv[1]); } else { loadRamFromFileStream(&fileStream); fileStream.close(); } } <commit_msg>Automaticaly selects view<commit_after>#include <signal.h> #include <stdio.h> #include <unistd.h> #include <algorithm> #include <cmath> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <streambuf> #include <string> #include <tuple> #include <vector> #include "const.hpp" #include "cpu.hpp" #include "cursor.hpp" #include "drawing3D.hpp" #include "drawing3Db.hpp" #include "drawing2D.hpp" #include "output.hpp" #include "printer.hpp" #include "ram.hpp" #include "renderer.hpp" #include "util.hpp" #include "view.hpp" using namespace std; extern "C" { extern volatile sig_atomic_t pleaseExit; void setEnvironment(); void resetEnvironment(); } void startInteractiveMode(); void drawScreen(); void switchBitUnderCursor(); void eraseByteUnderCursor(); char readStdin(bool drawCursor); void sleepAndCheckForKey(); void exec(); void run(); string getFreeFileName(); void saveRamToFile(); void switchDrawing(); void userInput(); void prepareOutput(); bool getBool(char c); void writeInstructionBitToRam(int address, int bitIndex, bool bitValue); void writeDataBitToRam(int address, int bitIndex, bool bitValue); void writeLineToRam(string line, int address); void loadRamFromFileStream(ifstream* fileStream); void checkIfInputIsPiped(); void loadRamIfFileSpecified(int argc, const char* argv[]); void selectView(); ////////////////////////// ////////// VARS ////////// ////////////////////////// // Two global variables. bool interactivieMode; bool executionCanceled = false; // Main components. Printer printer; Ram ram = Ram(printer); Cpu cpu = Cpu(&ram); // Graphic representation of the computer's state. vector<vector<string>> buffer; // Cycle counter. int executionCounter = 0; // Saved state of a ram. Loaded after execution ends. map<AddrSpace, vector<vector<bool>>> savedRamState; // Object for keeping track of, and moving around cursor. Cursor cursor = Cursor(ram); // Two views. View VIEW_3D = View(drawing3D, LIGHTBULB_ON_3D, LIGHTBULB_OFF_3D); View VIEW_3D_B = View(drawing3Db, LIGHTBULB_ON_3D_B, LIGHTBULB_OFF_3D_B); View VIEW_2D = View(drawing2D, LIGHTBULB_ON_2D, LIGHTBULB_OFF_2D); View *selectedView = &VIEW_3D; // Whether next key should be read as a char whose value shall thence be // inserted into ram. bool insertChar = false; ////////////////////////// ////////// MAIN ////////// ////////////////////////// int main(int argc, const char* argv[]) { srand(time(NULL)); checkIfInputIsPiped(); loadRamIfFileSpecified(argc, argv); if (interactivieMode) { startInteractiveMode(); } else { exec(); } } void startInteractiveMode() { selectView(); setEnvironment(); prepareOutput(); clearScreen(); redrawScreen(); userInput(); } ////////////////////////// /////// FUNCTIONS //////// ////////////////////////// void selectView() { const char* term = std::getenv("TERM"); if (strcmp(term, "linux") == 0) { selectedView = &VIEW_3D_B; } else if (strcmp(term, "rxvt") == 0) { selectedView = &VIEW_2D; } // if(const char* env_p = std::getenv("PATH")) // std::cout << "Your PATH is: " << env_p << '\n'; } void drawScreen() { buffer = Renderer::renderState(printer, ram, cpu, cursor, *selectedView); int i = 0; for (vector<string> line : buffer) { replaceLine(line, i++); } } void switchBitUnderCursor() { bool bitValue = cursor.getBit(); cursor.setBit(!bitValue); } void eraseByteUnderCursor() { cursor.setWord(Util::getBoolByte(0)); } char readStdin(bool drawCursor) { char c = 0; errno = 0; ssize_t num = read(0, &c, 1); if (num == -1 && errno == EINTR) { // Exits if ctrl-c was pressed. if (pleaseExit) { exit(0); } redrawScreen(); return readStdin(drawCursor); } return c; } /* * Runs every cycle. */ void sleepAndCheckForKey() { usleep(FQ*1000); // Exits if ctrl-c was pressed. if (pleaseExit) { exit(0); } // Pauses execution if a key was hit, and waits for another key hit. if (int keyCode = Util::getKey()) { // If escape was pressed. if (keyCode == 27) { executionCanceled = true; return; } // "Press key to continue." keyCode = readStdin(false); // If esc key was pressed. if (keyCode == 27) { executionCanceled = true; } } } void exec() { while(!executionCanceled) { bool shouldContinue = cpu.step(); if (interactivieMode) { redrawScreen(); } if (!shouldContinue) { return; } if (interactivieMode) { sleepAndCheckForKey(); } } } /* * Saves the state of the ram and starts the execution of a program. * When execution stops, due to it reaching last address or user pressing * 'esc', it loads back the saved state of the ram, and resets the cpu. */ void run() { if (executionCounter > 0) { printer.printEmptyLine(); } savedRamState = ram.state; exec(); // If 'esc' was pressed then it doesn't wait for keypress at the end. if (executionCanceled) { executionCanceled = false; } else { readStdin(false); } ram.state = savedRamState; cpu = Cpu(&ram); redrawScreen(); executionCounter++; } string getFreeFileName() { int i = 0; while (Util::fileExists(SAVE_FILE_NAME + to_string(++i))); return SAVE_FILE_NAME + to_string(i); } void saveRamToFile() { string fileName = getFreeFileName(); ofstream fileStream(fileName); fileStream << ram.getString(); fileStream.close(); } void switchDrawing() { if (*selectedView == VIEW_3D) { selectedView = &VIEW_3D_B; } else if (*selectedView == VIEW_3D_B) { selectedView = &VIEW_2D; } else { selectedView = &VIEW_3D; } prepareOutput(); clearScreen(); redrawScreen(); userInput(); } void userInput() { while(1) { char c = readStdin(true); if (insertChar) { insertChar = false; if (c == 27) { // Esc continue; } cursor.setWord(Util::getBoolByte(c)); cursor.increaseY(); } else { switch (c) { // UP case 107: // k case 65: // A, part of escape seqence of up arrow cursor.decreaseY(); break; // DOWN case 106: // j case 66: // B, part of escape seqence of down arrow cursor.increaseY(); break; // RIGHT case 108: // l case 67: // C, part of escape seqence of rigth arrow cursor.increaseX(); break; // LEFT case 104: // h case 68: // D, part of escape seqence of left arrow cursor.decreaseX(); break; // SWAP UP case 75: // K case 53: // 5, part of escape seqence of page up cursor.moveByteUp(); break; // SWAP DOWN case 74: // J case 54: // 6, part of escape seqence of page down cursor.moveByteDown(); break; // SAVE case 119: // w case 115: // s saveRamToFile(); break; // FLIP case 32: // space switchBitUnderCursor(); break; // DELETE case 51: // 3, part of escape seqence of delete key eraseByteUnderCursor(); break; // SWITCH ADR SPACE case 116: // t case 9: // tab cursor.switchAddressSpace(); break; // RUN case 10: // enter run(); break; case 122: // z switchDrawing(); break; case 105: { // i if (cursor.getAddressSpace() == DATA) { insertChar = true; } break; } case 102: // f cursor.setBit(true); cursor.increaseX(); break; case 100: // d cursor.setBit(false); cursor.increaseX(); break; case 111: // o cursor.increaseY(); cursor.setBitIndex(0); } } redrawScreen(); } } /* * Initializes 'output.cpp' by sending dimensions of a 'drawing' and * a 'drawScreen' callback function, that output.c will use on every * screen redraw. */ void prepareOutput() { setOutput(&drawScreen, selectedView->width, selectedView->height); } bool getBool(char c) { return c == '*'; } void writeInstructionBitToRam(int address, int bitIndex, bool bitValue) { ram.state[CODE].at(address).at(bitIndex) = bitValue; } void writeDataBitToRam(int address, int bitIndex, bool bitValue) { ram.state[DATA].at(address).at(bitIndex) = bitValue; } void writeLineToRam(string line, int address) { int bitIndex = 0; for (char c : line) { if (address < RAM_SIZE) { writeInstructionBitToRam(address, bitIndex, getBool(c)); } else { writeDataBitToRam(address-RAM_SIZE, bitIndex, getBool(c)); } if (++bitIndex >= WORD_SIZE) { return; } } } void loadRamFromFileStream(ifstream* fileStream) { int address = 0; while (!fileStream->eof()) { string line; getline(*fileStream, line); bool lineEmptyOrAComment = line.empty() || line[0] == '#'; if (lineEmptyOrAComment) { continue; } writeLineToRam(line, address); if (++address >= 2*RAM_SIZE) { return; } } } void checkIfInputIsPiped() { interactivieMode = !Util::inputIsPiped(); } void loadRamIfFileSpecified(int argc, const char* argv[]) { if (argc <= 1) { return; } ifstream fileStream; fileStream.open(argv[1]); if (fileStream.fail()) { fprintf(stderr, "Invalid filename '%s'. Aborting ram load.", argv[1]); } else { loadRamFromFileStream(&fileStream); fileStream.close(); } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/software/license/ * * 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 "Gaussian2DModel.h" #include <cmath> #include "UniformDistribution.h" namespace madai { Gaussian2DModel ::Gaussian2DModel() : m_MeanX( 23.2 ), m_MeanY( -14.0 ), m_StandardDeviationX( 4.0 ), m_StandardDeviationY( 12.3 ) { UniformDistribution xPrior; xPrior.SetMinimum( m_MeanX - 10.0 * m_StandardDeviationX ); xPrior.SetMaximum( m_MeanX + 10.0 * m_StandardDeviationX ); this->AddParameter( "X", xPrior ); UniformDistribution yPrior; yPrior.SetMinimum( m_MeanY - 10.0 * m_StandardDeviationY ); yPrior.SetMaximum( m_MeanY + 10.0 * m_StandardDeviationY ); this->AddParameter( "Y", yPrior ); this->AddScalarOutputName( "Value" ); } Model::ErrorType Gaussian2DModel ::LoadConfigurationFile( const std::string fileName ) { // Member variables should be set from values ready from a file. return Model::NO_ERROR; } Model::ErrorType Gaussian2DModel ::GetScalarOutputs( const std::vector< double > & parameters, std::vector< double > & scalars ) const { scalars.clear(); // Remove all elements from the output vector. // Compute "Value" output. double x = parameters[0]; double y = parameters[1]; double dx = x - m_MeanX; double dy = y - m_MeanY; double sx = m_StandardDeviationX; double sy = m_StandardDeviationY; // Negate the Gaussian so there is a well-defined global minimum double value = exp( -( ((dx*dx) / (2.0 * sx * sx)) + ((dy*dy) / (2.0 * sy * sy)) ) ); scalars.push_back( value ); return NO_ERROR; } Model::ErrorType Gaussian2DModel ::GetScalarAndGradientOutputs( const std::vector< double > & parameters, const std::vector< bool > & activeParameters, std::vector< double > & scalars, std::vector< double > & gradient) const { scalars.clear(); gradient.clear(); ErrorType error = this->GetScalarOutputs( parameters, scalars ); if ( error != NO_ERROR ) { return error; } if ( activeParameters.size() != this->GetNumberOfParameters() ) { return INVALID_ACTIVE_PARAMETERS; } double functionValue = scalars[0]; unsigned int activeParameter = 0; if ( activeParameters[0] ) { gradient.push_back( -functionValue * this->PartialX( parameters[0], functionValue ) ); } if ( activeParameters[1] ) { gradient.push_back( -functionValue * this->PartialY( parameters[1], functionValue ) ); } return NO_ERROR; } double Gaussian2DModel ::PartialX( double x, double value ) const { double dx = x - m_MeanX; double sx = m_StandardDeviationX; return -(value * dx) / (sx * sx); } double Gaussian2DModel ::PartialY( double y, double value ) const { double dy = y - m_MeanY; double sy = m_StandardDeviationY; return -(value * dy) / (sy * sy); } void Gaussian2DModel ::GetDeviations( double & DevX, double & DevY ) const { DevX = this->m_StandardDeviationX; DevY = this->m_StandardDeviationY; } void Gaussian2DModel ::GetMeans( double & MeanX, double & MeanY ) const { MeanX = this->m_MeanX; MeanY = this->m_MeanY; } } // end namespace madai <commit_msg>Fixed the gradient calculation to account for the observed value<commit_after>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/software/license/ * * 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 "Gaussian2DModel.h" #include <cmath> #include "UniformDistribution.h" namespace madai { Gaussian2DModel ::Gaussian2DModel() : m_MeanX( 23.2 ), m_MeanY( -14.0 ), m_StandardDeviationX( 4.0 ), m_StandardDeviationY( 12.3 ) { UniformDistribution xPrior; xPrior.SetMinimum( m_MeanX - 10.0 * m_StandardDeviationX ); xPrior.SetMaximum( m_MeanX + 10.0 * m_StandardDeviationX ); this->AddParameter( "X", xPrior ); UniformDistribution yPrior; yPrior.SetMinimum( m_MeanY - 10.0 * m_StandardDeviationY ); yPrior.SetMaximum( m_MeanY + 10.0 * m_StandardDeviationY ); this->AddParameter( "Y", yPrior ); this->AddScalarOutputName( "Value" ); // Usually the observed scalar values would be set from outside the // Model object. As this is a test object, however, we are setting // the observed values here. std::vector< double > observedScalars( 1, 1.0 ); this->SetObservedScalarValues( observedScalars ); } Model::ErrorType Gaussian2DModel ::LoadConfigurationFile( const std::string fileName ) { // Member variables should be set from values ready from a file. return Model::NO_ERROR; } Model::ErrorType Gaussian2DModel ::GetScalarOutputs( const std::vector< double > & parameters, std::vector< double > & scalars ) const { scalars.clear(); // Remove all elements from the output vector. // Compute "Value" output. double x = parameters[0]; double y = parameters[1]; double dx = x - m_MeanX; double dy = y - m_MeanY; double sx = m_StandardDeviationX; double sy = m_StandardDeviationY; double value = exp( -( ((dx*dx) / (2.0 * sx * sx)) + ((dy*dy) / (2.0 * sy * sy)) ) ); scalars.push_back( value ); return NO_ERROR; } Model::ErrorType Gaussian2DModel ::GetScalarAndGradientOutputs( const std::vector< double > & parameters, const std::vector< bool > & activeParameters, std::vector< double > & scalars, std::vector< double > & gradient) const { scalars.clear(); gradient.clear(); ErrorType error = this->GetScalarOutputs( parameters, scalars ); if ( error != NO_ERROR ) { return error; } if ( activeParameters.size() != this->GetNumberOfParameters() ) { return INVALID_ACTIVE_PARAMETERS; } double functionValue = scalars[0]; unsigned int activeParameter = 0; if ( activeParameters[0] ) { gradient.push_back( -(functionValue - m_ObservedScalarValues[0]) * this->PartialX( parameters[0], functionValue ) ); } if ( activeParameters[1] ) { gradient.push_back( -(functionValue - m_ObservedScalarValues[0]) * this->PartialY( parameters[1], functionValue ) ); } return NO_ERROR; } double Gaussian2DModel ::PartialX( double x, double value ) const { double dx = x - m_MeanX; double sx = m_StandardDeviationX; return -(value * dx) / (sx * sx); } double Gaussian2DModel ::PartialY( double y, double value ) const { double dy = y - m_MeanY; double sy = m_StandardDeviationY; return -(value * dy) / (sy * sy); } void Gaussian2DModel ::GetDeviations( double & DevX, double & DevY ) const { DevX = this->m_StandardDeviationX; DevY = this->m_StandardDeviationY; } void Gaussian2DModel ::GetMeans( double & MeanX, double & MeanY ) const { MeanX = this->m_MeanX; MeanY = this->m_MeanY; } } // end namespace madai <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2015 Mark Charlebois. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file hello_start_linux.cpp * * @author Thomas Gubler <thomasgubler@gmail.com> * @author Mark Charlebois <mcharleb@gmail.com> */ #include "hello_example.h" #include <px4_app.h> #include <px4_tasks.h> #include <stdio.h> #include <string.h> #include <sched.h> #define SCHED_DEFAULT SCHED_FIFO #define SCHED_PRIORITY_MAX sched_get_priority_max(SCHED_FIFO) #define SCHED_PRIORITY_DEFAULT sched_get_priority_max(SCHED_FIFO) static int daemon_task; /* Handle of deamon task / thread */ //using namespace px4; extern "C" __EXPORT int hello_main(int argc, char *argv[]); int hello_main(int argc, char *argv[]) { if (argc < 2) { printf("usage: hello {start|stop|status}\n"); return 1; } if (!strcmp(argv[1], "start")) { if (HelloExample::mgr.isRunning()) { printf("already running\n"); /* this is not an error */ return 0; } daemon_task = px4_task_spawn_cmd("hello", SCHED_DEFAULT, SCHED_PRIORITY_MAX - 5, 2000, PX4_MAIN, (argv) ? (char* const*)&argv[2] : (char* const*)NULL); return 0; } if (!strcmp(argv[1], "stop")) { HelloExample::mgr.requestExit(); return 0; } if (!strcmp(argv[1], "status")) { if (HelloExample::mgr.isRunning()) { printf("is running\n"); } else { printf("not started\n"); } return 0; } printf("usage: hello {start|stop|status}\n"); return 1; } <commit_msg>Fixed usage string for hello app<commit_after>/**************************************************************************** * * Copyright (C) 2015 Mark Charlebois. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file hello_start_linux.cpp * * @author Thomas Gubler <thomasgubler@gmail.com> * @author Mark Charlebois <mcharleb@gmail.com> */ #include "hello_example.h" #include <px4_app.h> #include <px4_tasks.h> #include <stdio.h> #include <string.h> #include <sched.h> #define SCHED_DEFAULT SCHED_FIFO #define SCHED_PRIORITY_MAX sched_get_priority_max(SCHED_FIFO) #define SCHED_PRIORITY_DEFAULT sched_get_priority_max(SCHED_FIFO) static int daemon_task; /* Handle of deamon task / thread */ //using namespace px4; extern "C" __EXPORT int hello_main(int argc, char *argv[]); int hello_main(int argc, char *argv[]) { if (argc < 2) { printf("usage: hello {start|stop|status}\n"); return 1; } if (!strcmp(argv[1], "start")) { if (HelloExample::mgr.isRunning()) { printf("already running\n"); /* this is not an error */ return 0; } daemon_task = px4_task_spawn_cmd("hello", SCHED_DEFAULT, SCHED_PRIORITY_MAX - 5, 2000, PX4_MAIN, (argv) ? (char* const*)&argv[2] : (char* const*)NULL); return 0; } if (!strcmp(argv[1], "stop")) { HelloExample::mgr.requestExit(); return 0; } if (!strcmp(argv[1], "status")) { if (HelloExample::mgr.isRunning()) { printf("is running\n"); } else { printf("not started\n"); } return 0; } printf("usage: hello_main {start|stop|status}\n"); return 1; } <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "print_number_process.h" #include <vistk/pipeline_types/port_types.h> #include <vistk/pipeline/datum.h> #include <vistk/pipeline/process_exception.h> #include <boost/filesystem/path.hpp> #include <iostream> #include <fstream> namespace vistk { class print_number_process::priv { public: typedef uint32_t number_t; typedef boost::filesystem::path path_t; priv(path_t const& output_path); ~priv(); path_t const path; edge_t input_edge; std::ofstream fout; static config::key_t const CONFIG_OUTPUT_NAME; static port_t const INPUT_PORT_NAME; }; config::key_t const print_number_process::priv::CONFIG_OUTPUT_NAME = config::key_t("output"); process::port_t const print_number_process::priv::INPUT_PORT_NAME = process::port_t("number"); print_number_process ::print_number_process(config_t const& config) : process(config) { priv::path_t path = config->get_value<priv::path_t>(priv::CONFIG_OUTPUT_NAME, priv::path_t()); d = boost::shared_ptr<priv>(new priv(path)); } print_number_process ::~print_number_process() { } process_registry::type_t print_number_process ::type() const { return process_registry::type_t("print_number_process"); } void print_number_process ::_init() { d->fout.open(d->path.native().c_str()); if (!d->fout.good()) { /// \todo Throw exception. } } void print_number_process ::_step() { edge_datum_t const input_dat = d->input_edge->get_datum(); switch (input_dat.get<0>()->type()) { case datum::DATUM_DATA: { priv::number_t const input = input_dat.get<0>()->get_datum<priv::number_t>(); d->fout << input << std::endl; break; } case datum::DATUM_EMPTY: break; case datum::DATUM_COMPLETE: mark_as_complete(); break; case datum::DATUM_ERROR: break; case datum::DATUM_INVALID: default: break; } process::_step(); } void print_number_process ::_connect_input_port(port_t const& port, edge_t edge) { if (port == priv::INPUT_PORT_NAME) { if (d->input_edge) { throw port_reconnect_exception(name(), port); } d->input_edge = edge; return; } process::_connect_input_port(port, edge); } process::port_type_t print_number_process ::_input_port_type(port_t const& port) const { if (port == priv::INPUT_PORT_NAME) { port_flags_t flags; flags.insert(flag_required); return port_type_t(port_types::t_integer, flags); } return process::_input_port_type(port); } process::port_description_t print_number_process ::_input_port_description(port_t const& port) const { if (port == priv::INPUT_PORT_NAME) { return port_description_t("Where numbers are read from."); } return process::_input_port_description(port); } process::ports_t print_number_process ::_input_ports() const { ports_t ports; ports.push_back(priv::INPUT_PORT_NAME); return ports; } config::keys_t print_number_process ::_available_config() const { config::keys_t keys = process::_available_config(); keys.push_back(priv::CONFIG_OUTPUT_NAME); return keys; } config::value_t print_number_process ::_config_default(config::key_t const& key) const { if (key == priv::CONFIG_OUTPUT_NAME) { return config::value_t(); } return process::_config_default(key); } config::description_t print_number_process ::_config_description(config::key_t const& key) const { if (key == priv::CONFIG_OUTPUT_NAME) { return config::description_t("The path the file to output to"); } return process::_config_description(key); } print_number_process::priv ::priv(path_t const& output_path) : path(output_path) { } print_number_process::priv ::~priv() { } } <commit_msg>Check configuration of the print_number process<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "print_number_process.h" #include <vistk/pipeline_types/port_types.h> #include <vistk/pipeline/datum.h> #include <vistk/pipeline/process_exception.h> #include <boost/filesystem/path.hpp> #include <iostream> #include <fstream> namespace vistk { class print_number_process::priv { public: typedef uint32_t number_t; typedef boost::filesystem::path path_t; priv(path_t const& output_path); ~priv(); path_t const path; edge_t input_edge; std::ofstream fout; static config::key_t const CONFIG_OUTPUT_NAME; static port_t const INPUT_PORT_NAME; }; config::key_t const print_number_process::priv::CONFIG_OUTPUT_NAME = config::key_t("output"); process::port_t const print_number_process::priv::INPUT_PORT_NAME = process::port_t("number"); print_number_process ::print_number_process(config_t const& config) : process(config) { priv::path_t path = config->get_value<priv::path_t>(priv::CONFIG_OUTPUT_NAME, priv::path_t()); d = boost::shared_ptr<priv>(new priv(path)); } print_number_process ::~print_number_process() { } process_registry::type_t print_number_process ::type() const { return process_registry::type_t("print_number_process"); } void print_number_process ::_init() { boost::filesystem::path::string_type const path = d->path.native(); if (path.empty()) { config::value_t const value = config::value_t(path.begin(), path.end()); throw invalid_configuration_value_exception(name(), priv::CONFIG_OUTPUT_NAME, value, "The path given was empty"); } d->fout.open(path.c_str()); if (!d->fout.good()) { throw invalid_configuration_exception(name(), "Failed to open the path: " + path); } } void print_number_process ::_step() { edge_datum_t const input_dat = d->input_edge->get_datum(); switch (input_dat.get<0>()->type()) { case datum::DATUM_DATA: { priv::number_t const input = input_dat.get<0>()->get_datum<priv::number_t>(); d->fout << input << std::endl; break; } case datum::DATUM_EMPTY: break; case datum::DATUM_COMPLETE: mark_as_complete(); break; case datum::DATUM_ERROR: break; case datum::DATUM_INVALID: default: break; } process::_step(); } void print_number_process ::_connect_input_port(port_t const& port, edge_t edge) { if (port == priv::INPUT_PORT_NAME) { if (d->input_edge) { throw port_reconnect_exception(name(), port); } d->input_edge = edge; return; } process::_connect_input_port(port, edge); } process::port_type_t print_number_process ::_input_port_type(port_t const& port) const { if (port == priv::INPUT_PORT_NAME) { port_flags_t flags; flags.insert(flag_required); return port_type_t(port_types::t_integer, flags); } return process::_input_port_type(port); } process::port_description_t print_number_process ::_input_port_description(port_t const& port) const { if (port == priv::INPUT_PORT_NAME) { return port_description_t("Where numbers are read from."); } return process::_input_port_description(port); } process::ports_t print_number_process ::_input_ports() const { ports_t ports; ports.push_back(priv::INPUT_PORT_NAME); return ports; } config::keys_t print_number_process ::_available_config() const { config::keys_t keys = process::_available_config(); keys.push_back(priv::CONFIG_OUTPUT_NAME); return keys; } config::value_t print_number_process ::_config_default(config::key_t const& key) const { if (key == priv::CONFIG_OUTPUT_NAME) { return config::value_t(); } return process::_config_default(key); } config::description_t print_number_process ::_config_description(config::key_t const& key) const { if (key == priv::CONFIG_OUTPUT_NAME) { return config::description_t("The path the file to output to"); } return process::_config_description(key); } print_number_process::priv ::priv(path_t const& output_path) : path(output_path) { } print_number_process::priv ::~priv() { } } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * Raphael Hiesgen <raphael.hiesgen (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_IO_NETWORK_ASIO_MULTIPLEXER_HPP #define CAF_IO_NETWORK_ASIO_MULTIPLEXER_HPP #include "caf/config.hpp" CAF_PUSH_WARNINGS #include "boost/asio.hpp" CAF_POP_WARNINGS #include "caf/logger.hpp" #include "caf/io/receive_policy.hpp" #include "caf/io/network/multiplexer.hpp" #include "caf/io/network/native_socket.hpp" #include "caf/io/network/stream_manager.hpp" #include "caf/io/network/acceptor_manager.hpp" namespace caf { namespace io { namespace network { /// Low-level error code. using error_code = boost::system::error_code; /// Low-level backend for IO multiplexing. using io_service = boost::asio::io_service; /// Low-level socket type used as default. using asio_tcp_socket = boost::asio::ip::tcp::socket; /// Low-level socket type used as default. using asio_tcp_socket_acceptor = boost::asio::ip::tcp::acceptor; /// A wrapper for the boost::asio multiplexer class asio_multiplexer : public multiplexer { public: friend class io::middleman; friend class supervisor; expected<connection_handle> new_tcp_scribe(const std::string&, uint16_t) override; expected<void> assign_tcp_scribe(abstract_broker*, connection_handle hdl) override; template <class Socket> connection_handle add_tcp_scribe(abstract_broker*, Socket&& sock); connection_handle add_tcp_scribe(abstract_broker*, native_socket fd) override; expected<connection_handle> add_tcp_scribe(abstract_broker*, const std::string&, uint16_t) override; expected<std::pair<accept_handle, uint16_t>> new_tcp_doorman(uint16_t p, const char* in, bool rflag) override; expected<void> assign_tcp_doorman(abstract_broker*, accept_handle hdl) override; accept_handle add_tcp_doorman(abstract_broker*, asio_tcp_socket_acceptor&& sock); accept_handle add_tcp_doorman(abstract_broker*, native_socket fd) override; expected<std::pair<accept_handle, uint16_t>> add_tcp_doorman(abstract_broker*, uint16_t, const char*, bool) override; void exec_later(resumable* ptr) override; asio_multiplexer(actor_system* sys); ~asio_multiplexer(); supervisor_ptr make_supervisor() override; void run() override; boost::asio::io_service* pimpl() override; inline boost::asio::io_service& service() { return service_; } private: io_service service_; std::mutex mtx_sockets_; std::mutex mtx_acceptors_; std::map<int64_t, asio_tcp_socket> unassigned_sockets_; std::map<int64_t, asio_tcp_socket_acceptor> unassigned_acceptors_; }; template <class T> connection_handle conn_hdl_from_socket(T& sock) { return connection_handle::from_int( int64_from_native_socket(sock.native_handle())); } template <class T> accept_handle accept_hdl_from_socket(T& sock) { return accept_handle::from_int( int64_from_native_socket(sock.native_handle())); } /// @relates manager using manager_ptr = intrusive_ptr<manager>; /// A stream capable of both reading and writing. The stream's input /// data is forwarded to its {@link stream_manager manager}. template <class Socket> class asio_stream { public: /// A smart pointer to a stream manager. using manager_ptr = intrusive_ptr<stream_manager>; /// A buffer class providing a compatible interface to `std::vector`. using buffer_type = std::vector<char>; asio_stream(asio_multiplexer& ref) : reading_(false), writing_(false), ack_writes_(false), fd_(ref.service()), backend_(ref), rd_buf_ready_(false) { configure_read(receive_policy::at_most(1024)); } /// Returns the IO socket. Socket& socket_handle() { return fd_; } /// Returns the IO socket. const Socket& socket_handle() const { return fd_; } /// Initializes this stream, setting the socket handle to `fd`. void init(Socket fd) { fd_ = std::move(fd); } /// Starts reading data from the socket, forwarding incoming data to `mgr`. void start(stream_manager* mgr) { CAF_ASSERT(mgr != nullptr); activate(mgr); } /// Configures how much data will be provided for the next `consume` callback. /// @warning Must not be called outside the IO multiplexers event loop /// once the stream has been started. void configure_read(receive_policy::config config) { rd_flag_ = config.first; rd_size_ = config.second; } void ack_writes(bool enable) { CAF_LOG_TRACE(CAF_ARG(enable)); ack_writes_ = enable; } /// Copies data to the write buffer. /// @note Not thread safe. void write(const void* buf, size_t num_bytes) { CAF_LOG_TRACE(CAF_ARG(num_bytes)); auto first = reinterpret_cast<const char*>(buf); auto last = first + num_bytes; wr_offline_buf_.insert(wr_offline_buf_.end(), first, last); } /// Returns the write buffer of this stream. /// @warning Must not be modified outside the IO multiplexers event loop /// once the stream has been started. buffer_type& wr_buf() { return wr_offline_buf_; } buffer_type& rd_buf() { return rd_buf_; } /// Sends the content of the write buffer, calling the `io_failure` /// member function of `mgr` in case of an error. /// @warning Must not be called outside the IO multiplexers event loop /// once the stream has been started. void flush(const manager_ptr& mgr) { CAF_ASSERT(mgr != nullptr); if (!wr_offline_buf_.empty() && !writing_) { writing_ = true; write_loop(mgr); } } /// Closes the network connection, thus stopping this stream. void stop() { CAF_LOG_TRACE(""); fd_.close(); } void stop_reading() { CAF_LOG_TRACE(""); error_code ec; // ignored fd_.shutdown(boost::asio::ip::tcp::socket::shutdown_receive, ec); } asio_multiplexer& backend() { return backend_; } /// Activates the stream. void activate(stream_manager* mgr) { read_loop(mgr); } /// Stops activity of the stream. void passivate() { reading_ = false; } private: bool read_one(stream_manager* ptr, size_t num_bytes) { if (!reading_) { // broker was passivated while async read was on its way rd_buf_ready_ = true; // make sure buf size matches read_bytes in case of async_read if (rd_buf_.size() != num_bytes) rd_buf_.resize(num_bytes); return false; } if (ptr->consume(&backend(), rd_buf_.data(), num_bytes)) return reading_; return false; } void read_loop(manager_ptr mgr) { reading_ = true; if (rd_buf_ready_) { rd_buf_ready_ = false; if (read_one(mgr.get(), rd_buf_.size())) read_loop(std::move(mgr)); return; } auto cb = [=](const error_code& ec, size_t read_bytes) mutable { CAF_LOG_TRACE(""); if (!ec) { // bail out early in case broker passivated stream in the meantime if (read_one(mgr.get(), read_bytes)) read_loop(std::move(mgr)); } else { mgr->io_failure(&backend(), operation::read); } }; switch (rd_flag_) { case receive_policy_flag::exactly: if (rd_buf_.size() < rd_size_) { rd_buf_.resize(rd_size_); } boost::asio::async_read(fd_, boost::asio::buffer(rd_buf_, rd_size_), cb); break; case receive_policy_flag::at_most: if (rd_buf_.size() < rd_size_) rd_buf_.resize(rd_size_); fd_.async_read_some(boost::asio::buffer(rd_buf_, rd_size_), cb); break; case receive_policy_flag::at_least: { // read up to 10% more, but at least allow 100 bytes more auto min_size = rd_size_ + std::max<size_t>(100, rd_size_ / 10); if (rd_buf_.size() < min_size) { rd_buf_.resize(min_size); } collect_data(mgr, 0); break; } } } void write_loop(const manager_ptr& mgr) { if (wr_offline_buf_.empty()) { writing_ = false; return; } wr_buf_.clear(); wr_buf_.swap(wr_offline_buf_); boost::asio::async_write( fd_, boost::asio::buffer(wr_buf_), [=](const error_code& ec, size_t nb) { CAF_LOG_TRACE(""); if (ec) { CAF_LOG_DEBUG(CAF_ARG(ec.message())); mgr->io_failure(&backend(), operation::read); writing_ = false; return; } CAF_LOG_DEBUG(CAF_ARG(nb)); if (ack_writes_) mgr->data_transferred(&backend(), nb, wr_offline_buf_.size()); write_loop(mgr); }); } void collect_data(manager_ptr mgr, size_t collected_bytes) { fd_.async_read_some(boost::asio::buffer(rd_buf_.data() + collected_bytes, rd_buf_.size() - collected_bytes), [=](const error_code& ec, size_t nb) mutable { CAF_LOG_TRACE(CAF_ARG(nb)); if (!ec) { auto sum = collected_bytes + nb; if (sum >= rd_size_) { if (read_one(mgr.get(), sum)) read_loop(std::move(mgr)); } else { collect_data(std::move(mgr), sum); } } else { mgr->io_failure(&backend(), operation::write); } }); } bool reading_; bool writing_; bool ack_writes_; Socket fd_; receive_policy_flag rd_flag_; size_t rd_size_; buffer_type rd_buf_; buffer_type wr_buf_; buffer_type wr_offline_buf_; asio_multiplexer& backend_; bool rd_buf_ready_; }; /// An acceptor is responsible for accepting incoming connections. template <class SocketAcceptor> class asio_acceptor { using protocol_type = typename SocketAcceptor::protocol_type; using socket_type = boost::asio::basic_stream_socket<protocol_type>; public: /// A manager providing the `accept` member function. using manager_type = acceptor_manager; /// A smart pointer to an acceptor manager. using manager_ptr = intrusive_ptr<manager_type>; asio_acceptor(asio_multiplexer& am, io_service& io) : accepting_(false), backend_(am), accept_fd_(io), fd_valid_(false), fd_(io) { // nop } /// Returns the `multiplexer` this acceptor belongs to. asio_multiplexer& backend() { return backend_; } /// Returns the IO socket. SocketAcceptor& socket_handle() { return accept_fd_; } /// Returns the IO socket. const SocketAcceptor& socket_handle() const { return accept_fd_; } /// Returns the accepted socket. This member function should /// be called only from the `new_connection` callback. inline socket_type& accepted_socket() { return fd_; } /// Initializes this acceptor, setting the socket handle to `fd`. void init(SocketAcceptor fd) { accept_fd_ = std::move(fd); } /// Starts this acceptor, forwarding all incoming connections to /// `manager`. The intrusive pointer will be released after the /// acceptor has been closed or an IO error occured. void start(manager_type* mgr) { activate(mgr); } /// Starts the accept loop. void activate(manager_type* mgr) { accept_loop(mgr); } /// Starts the accept loop. void passivate() { accepting_ = false; } /// Closes the network connection, thus stopping this acceptor. void stop() { accept_fd_.close(); } private: bool accept_one(manager_type* mgr) { auto res = mgr->new_connection(); // moves fd_ // reset fd_ for next accept operation fd_ = socket_type{accept_fd_.get_io_service()}; return res && accepting_; } void accept_loop(manager_ptr mgr) { accepting_ = true; // accept "cached" connection first if (fd_valid_) { fd_valid_ = false; if (accept_one(mgr.get())) accept_loop(std::move(mgr)); return; } accept_fd_.async_accept(fd_, [=](const error_code& ec) mutable { CAF_LOG_TRACE(""); if (!ec) { // if broker has passivated this in the meantime, cache fd_ for later if (!accepting_) { fd_valid_ = true; return; } if (accept_one(mgr.get())) accept_loop(std::move(mgr)); } else { mgr->io_failure(&backend(), operation::read); } }); } bool accepting_; asio_multiplexer& backend_; SocketAcceptor accept_fd_; bool fd_valid_; socket_type fd_; }; } // namesapce network } // namespace io } // namespace caf #endif // CAF_IO_NETWORK_ASIO_MULTIPLEXER_HPP <commit_msg>Ensure only one ASIO async operation is pending<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * Raphael Hiesgen <raphael.hiesgen (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_IO_NETWORK_ASIO_MULTIPLEXER_HPP #define CAF_IO_NETWORK_ASIO_MULTIPLEXER_HPP #include "caf/config.hpp" CAF_PUSH_WARNINGS #include "boost/asio.hpp" CAF_POP_WARNINGS #include "caf/logger.hpp" #include "caf/io/receive_policy.hpp" #include "caf/io/network/multiplexer.hpp" #include "caf/io/network/native_socket.hpp" #include "caf/io/network/stream_manager.hpp" #include "caf/io/network/acceptor_manager.hpp" namespace caf { namespace io { namespace network { /// Low-level error code. using error_code = boost::system::error_code; /// Low-level backend for IO multiplexing. using io_service = boost::asio::io_service; /// Low-level socket type used as default. using asio_tcp_socket = boost::asio::ip::tcp::socket; /// Low-level socket type used as default. using asio_tcp_socket_acceptor = boost::asio::ip::tcp::acceptor; /// A wrapper for the boost::asio multiplexer class asio_multiplexer : public multiplexer { public: friend class io::middleman; friend class supervisor; expected<connection_handle> new_tcp_scribe(const std::string&, uint16_t) override; expected<void> assign_tcp_scribe(abstract_broker*, connection_handle hdl) override; template <class Socket> connection_handle add_tcp_scribe(abstract_broker*, Socket&& sock); connection_handle add_tcp_scribe(abstract_broker*, native_socket fd) override; expected<connection_handle> add_tcp_scribe(abstract_broker*, const std::string&, uint16_t) override; expected<std::pair<accept_handle, uint16_t>> new_tcp_doorman(uint16_t p, const char* in, bool rflag) override; expected<void> assign_tcp_doorman(abstract_broker*, accept_handle hdl) override; accept_handle add_tcp_doorman(abstract_broker*, asio_tcp_socket_acceptor&& sock); accept_handle add_tcp_doorman(abstract_broker*, native_socket fd) override; expected<std::pair<accept_handle, uint16_t>> add_tcp_doorman(abstract_broker*, uint16_t, const char*, bool) override; void exec_later(resumable* ptr) override; asio_multiplexer(actor_system* sys); ~asio_multiplexer(); supervisor_ptr make_supervisor() override; void run() override; boost::asio::io_service* pimpl() override; inline boost::asio::io_service& service() { return service_; } private: io_service service_; std::mutex mtx_sockets_; std::mutex mtx_acceptors_; std::map<int64_t, asio_tcp_socket> unassigned_sockets_; std::map<int64_t, asio_tcp_socket_acceptor> unassigned_acceptors_; }; template <class T> connection_handle conn_hdl_from_socket(T& sock) { return connection_handle::from_int( int64_from_native_socket(sock.native_handle())); } template <class T> accept_handle accept_hdl_from_socket(T& sock) { return accept_handle::from_int( int64_from_native_socket(sock.native_handle())); } /// @relates manager using manager_ptr = intrusive_ptr<manager>; /// A stream capable of both reading and writing. The stream's input /// data is forwarded to its {@link stream_manager manager}. template <class Socket> class asio_stream { public: /// A smart pointer to a stream manager. using manager_ptr = intrusive_ptr<stream_manager>; /// A buffer class providing a compatible interface to `std::vector`. using buffer_type = std::vector<char>; asio_stream(asio_multiplexer& ref) : reading_(false), writing_(false), ack_writes_(false), fd_(ref.service()), backend_(ref), rd_buf_ready_(false), async_read_pending_(false) { configure_read(receive_policy::at_most(1024)); } /// Returns the IO socket. Socket& socket_handle() { return fd_; } /// Returns the IO socket. const Socket& socket_handle() const { return fd_; } /// Initializes this stream, setting the socket handle to `fd`. void init(Socket fd) { fd_ = std::move(fd); } /// Starts reading data from the socket, forwarding incoming data to `mgr`. void start(stream_manager* mgr) { CAF_ASSERT(mgr != nullptr); activate(mgr); } /// Configures how much data will be provided for the next `consume` callback. /// @warning Must not be called outside the IO multiplexers event loop /// once the stream has been started. void configure_read(receive_policy::config config) { rd_flag_ = config.first; rd_size_ = config.second; } void ack_writes(bool enable) { CAF_LOG_TRACE(CAF_ARG(enable)); ack_writes_ = enable; } /// Copies data to the write buffer. /// @note Not thread safe. void write(const void* buf, size_t num_bytes) { CAF_LOG_TRACE(CAF_ARG(num_bytes)); auto first = reinterpret_cast<const char*>(buf); auto last = first + num_bytes; wr_offline_buf_.insert(wr_offline_buf_.end(), first, last); } /// Returns the write buffer of this stream. /// @warning Must not be modified outside the IO multiplexers event loop /// once the stream has been started. buffer_type& wr_buf() { return wr_offline_buf_; } buffer_type& rd_buf() { return rd_buf_; } /// Sends the content of the write buffer, calling the `io_failure` /// member function of `mgr` in case of an error. /// @warning Must not be called outside the IO multiplexers event loop /// once the stream has been started. void flush(const manager_ptr& mgr) { CAF_ASSERT(mgr != nullptr); if (!wr_offline_buf_.empty() && !writing_) { writing_ = true; write_loop(mgr); } } /// Closes the network connection, thus stopping this stream. void stop() { CAF_LOG_TRACE(""); fd_.close(); } void stop_reading() { CAF_LOG_TRACE(""); error_code ec; // ignored fd_.shutdown(boost::asio::ip::tcp::socket::shutdown_receive, ec); } asio_multiplexer& backend() { return backend_; } /// Activates the stream. void activate(stream_manager* mgr) { reading_ = true; read_loop(mgr); } /// Stops activity of the stream. void passivate() { reading_ = false; } private: bool read_one(stream_manager* ptr, size_t num_bytes) { if (!reading_) { // broker was passivated while async read was on its way rd_buf_ready_ = true; // make sure buf size matches read_bytes in case of async_read if (rd_buf_.size() != num_bytes) rd_buf_.resize(num_bytes); return false; } if (ptr->consume(&backend(), rd_buf_.data(), num_bytes)) return reading_; return false; } void read_loop(manager_ptr mgr) { if (async_read_pending_) return; if (rd_buf_ready_) { rd_buf_ready_ = false; if (read_one(mgr.get(), rd_buf_.size())) read_loop(std::move(mgr)); return; } auto cb = [=](const error_code& ec, size_t read_bytes) mutable { async_read_pending_ = false; CAF_LOG_TRACE(""); if (!ec) { // bail out early in case broker passivated stream in the meantime if (read_one(mgr.get(), read_bytes)) read_loop(std::move(mgr)); } else { mgr->io_failure(&backend(), operation::read); } }; switch (rd_flag_) { case receive_policy_flag::exactly: if (rd_buf_.size() < rd_size_) rd_buf_.resize(rd_size_); async_read_pending_ = true; boost::asio::async_read(fd_, boost::asio::buffer(rd_buf_, rd_size_), cb); break; case receive_policy_flag::at_most: if (rd_buf_.size() < rd_size_) rd_buf_.resize(rd_size_); async_read_pending_ = true; fd_.async_read_some(boost::asio::buffer(rd_buf_, rd_size_), cb); break; case receive_policy_flag::at_least: { // read up to 10% more, but at least allow 100 bytes more auto min_size = rd_size_ + std::max<size_t>(100, rd_size_ / 10); if (rd_buf_.size() < min_size) { rd_buf_.resize(min_size); } collect_data(mgr, 0); break; } } } void write_loop(const manager_ptr& mgr) { if (wr_offline_buf_.empty()) { writing_ = false; return; } wr_buf_.clear(); wr_buf_.swap(wr_offline_buf_); boost::asio::async_write( fd_, boost::asio::buffer(wr_buf_), [=](const error_code& ec, size_t nb) { CAF_LOG_TRACE(""); if (ec) { CAF_LOG_DEBUG(CAF_ARG(ec.message())); mgr->io_failure(&backend(), operation::read); writing_ = false; return; } CAF_LOG_DEBUG(CAF_ARG(nb)); if (ack_writes_) mgr->data_transferred(&backend(), nb, wr_offline_buf_.size()); write_loop(mgr); }); } void collect_data(manager_ptr mgr, size_t collected_bytes) { async_read_pending_ = true; fd_.async_read_some(boost::asio::buffer(rd_buf_.data() + collected_bytes, rd_buf_.size() - collected_bytes), [=](const error_code& ec, size_t nb) mutable { async_read_pending_ = false; CAF_LOG_TRACE(CAF_ARG(nb)); if (!ec) { auto sum = collected_bytes + nb; if (sum >= rd_size_) { if (read_one(mgr.get(), sum)) read_loop(std::move(mgr)); } else { collect_data(std::move(mgr), sum); } } else { mgr->io_failure(&backend(), operation::write); } }); } /// Set if read loop was started by user and unset if passivate is called. bool reading_; /// Set on flush, also indicates that an async_write is pending. bool writing_; /// Stores whether user requested ACK messages for async writes. bool ack_writes_; /// TCP socket for this connection. Socket fd_; /// Configures how chunk sizes are calculated. receive_policy_flag rd_flag_; /// Minimum, maximum, or exact size of a chunk, depending on `rd_flag_`. size_t rd_size_; /// Input buffer. buffer_type rd_buf_; /// Output buffer for ASIO. buffer_type wr_buf_; /// Swapped with `wr_buf_` before next write. Users write into this buffer /// as long as `wr_buf_` is processed by ASIO. buffer_type wr_offline_buf_; /// Reference to our I/O backend. asio_multiplexer& backend_; /// Signalizes that a scribe was passivated while an async read was pending. bool rd_buf_ready_; /// Makes sure no more than one async_read is pending at any given time bool async_read_pending_; }; /// An acceptor is responsible for accepting incoming connections. template <class SocketAcceptor> class asio_acceptor { using protocol_type = typename SocketAcceptor::protocol_type; using socket_type = boost::asio::basic_stream_socket<protocol_type>; public: /// A manager providing the `accept` member function. using manager_type = acceptor_manager; /// A smart pointer to an acceptor manager. using manager_ptr = intrusive_ptr<manager_type>; asio_acceptor(asio_multiplexer& am, io_service& io) : accepting_(false), backend_(am), accept_fd_(io), fd_valid_(false), fd_(io), async_accept_pending_(false) { // nop } /// Returns the `multiplexer` this acceptor belongs to. asio_multiplexer& backend() { return backend_; } /// Returns the IO socket. SocketAcceptor& socket_handle() { return accept_fd_; } /// Returns the IO socket. const SocketAcceptor& socket_handle() const { return accept_fd_; } /// Returns the accepted socket. This member function should /// be called only from the `new_connection` callback. inline socket_type& accepted_socket() { return fd_; } /// Initializes this acceptor, setting the socket handle to `fd`. void init(SocketAcceptor fd) { accept_fd_ = std::move(fd); } /// Starts this acceptor, forwarding all incoming connections to /// `manager`. The intrusive pointer will be released after the /// acceptor has been closed or an IO error occured. void start(manager_type* mgr) { activate(mgr); } /// Starts the accept loop. void activate(manager_type* mgr) { accepting_ = true; accept_loop(mgr); } /// Starts the accept loop. void passivate() { accepting_ = false; } /// Closes the network connection, thus stopping this acceptor. void stop() { accept_fd_.close(); } private: bool accept_one(manager_type* mgr) { auto res = mgr->new_connection(); // moves fd_ // reset fd_ for next accept operation fd_ = socket_type{accept_fd_.get_io_service()}; return res && accepting_; } void accept_loop(manager_ptr mgr) { if (async_accept_pending_) return; // accept "cached" connection first if (fd_valid_) { fd_valid_ = false; if (accept_one(mgr.get())) accept_loop(std::move(mgr)); return; } async_accept_pending_ = true; accept_fd_.async_accept(fd_, [=](const error_code& ec) mutable { CAF_LOG_TRACE(""); async_accept_pending_ = false; if (!ec) { // if broker has passivated this in the meantime, cache fd_ for later if (!accepting_) { fd_valid_ = true; return; } if (accept_one(mgr.get())) accept_loop(std::move(mgr)); } else { mgr->io_failure(&backend(), operation::read); } }); } bool accepting_; asio_multiplexer& backend_; SocketAcceptor accept_fd_; bool fd_valid_; socket_type fd_; /// Makes sure no more than one async_accept is pending at any given time bool async_accept_pending_; }; } // namesapce network } // namespace io } // namespace caf #endif // CAF_IO_NETWORK_ASIO_MULTIPLEXER_HPP <|endoftext|>
<commit_before>#include "PointRenderer.h" #include "graphics/Shader.h" #include "graphics/ShaderManager.h" #include "graphics/Texture.h" #include "graphics/TextureManager.h" #include "graphics/ViewState.h" #include "graphics/shaders/RegularShaderSource.h" #include "graphics/utils/GLContext.h" #include "layers/VectorLayer.h" #include "renderers/drawdatas/PointDrawData.h" #include "renderers/components/RayIntersectedElement.h" #include "renderers/components/StyleTextureCache.h" #include "utils/Const.h" #include "utils/Log.h" #include "vectorelements/Point.h" #include <cglib/mat.h> namespace carto { PointRenderer::PointRenderer() : _elements(), _tempElements(), _drawDataBuffer(), _prevBitmap(nullptr), _colorBuf(), _coordBuf(), _indexBuf(), _texCoordBuf(), _shader(), _a_color(0), _a_coord(0), _a_texCoord(0), _u_mvpMat(0), _u_tex(0), _mutex() { } PointRenderer::~PointRenderer() { } void PointRenderer::offsetLayerHorizontally(double offset) { // Offset current draw data batch horizontally by the required amount std::lock_guard<std::mutex> lock(_mutex); for (const std::shared_ptr<Point>& element : _elements) { element->getDrawData()->offsetHorizontally(offset); } } void PointRenderer::onSurfaceCreated(const std::shared_ptr<ShaderManager>& shaderManager, const std::shared_ptr<TextureManager>& textureManager) { _shader = shaderManager->createShader(regular_shader_source); // Get shader variables locations glUseProgram(_shader->getProgId()); _a_color = _shader->getAttribLoc("a_color"); _a_coord = _shader->getAttribLoc("a_coord"); _a_texCoord = _shader->getAttribLoc("a_texCoord"); _u_mvpMat = _shader->getUniformLoc("u_mvpMat"); _u_tex = _shader->getUniformLoc("u_tex"); } void PointRenderer::onDrawFrame(float deltaSeconds, StyleTextureCache& styleCache, const ViewState& viewState) { std::lock_guard<std::mutex> lock(_mutex); if (_elements.empty()) { // Early return, to avoid calling glUseProgram etc. return; } bind(viewState); // Draw points, batch by bitmap for (const std::shared_ptr<Point>& element : _elements) { std::shared_ptr<PointDrawData> drawData = element->getDrawData(); addToBatch(drawData, styleCache, viewState); } drawBatch(styleCache, viewState); unbind(); GLContext::CheckGLError("PointRenderer::onDrawFrame"); } void PointRenderer::onSurfaceDestroyed() { _shader.reset(); } void PointRenderer::addElement(const std::shared_ptr<Point>& element) { _tempElements.push_back(element); } void PointRenderer::refreshElements() { std::lock_guard<std::mutex> lock(_mutex); _elements.clear(); _elements.swap(_tempElements); } void PointRenderer::updateElement(const std::shared_ptr<Point>& element) { std::lock_guard<std::mutex> lock(_mutex); if (std::find(_elements.begin(), _elements.end(), element) == _elements.end()) { _elements.push_back(element); } } void PointRenderer::removeElement(const std::shared_ptr<Point>& element) { std::lock_guard<std::mutex> lock(_mutex); _elements.erase(std::remove(_elements.begin(), _elements.end(), element), _elements.end()); } void PointRenderer::calculateRayIntersectedElements(const std::shared_ptr<VectorLayer>& layer, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) const { std::lock_guard<std::mutex> lock(_mutex); for (const std::shared_ptr<Point>& element : _elements) { FindElementRayIntersection(element, element->getDrawData(), layer, ray, viewState, results); } } void PointRenderer::BuildAndDrawBuffers(GLuint a_color, GLuint a_coord, GLuint a_texCoord, std::vector<unsigned char>& colorBuf, std::vector<float>& coordBuf, std::vector<unsigned short>& indexBuf, std::vector<float>& texCoordBuf, std::vector<std::shared_ptr<PointDrawData> >& drawDataBuffer, const cglib::vec2<float>& texCoordScale, StyleTextureCache& styleCache, const ViewState& viewState) { // Resize the buffers, if necessary if (coordBuf.size() < drawDataBuffer.size() * 4 * 3) { coordBuf.resize(std::min(drawDataBuffer.size() * 4 * 3, GLContext::MAX_VERTEXBUFFER_SIZE * 3)); texCoordBuf.resize(std::min(drawDataBuffer.size() * 4 * 2, GLContext::MAX_VERTEXBUFFER_SIZE * 2)); colorBuf.resize(std::min(drawDataBuffer.size() * 4 * 4, GLContext::MAX_VERTEXBUFFER_SIZE * 4)); indexBuf.resize(std::min(drawDataBuffer.size() * 6, GLContext::MAX_VERTEXBUFFER_SIZE)); } // Calculate and draw buffers cglib::vec3<double> cameraPos = viewState.getCameraPos(); GLuint drawDataIndex = 0; for (std::size_t i = 0; i < drawDataBuffer.size(); i++) { const std::shared_ptr<PointDrawData>& drawData = drawDataBuffer[i]; float coordScale = drawData->getSize() * viewState.getUnitToDPCoef() * 0.5f; cglib::vec3<float> translate = cglib::vec3<float>::convert(drawData->getPos() - cameraPos); cglib::vec3<float> dx = drawData->getXAxis() * coordScale; cglib::vec3<float> dy = drawData->getYAxis() * coordScale; // Check for possible overflow in the buffers if ((drawDataIndex + 1) * 6 > GLContext::MAX_VERTEXBUFFER_SIZE) { // If it doesn't fit, stop and draw the buffers glVertexAttribPointer(a_color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colorBuf.data()); glVertexAttribPointer(a_coord, 3, GL_FLOAT, GL_FALSE, 0, coordBuf.data()); glVertexAttribPointer(a_texCoord, 2, GL_FLOAT, GL_FALSE, 0, texCoordBuf.data()); glDrawElements(GL_TRIANGLES, drawDataIndex * 6, GL_UNSIGNED_SHORT, indexBuf.data()); // Start filling buffers from the beginning drawDataIndex = 0; } // Calculate coordinates int coordIndex = drawDataIndex * 4 * 3; coordBuf[coordIndex + 0] = translate(0) - dx(0) + dy(0); coordBuf[coordIndex + 1] = translate(1) - dx(1) + dy(1); coordBuf[coordIndex + 2] = translate(2) - dx(2) + dy(2); coordBuf[coordIndex + 3] = translate(0) - dx(0) - dy(0); coordBuf[coordIndex + 4] = translate(1) - dx(1) - dy(1); coordBuf[coordIndex + 5] = translate(2) - dx(2) - dy(2); coordBuf[coordIndex + 6] = translate(0) + dx(0) + dy(0); coordBuf[coordIndex + 7] = translate(1) + dx(1) + dy(1); coordBuf[coordIndex + 8] = translate(2) + dx(2) + dy(2); coordBuf[coordIndex + 9] = translate(0) + dx(0) - dy(0); coordBuf[coordIndex + 10] = translate(1) + dx(1) - dy(1); coordBuf[coordIndex + 11] = translate(2) + dx(2) - dy(2); // Calculate texture coordinates int texCoordIndex = drawDataIndex * 4 * 2; texCoordBuf[texCoordIndex + 0] = 0.0f; texCoordBuf[texCoordIndex + 1] = texCoordScale(1); texCoordBuf[texCoordIndex + 2] = 0.0f; texCoordBuf[texCoordIndex + 3] = 0.0f; texCoordBuf[texCoordIndex + 4] = texCoordScale(0); texCoordBuf[texCoordIndex + 5] = texCoordScale(1); texCoordBuf[texCoordIndex + 6] = texCoordScale(0); texCoordBuf[texCoordIndex + 7] = 0.0f; // Calculate colors const Color& color = drawData->getColor(); int colorIndex = drawDataIndex * 4 * 4; for (int i = 0; i < 16; i += 4) { colorBuf[colorIndex + i] = color.getR(); colorBuf[colorIndex + i + 1] = color.getG(); colorBuf[colorIndex + i + 2] = color.getB(); colorBuf[colorIndex + i + 3] = color.getA(); } // Calculate indices int indexIndex = drawDataIndex * 6; int vertexIndex = drawDataIndex * 4; indexBuf[indexIndex + 0] = vertexIndex; indexBuf[indexIndex + 1] = vertexIndex + 1; indexBuf[indexIndex + 2] = vertexIndex + 2; indexBuf[indexIndex + 3] = vertexIndex + 1; indexBuf[indexIndex + 4] = vertexIndex + 3; indexBuf[indexIndex + 5] = vertexIndex + 2; drawDataIndex++; } // Draw the final batch if (drawDataIndex > 0) { glVertexAttribPointer(a_color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colorBuf.data()); glVertexAttribPointer(a_coord, 3, GL_FLOAT, GL_FALSE, 0, coordBuf.data()); glVertexAttribPointer(a_texCoord, 2, GL_FLOAT, GL_FALSE, 0, texCoordBuf.data()); glDrawElements(GL_TRIANGLES, drawDataIndex * 6, GL_UNSIGNED_SHORT, indexBuf.data()); } } bool PointRenderer::FindElementRayIntersection(const std::shared_ptr<VectorElement>& element, const std::shared_ptr<PointDrawData>& drawData, const std::shared_ptr<VectorLayer>& layer, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) { const cglib::vec3<double>& pos = drawData->getPos(); // Calculate coordinates float coordScale = drawData->getSize() * viewState.getUnitToDPCoef() * 0.5f * drawData->getClickScale(); cglib::vec3<double> topLeft (pos(0) - coordScale, pos(1) + coordScale, pos(2)); cglib::vec3<double> bottomLeft (pos(0) - coordScale, pos(1) - coordScale, pos(2)); cglib::vec3<double> topRight (pos(0) + coordScale, pos(1) + coordScale, pos(2)); cglib::vec3<double> bottomRight(pos(0) + coordScale, pos(1) - coordScale, pos(2)); // If either triangle intersects the ray, add the element to result list double t = 0; if (cglib::intersect_triangle(topLeft, bottomLeft, topRight, ray, &t) || cglib::intersect_triangle(bottomLeft, bottomRight, topRight, ray, &t)) { MapPos clickPos(ray(t)(0), ray(t)(1), ray(t)(2)); int priority = static_cast<int>(results.size()); results.push_back(RayIntersectedElement(std::static_pointer_cast<VectorElement>(element), layer, ray(t), pos, priority)); return true; } return false; } void PointRenderer::bind(const ViewState& viewState) { // Prepare for drawing glUseProgram(_shader->getProgId()); // Texture glUniform1i(_u_tex, 0); // Matrix const cglib::mat4x4<float>& mvpMat = viewState.getRTEModelviewProjectionMat(); glUniformMatrix4fv(_u_mvpMat, 1, GL_FALSE, mvpMat.data()); // Coords, texCoords, colors glEnableVertexAttribArray(_a_coord); glEnableVertexAttribArray(_a_texCoord); glEnableVertexAttribArray(_a_color); } void PointRenderer::unbind() { // Disable bound arrays glDisableVertexAttribArray(_a_coord); glDisableVertexAttribArray(_a_texCoord); glDisableVertexAttribArray(_a_color); } bool PointRenderer::isEmptyBatch() const { return _drawDataBuffer.empty(); } void PointRenderer::addToBatch(const std::shared_ptr<PointDrawData>& drawData, StyleTextureCache& styleCache, const ViewState& viewState) { const Bitmap* bitmap = drawData->getBitmap().get(); if (!_drawDataBuffer.empty() && ((_prevBitmap != bitmap))) { drawBatch(styleCache, viewState); } _drawDataBuffer.push_back(std::move(drawData)); _prevBitmap = bitmap; } void PointRenderer::drawBatch(StyleTextureCache& styleCache, const ViewState& viewState) { if (_drawDataBuffer.empty()) { return; } // Bind texture const std::shared_ptr<Bitmap>& bitmap = _drawDataBuffer.front()->getBitmap(); std::shared_ptr<Texture> texture = styleCache.get(bitmap); if (!texture) { texture = styleCache.create(bitmap, true, false); } glBindTexture(GL_TEXTURE_2D, texture->getTexId()); // Draw the draw datas BuildAndDrawBuffers(_a_color, _a_coord, _a_texCoord, _colorBuf, _coordBuf, _indexBuf, _texCoordBuf, _drawDataBuffer, texture->getTexCoordScale(), styleCache, viewState); _drawDataBuffer.clear(); _prevBitmap = nullptr; } } <commit_msg>Fix point intersection calculations<commit_after>#include "PointRenderer.h" #include "graphics/Shader.h" #include "graphics/ShaderManager.h" #include "graphics/Texture.h" #include "graphics/TextureManager.h" #include "graphics/ViewState.h" #include "graphics/shaders/RegularShaderSource.h" #include "graphics/utils/GLContext.h" #include "layers/VectorLayer.h" #include "renderers/drawdatas/PointDrawData.h" #include "renderers/components/RayIntersectedElement.h" #include "renderers/components/StyleTextureCache.h" #include "utils/Const.h" #include "utils/Log.h" #include "vectorelements/Point.h" #include <cglib/mat.h> namespace carto { PointRenderer::PointRenderer() : _elements(), _tempElements(), _drawDataBuffer(), _prevBitmap(nullptr), _colorBuf(), _coordBuf(), _indexBuf(), _texCoordBuf(), _shader(), _a_color(0), _a_coord(0), _a_texCoord(0), _u_mvpMat(0), _u_tex(0), _mutex() { } PointRenderer::~PointRenderer() { } void PointRenderer::offsetLayerHorizontally(double offset) { // Offset current draw data batch horizontally by the required amount std::lock_guard<std::mutex> lock(_mutex); for (const std::shared_ptr<Point>& element : _elements) { element->getDrawData()->offsetHorizontally(offset); } } void PointRenderer::onSurfaceCreated(const std::shared_ptr<ShaderManager>& shaderManager, const std::shared_ptr<TextureManager>& textureManager) { _shader = shaderManager->createShader(regular_shader_source); // Get shader variables locations glUseProgram(_shader->getProgId()); _a_color = _shader->getAttribLoc("a_color"); _a_coord = _shader->getAttribLoc("a_coord"); _a_texCoord = _shader->getAttribLoc("a_texCoord"); _u_mvpMat = _shader->getUniformLoc("u_mvpMat"); _u_tex = _shader->getUniformLoc("u_tex"); } void PointRenderer::onDrawFrame(float deltaSeconds, StyleTextureCache& styleCache, const ViewState& viewState) { std::lock_guard<std::mutex> lock(_mutex); if (_elements.empty()) { // Early return, to avoid calling glUseProgram etc. return; } bind(viewState); // Draw points, batch by bitmap for (const std::shared_ptr<Point>& element : _elements) { std::shared_ptr<PointDrawData> drawData = element->getDrawData(); addToBatch(drawData, styleCache, viewState); } drawBatch(styleCache, viewState); unbind(); GLContext::CheckGLError("PointRenderer::onDrawFrame"); } void PointRenderer::onSurfaceDestroyed() { _shader.reset(); } void PointRenderer::addElement(const std::shared_ptr<Point>& element) { _tempElements.push_back(element); } void PointRenderer::refreshElements() { std::lock_guard<std::mutex> lock(_mutex); _elements.clear(); _elements.swap(_tempElements); } void PointRenderer::updateElement(const std::shared_ptr<Point>& element) { std::lock_guard<std::mutex> lock(_mutex); if (std::find(_elements.begin(), _elements.end(), element) == _elements.end()) { _elements.push_back(element); } } void PointRenderer::removeElement(const std::shared_ptr<Point>& element) { std::lock_guard<std::mutex> lock(_mutex); _elements.erase(std::remove(_elements.begin(), _elements.end(), element), _elements.end()); } void PointRenderer::calculateRayIntersectedElements(const std::shared_ptr<VectorLayer>& layer, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) const { std::lock_guard<std::mutex> lock(_mutex); for (const std::shared_ptr<Point>& element : _elements) { FindElementRayIntersection(element, element->getDrawData(), layer, ray, viewState, results); } } void PointRenderer::BuildAndDrawBuffers(GLuint a_color, GLuint a_coord, GLuint a_texCoord, std::vector<unsigned char>& colorBuf, std::vector<float>& coordBuf, std::vector<unsigned short>& indexBuf, std::vector<float>& texCoordBuf, std::vector<std::shared_ptr<PointDrawData> >& drawDataBuffer, const cglib::vec2<float>& texCoordScale, StyleTextureCache& styleCache, const ViewState& viewState) { // Resize the buffers, if necessary if (coordBuf.size() < drawDataBuffer.size() * 4 * 3) { coordBuf.resize(std::min(drawDataBuffer.size() * 4 * 3, GLContext::MAX_VERTEXBUFFER_SIZE * 3)); texCoordBuf.resize(std::min(drawDataBuffer.size() * 4 * 2, GLContext::MAX_VERTEXBUFFER_SIZE * 2)); colorBuf.resize(std::min(drawDataBuffer.size() * 4 * 4, GLContext::MAX_VERTEXBUFFER_SIZE * 4)); indexBuf.resize(std::min(drawDataBuffer.size() * 6, GLContext::MAX_VERTEXBUFFER_SIZE)); } // Calculate and draw buffers cglib::vec3<double> cameraPos = viewState.getCameraPos(); GLuint drawDataIndex = 0; for (std::size_t i = 0; i < drawDataBuffer.size(); i++) { const std::shared_ptr<PointDrawData>& drawData = drawDataBuffer[i]; float coordScale = drawData->getSize() * viewState.getUnitToDPCoef() * 0.5f; cglib::vec3<float> translate = cglib::vec3<float>::convert(drawData->getPos() - cameraPos); cglib::vec3<float> dx = drawData->getXAxis() * coordScale; cglib::vec3<float> dy = drawData->getYAxis() * coordScale; // Check for possible overflow in the buffers if ((drawDataIndex + 1) * 6 > GLContext::MAX_VERTEXBUFFER_SIZE) { // If it doesn't fit, stop and draw the buffers glVertexAttribPointer(a_color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colorBuf.data()); glVertexAttribPointer(a_coord, 3, GL_FLOAT, GL_FALSE, 0, coordBuf.data()); glVertexAttribPointer(a_texCoord, 2, GL_FLOAT, GL_FALSE, 0, texCoordBuf.data()); glDrawElements(GL_TRIANGLES, drawDataIndex * 6, GL_UNSIGNED_SHORT, indexBuf.data()); // Start filling buffers from the beginning drawDataIndex = 0; } // Calculate coordinates int coordIndex = drawDataIndex * 4 * 3; coordBuf[coordIndex + 0] = translate(0) - dx(0) + dy(0); coordBuf[coordIndex + 1] = translate(1) - dx(1) + dy(1); coordBuf[coordIndex + 2] = translate(2) - dx(2) + dy(2); coordBuf[coordIndex + 3] = translate(0) - dx(0) - dy(0); coordBuf[coordIndex + 4] = translate(1) - dx(1) - dy(1); coordBuf[coordIndex + 5] = translate(2) - dx(2) - dy(2); coordBuf[coordIndex + 6] = translate(0) + dx(0) + dy(0); coordBuf[coordIndex + 7] = translate(1) + dx(1) + dy(1); coordBuf[coordIndex + 8] = translate(2) + dx(2) + dy(2); coordBuf[coordIndex + 9] = translate(0) + dx(0) - dy(0); coordBuf[coordIndex + 10] = translate(1) + dx(1) - dy(1); coordBuf[coordIndex + 11] = translate(2) + dx(2) - dy(2); // Calculate texture coordinates int texCoordIndex = drawDataIndex * 4 * 2; texCoordBuf[texCoordIndex + 0] = 0.0f; texCoordBuf[texCoordIndex + 1] = texCoordScale(1); texCoordBuf[texCoordIndex + 2] = 0.0f; texCoordBuf[texCoordIndex + 3] = 0.0f; texCoordBuf[texCoordIndex + 4] = texCoordScale(0); texCoordBuf[texCoordIndex + 5] = texCoordScale(1); texCoordBuf[texCoordIndex + 6] = texCoordScale(0); texCoordBuf[texCoordIndex + 7] = 0.0f; // Calculate colors const Color& color = drawData->getColor(); int colorIndex = drawDataIndex * 4 * 4; for (int i = 0; i < 16; i += 4) { colorBuf[colorIndex + i] = color.getR(); colorBuf[colorIndex + i + 1] = color.getG(); colorBuf[colorIndex + i + 2] = color.getB(); colorBuf[colorIndex + i + 3] = color.getA(); } // Calculate indices int indexIndex = drawDataIndex * 6; int vertexIndex = drawDataIndex * 4; indexBuf[indexIndex + 0] = vertexIndex; indexBuf[indexIndex + 1] = vertexIndex + 1; indexBuf[indexIndex + 2] = vertexIndex + 2; indexBuf[indexIndex + 3] = vertexIndex + 1; indexBuf[indexIndex + 4] = vertexIndex + 3; indexBuf[indexIndex + 5] = vertexIndex + 2; drawDataIndex++; } // Draw the final batch if (drawDataIndex > 0) { glVertexAttribPointer(a_color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, colorBuf.data()); glVertexAttribPointer(a_coord, 3, GL_FLOAT, GL_FALSE, 0, coordBuf.data()); glVertexAttribPointer(a_texCoord, 2, GL_FLOAT, GL_FALSE, 0, texCoordBuf.data()); glDrawElements(GL_TRIANGLES, drawDataIndex * 6, GL_UNSIGNED_SHORT, indexBuf.data()); } } bool PointRenderer::FindElementRayIntersection(const std::shared_ptr<VectorElement>& element, const std::shared_ptr<PointDrawData>& drawData, const std::shared_ptr<VectorLayer>& layer, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) { float coordScale = drawData->getSize() * viewState.getUnitToDPCoef() * drawData->getClickScale() * 0.5f; cglib::vec3<double> pos = drawData->getPos(); cglib::vec3<double> dx = cglib::vec3<double>::convert(drawData->getXAxis() * coordScale); cglib::vec3<double> dy = cglib::vec3<double>::convert(drawData->getYAxis() * coordScale); // Calculate coordinates cglib::vec3<double> topLeft = pos - dx + dy; cglib::vec3<double> bottomLeft = pos - dx - dy; cglib::vec3<double> topRight = pos + dx + dy; cglib::vec3<double> bottomRight = pos + dx - dy; // If either triangle intersects the ray, add the element to result list double t = 0; if (cglib::intersect_triangle(topLeft, bottomLeft, topRight, ray, &t) || cglib::intersect_triangle(bottomLeft, bottomRight, topRight, ray, &t)) { MapPos clickPos(ray(t)(0), ray(t)(1), ray(t)(2)); int priority = static_cast<int>(results.size()); results.push_back(RayIntersectedElement(std::static_pointer_cast<VectorElement>(element), layer, ray(t), pos, priority)); return true; } return false; } void PointRenderer::bind(const ViewState& viewState) { // Prepare for drawing glUseProgram(_shader->getProgId()); // Texture glUniform1i(_u_tex, 0); // Matrix const cglib::mat4x4<float>& mvpMat = viewState.getRTEModelviewProjectionMat(); glUniformMatrix4fv(_u_mvpMat, 1, GL_FALSE, mvpMat.data()); // Coords, texCoords, colors glEnableVertexAttribArray(_a_coord); glEnableVertexAttribArray(_a_texCoord); glEnableVertexAttribArray(_a_color); } void PointRenderer::unbind() { // Disable bound arrays glDisableVertexAttribArray(_a_coord); glDisableVertexAttribArray(_a_texCoord); glDisableVertexAttribArray(_a_color); } bool PointRenderer::isEmptyBatch() const { return _drawDataBuffer.empty(); } void PointRenderer::addToBatch(const std::shared_ptr<PointDrawData>& drawData, StyleTextureCache& styleCache, const ViewState& viewState) { const Bitmap* bitmap = drawData->getBitmap().get(); if (!_drawDataBuffer.empty() && ((_prevBitmap != bitmap))) { drawBatch(styleCache, viewState); } _drawDataBuffer.push_back(std::move(drawData)); _prevBitmap = bitmap; } void PointRenderer::drawBatch(StyleTextureCache& styleCache, const ViewState& viewState) { if (_drawDataBuffer.empty()) { return; } // Bind texture const std::shared_ptr<Bitmap>& bitmap = _drawDataBuffer.front()->getBitmap(); std::shared_ptr<Texture> texture = styleCache.get(bitmap); if (!texture) { texture = styleCache.create(bitmap, true, false); } glBindTexture(GL_TEXTURE_2D, texture->getTexId()); // Draw the draw datas BuildAndDrawBuffers(_a_color, _a_coord, _a_texCoord, _colorBuf, _coordBuf, _indexBuf, _texCoordBuf, _drawDataBuffer, texture->getTexCoordScale(), styleCache, viewState); _drawDataBuffer.clear(); _prevBitmap = nullptr; } } <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // The code in this file is largely based on KDE's KLineEdit class // as included in KDE 4.5. See there for its authors: // http://api.kde.org/4.x-api/kdelibs-apidocs/kdeui/html/klineedit_8cpp.html // // Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org> // #include "RoutingLineEdit.h" #include <QtGui/QApplication> #include <QtGui/QClipboard> #include <QtGui/QLabel> #include <QtGui/QStyle> #include <QtGui/QMouseEvent> namespace Marble { class RoutingLineEditPrivate { public: QLabel* m_clearButton; QPixmap m_clearPixmap; RoutingLineEditPrivate( RoutingLineEdit* parent ); }; RoutingLineEditPrivate::RoutingLineEditPrivate( RoutingLineEdit* parent ) : m_clearButton( new QLabel( parent ) ) { m_clearButton->setCursor( Qt::ArrowCursor ); m_clearButton->setToolTip( QObject::tr( "Clear" ) ); } RoutingLineEdit::RoutingLineEdit( QWidget *parent ) : QLineEdit( parent ), d( new RoutingLineEditPrivate( this ) ) { updateClearButtonIcon( text() ); updateClearButton(); // Padding for clear button to avoid text underflow QString const direction = layoutDirection() == Qt::LeftToRight ? "right" : "left"; setStyleSheet( QString( ":enabled { padding-%1: %2; }").arg( direction).arg( 18 ) ); connect( this, SIGNAL( textChanged( QString ) ), SLOT( updateClearButtonIcon( QString ) ) ); } RoutingLineEdit::~RoutingLineEdit() { delete d; } void RoutingLineEdit::updateClearButtonIcon( const QString& text ) { d->m_clearButton->setVisible( text.length() > 0 ); if ( d->m_clearButton->pixmap() && !d->m_clearButton->pixmap()->isNull() ) { return; } if ( layoutDirection() == Qt::LeftToRight ) { d->m_clearButton->setPixmap( QPixmap( ":/icons/edit-clear-locationbar-rtl.png" ) ); } else { d->m_clearButton->setPixmap( QPixmap ( ":/icons/edit-clear-locationbar-ltr.png" ) ); } } void RoutingLineEdit::updateClearButton() { const QSize geom = size(); const int frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth, 0, this ); const int pixmapSize = d->m_clearButton->pixmap()->width(); int y = ( geom.height() - pixmapSize ) / 2; if ( layoutDirection() == Qt::LeftToRight ) { d->m_clearButton->move( geom.width() - frameWidth - pixmapSize - 1, y ); } else { d->m_clearButton->move( frameWidth + 1, y ); } } void RoutingLineEdit::mouseReleaseEvent( QMouseEvent* e ) { if ( d->m_clearButton == childAt( e->pos() ) ) { QString newText; if ( e->button() == Qt::MidButton ) { newText = QApplication::clipboard()->text( QClipboard::Selection ); setText( newText ); } else { setSelection( 0, text().size() ); del(); emit clearButtonClicked(); } emit textChanged( newText ); } QLineEdit::mouseReleaseEvent( e ); } void RoutingLineEdit::resizeEvent( QResizeEvent * event ) { updateClearButton(); QLineEdit::resizeEvent( event ); } } // namespace Marble #include "RoutingLineEdit.moc" <commit_msg>do not set a style sheet on maemo since that conflicts with the maemo style<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // The code in this file is largely based on KDE's KLineEdit class // as included in KDE 4.5. See there for its authors: // http://api.kde.org/4.x-api/kdelibs-apidocs/kdeui/html/klineedit_8cpp.html // // Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org> // #include "RoutingLineEdit.h" #include "global.h" #include <QtGui/QApplication> #include <QtGui/QClipboard> #include <QtGui/QLabel> #include <QtGui/QStyle> #include <QtGui/QMouseEvent> namespace Marble { class RoutingLineEditPrivate { public: QLabel* m_clearButton; QPixmap m_clearPixmap; RoutingLineEditPrivate( RoutingLineEdit* parent ); }; RoutingLineEditPrivate::RoutingLineEditPrivate( RoutingLineEdit* parent ) : m_clearButton( new QLabel( parent ) ) { m_clearButton->setCursor( Qt::ArrowCursor ); m_clearButton->setToolTip( QObject::tr( "Clear" ) ); } RoutingLineEdit::RoutingLineEdit( QWidget *parent ) : QLineEdit( parent ), d( new RoutingLineEditPrivate( this ) ) { updateClearButtonIcon( text() ); updateClearButton(); // Padding for clear button to avoid text underflow QString const direction = layoutDirection() == Qt::LeftToRight ? "right" : "left"; if ( !MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ) { setStyleSheet( QString( ":enabled { padding-%1: %2; }").arg( direction).arg( 18 ) ); } connect( this, SIGNAL( textChanged( QString ) ), SLOT( updateClearButtonIcon( QString ) ) ); } RoutingLineEdit::~RoutingLineEdit() { delete d; } void RoutingLineEdit::updateClearButtonIcon( const QString& text ) { d->m_clearButton->setVisible( text.length() > 0 ); if ( d->m_clearButton->pixmap() && !d->m_clearButton->pixmap()->isNull() ) { return; } if ( layoutDirection() == Qt::LeftToRight ) { d->m_clearButton->setPixmap( QPixmap( ":/icons/edit-clear-locationbar-rtl.png" ) ); } else { d->m_clearButton->setPixmap( QPixmap ( ":/icons/edit-clear-locationbar-ltr.png" ) ); } } void RoutingLineEdit::updateClearButton() { const QSize geom = size(); const int frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth, 0, this ); const int pixmapSize = d->m_clearButton->pixmap()->width(); int y = ( geom.height() - pixmapSize ) / 2; if ( layoutDirection() == Qt::LeftToRight ) { d->m_clearButton->move( geom.width() - frameWidth - pixmapSize - 1, y ); } else { d->m_clearButton->move( frameWidth + 1, y ); } } void RoutingLineEdit::mouseReleaseEvent( QMouseEvent* e ) { if ( d->m_clearButton == childAt( e->pos() ) ) { QString newText; if ( e->button() == Qt::MidButton ) { newText = QApplication::clipboard()->text( QClipboard::Selection ); setText( newText ); } else { setSelection( 0, text().size() ); del(); emit clearButtonClicked(); } emit textChanged( newText ); } QLineEdit::mouseReleaseEvent( e ); } void RoutingLineEdit::resizeEvent( QResizeEvent * event ) { updateClearButton(); QLineEdit::resizeEvent( event ); } } // namespace Marble #include "RoutingLineEdit.moc" <|endoftext|>
<commit_before>#include "braincloud/internal/GUID.h" #include <iomanip> #include <sstream> #include <algorithm> #if defined(WINAPI_FAMILY) || defined(WIN32) #include <objbase.h> #endif // preston: use the crossguid library on android. // it does support other platforms so a future enhancement would // be to solely //#ifdef __ANDROID //#include "jni.h" //#include "crossguid.h" //#endif std::string BrainCloud::GUID::generateGUID() { unsigned char buffer[16] = { 0 }; #if defined(WINAPI_FAMILY) || defined(WIN32) UUID guid; CoCreateGuid(&guid); memcpy(buffer, &guid, 16); #else // preston: for Android we should use crossguid lib to get the right thing... // just not sure how to get the JNIEnv pointer right now... for (int i = 0; i < 16; ++i) { buffer[i] = (unsigned char) (rand() % 255); } #endif std::stringstream ss; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[3]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[2]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[1]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[0]; ss << "-"; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[5]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[4]; ss << "-"; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[7]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[6]; ss << "-"; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[8]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[9]; ss << "-"; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[10]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[11]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[12]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[13]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[14]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[15]; return ss.str(); } <commit_msg>Added ifdef to GUID.cpp as the cocoapods are picking up this file and mac uses a function in GUID.mm.<commit_after>#if !defined(__APPLE__) #include "braincloud/internal/GUID.h" #include <iomanip> #include <sstream> #include <algorithm> #if defined(WINAPI_FAMILY) || defined(WIN32) #include <objbase.h> #endif // preston: use the crossguid library on android. // it does support other platforms so a future enhancement would // be to solely //#ifdef __ANDROID //#include "jni.h" //#include "crossguid.h" //#endif std::string BrainCloud::GUID::generateGUID() { unsigned char buffer[16] = { 0 }; #if defined(WINAPI_FAMILY) || defined(WIN32) UUID guid; CoCreateGuid(&guid); memcpy(buffer, &guid, 16); #else // preston: for Android we should use crossguid lib to get the right thing... // just not sure how to get the JNIEnv pointer right now... for (int i = 0; i < 16; ++i) { buffer[i] = (unsigned char) (rand() % 255); } #endif std::stringstream ss; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[3]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[2]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[1]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[0]; ss << "-"; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[5]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[4]; ss << "-"; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[7]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[6]; ss << "-"; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[8]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[9]; ss << "-"; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[10]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[11]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[12]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[13]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[14]; ss << std::hex << std::setw(2) << std::setfill('0') << (int)buffer[15]; return ss.str(); } #endif // !defined(__APPLE__) <|endoftext|>
<commit_before>#include <cstring> #include <cstdlib> #include <fstream> #include "Game.h" using namespace std; Game::Game(int numOfLand , int numOfZombie ) :map_(numOfLand),numOfZombie_(numOfZombie), numOfLand_(numOfLand) { for (int i=0; i<numOfZombie_; i+=1) { Zombie *temp = new Zombie(RandZombiePos()); zombies_.push_back(temp); } InitPlants() ; } bool Game::InitPlants() // process file plants.txt { fstream f("plants.txt"); if (!f) { cout << "Can't find plants.txt!" << endl; return false; } while (!f.eof()) { string input,name,cost_str; int cost = 0; int fullHP = 0; //getline(f,input); f >> input; if (input == "C")//coin plant { f >> name >> cost_str ; cost_str.erase(cost_str.begin()+0);// erase $ symbol cost = atoi(cost_str.c_str());// change 100 to int f >> fullHP; int round,getmoney; f >> round >> getmoney ; CoinPlant* plant = new CoinPlant(name,cost,fullHP,round,getmoney); plantTypes_.push_back(plant); } else if(input == "S")//horn plant or shoot plant { f >> name >> cost_str ; cost_str.erase(cost_str.begin()+0);// erase $ symbol cost = atoi(cost_str.c_str());// change 100 to int f >> fullHP; int damage; f >> damage; ShotPlant* plant = new ShotPlant(name,cost,fullHP,damage); plantTypes_.push_back(plant); } else if(input == "B")//bomb plant { f >> name >> cost_str ; cost_str.erase(cost_str.begin()+0);// erase $ symbol cost = atoi(cost_str.c_str());// change 100 to int f >> fullHP; BombPlant* plant = new BombPlant(name,cost,fullHP); plantTypes_.push_back(plant); } else if(input == "H")//heal plant { f >> name >> cost_str ; cost_str.erase(cost_str.begin()+0);// erase $ symbol cost = atoi(cost_str.c_str());// change 100 to int int heal; f >> fullHP >> heal; HealPlant* plant = new HealPlant(name,cost,fullHP,heal); plantTypes_.push_back(plant); } if( min_price_ > plantTypes_.back()->getCost() ) min_price_ = plantTypes_.back()->getCost(); } f.close(); return true; } void Game::DisplayOfPlant()const { for (unsigned int i=0; i < plantTypes_.size(); i+=1) { cout << "[" << i << "] "; plantTypes_[i]->display(); } } int Game::RandZombiePos()const { int pos = rand()%numOfLand_; return pos; } int Game::Choice(string input) { int choice = atoi(input.c_str()); if (choice < 0 || choice > (int) plantTypes_.size()) { return lastmove_; } return choice; } void Game::DisplayMap()const { for (int i=0; i<numOfLand_; i+=1) { cout << "[" << i << "]{" ; if (player_.getPos() == i) { cout << "*"; } else { cout << " "; } for (int j=0; j<zombies_.size(); j+=1) { if (zombies_[j]->getPos() == i) { cout << j; } else { cout << " "; } } cout << "}"; if ( !map_[i].getStood() ) { cout << "Empty"; } else { map_[i].getPlant()->displayinfo(); } cout << endl; } } void Game::DisplayZombieInfo()const { cout << "Zombie information:" << endl; for (int i=0; i<zombies_.size(); i+=1) { cout << "[" << i << "] Damage: " << zombies_[i]->getAttack() << " HP:"; zombies_[i]->display(); cout << endl; } } int Game::Move(int max) { int move = rand()%max; return move+1; } void Game::PlayerAction() { if (map_[player_.getPos()].getStood()) { map_[player_.getPos()].getPlant()->doThing( player_ , getPlantList() ); } if (!EnoughMoney()) { cout << "You do not have enough money to plant anything!" << endl; return; } if (map_[player_.getPos()].getStood()) { cout << "Already planted!" << endl; return; } cout << "Player $" << player_.currentMoney() << ": Enter your choice (4 to give up, default: " << lastmove_ << ")...>"; string tempstr; getline(cin,tempstr); int choice = Choice(tempstr); lastmove_ = choice; if (choice == plantTypes_.size() ) { cout << "You give up!" << endl; return; } //Plant *newPlant = new Plant(*plantTypes_[choice]); //plantlist_.push_back(newPlant); if(map_.put( plantTypes_[choice]->clone() , player_.getPos()) )// bool { //player_ -= plantTypes_[choice]->getCost(); // cout << "You have planted " << plantTypes_[choice]->getName() << " at land " << player_.getPos() << " !" << endl; } } vector<Plant*> Game::getPlantList() { vector<Plant*> plantlist ; for( int i = 0 ; i < numOfLand_ ; i+=1 ) { plantlist.push_back(map_[i].getPlant()) ; } return plantlist ; } void Game::NextStep() { size_t currentPos = player_.getPos(); player_.setPos((Move(6)+currentPos)%numOfLand_); } void Game::PlantAction() { for (int i=0; i<numOfLand_; i+=1) { if (map_[i].getStood()) { if(map_[i].getPlant()->doThing(player_,getPlantList()) == 0) cout << "You have get coin!" << endl; } } } void Game::ZombieAction() { for (int i=0; i<zombies_.size(); i+=1) { int ZcurrentPos = zombies_[i]->getPos(); zombies_[i]->setPos((ZcurrentPos+Move(3))%numOfLand_); if(map_[zombies_[i]->getPos()].getStood() && ! map_[zombies_[i]->getPos()].getPlant()->beAttacked(*zombies_[i]) ) { map_[zombies_[i]->getPos()].recycle(); } if (zombies_[i]->getHP()<=0) { zombies_.erase(zombies_.begin()+i); } } } <commit_msg>Update Game.cpp<commit_after>#include <cstring> #include <cstdlib> #include <fstream> #include "Game.h" using namespace std; Game::Game(int numOfLand , int numOfZombie ) :map_(numOfLand),numOfZombie_(numOfZombie), numOfLand_(numOfLand) { for (int i=0; i<numOfZombie_; i+=1) { Zombie *temp = new Zombie(RandZombiePos()); zombies_.push_back(temp); } InitPlants() ; } bool Game::InitPlants() // process file plants.txt { fstream f("plants.txt"); if (!f) { cout << "Can't find plants.txt!" << endl; return false; } while (!f.eof()) { string input,name,cost_str; int cost = 0; int fullHP = 0; //getline(f,input); f >> input; if (input == "C")//coin plant { f >> name >> cost_str ; cost_str.erase(cost_str.begin()+0);// erase $ symbol cost = atoi(cost_str.c_str());// change 100 to int f >> fullHP; int round,getmoney; f >> round >> getmoney ; CoinPlant* plant = new CoinPlant(name,cost,fullHP,round,getmoney); plantTypes_.push_back(plant); } else if(input == "S")//horn plant or shoot plant { f >> name >> cost_str ; cost_str.erase(cost_str.begin()+0);// erase $ symbol cost = atoi(cost_str.c_str());// change 100 to int f >> fullHP; int damage; f >> damage; ShotPlant* plant = new ShotPlant(name,cost,fullHP,damage); plantTypes_.push_back(plant); } else if(input == "B")//bomb plant { f >> name >> cost_str ; cost_str.erase(cost_str.begin()+0);// erase $ symbol cost = atoi(cost_str.c_str());// change 100 to int f >> fullHP; BombPlant* plant = new BombPlant(name,cost,fullHP); plantTypes_.push_back(plant); } else if(input == "H")//heal plant { f >> name >> cost_str ; cost_str.erase(cost_str.begin()+0);// erase $ symbol cost = atoi(cost_str.c_str());// change 100 to int int heal; f >> fullHP >> heal; HealPlant* plant = new HealPlant(name,cost,fullHP,heal); plantTypes_.push_back(plant); } if( min_price_ > plantTypes_.back()->getCost() ) min_price_ = plantTypes_.back()->getCost(); } f.close(); return true; } void Game::DisplayOfPlant()const { for (unsigned int i=0; i < plantTypes_.size(); i+=1) { cout << "[" << i << "] "; plantTypes_[i]->display(); } } int Game::RandZombiePos()const { int pos = rand()%numOfLand_; return pos; } int Game::Choice(string input) { int choice = atoi(input.c_str()); if (choice < 0 || choice > (int) plantTypes_.size()) { return lastmove_; } return choice; } void Game::DisplayMap()const { for (int i=0; i<numOfLand_; i+=1) { cout << "[" << i << "]{" ; if (player_.getPos() == i) { cout << "*"; } else { cout << " "; } for (int j=0; j<zombies_.size(); j+=1) { if (zombies_[j]->getPos() == i) { cout << j; } else { cout << " "; } } cout << "}"; if ( !map_[i].getStood() ) { cout << "Empty"; } else { map_[i].getPlant()->displayinfo(); } cout << endl; } } void Game::DisplayZombieInfo()const { cout << "Zombie information:" << endl; for (int i=0; i<zombies_.size(); i+=1) { cout << "[" << i << "] Damage: " << zombies_[i]->getAttack() << " HP:"; zombies_[i]->display(); cout << endl; } } int Game::Move(int max) { int move = rand()%max; return move+1; } void Game::PlayerAction() { if (map_[player_.getPos()].getStood()) { map_[player_.getPos()].getPlant()->doThing( player_ , getPlantList() ); } if (!EnoughMoney()) { cout << "You do not have enough money to plant anything!" << endl; return; } if (map_[player_.getPos()].getStood()) { cout << "Already planted!" << endl; return; } cout << "Player $" << player_.currentMoney() << ": Enter your choice (4 to give up, default: " << lastmove_ << ")...>"; string tempstr; getline(cin,tempstr); int choice = Choice(tempstr); lastmove_ = choice; if (choice == plantTypes_.size() ) { cout << "You give up!" << endl; return; } //Plant *newPlant = new Plant(*plantTypes_[choice]); //plantlist_.push_back(newPlant); if(map_.put( plantTypes_[choice]->clone() , player_.getPos()) )// bool { //player_ -= plantTypes_[choice]->getCost(); //扣錢 cout << "You have planted " << plantTypes_[choice]->getName() << " at land " << player_.getPos() << " !" << endl; } } vector<Plant*> Game::getPlantList() { vector<Plant*> plantlist ; for( int i = 0 ; i < numOfLand_ ; i+=1 ) { plantlist.push_back(map_[i].getPlant()) ; } return plantlist ; } void Game::NextStep() { size_t currentPos = player_.getPos(); player_.setPos((Move(6)+currentPos)%numOfLand_); } void Game::PlantAction() { for (int i=0; i<numOfLand_; i+=1) { if (map_[i].getStood()) { if(map_[i].getPlant()->doThing(player_,getPlantList()) == 0) cout << "You have get coin!" << endl; } } } void Game::ZombieAction() { for (int i=0; i<zombies_.size(); i+=1) { int ZcurrentPos = zombies_[i]->getPos(); zombies_[i]->setPos((ZcurrentPos+Move(3))%numOfLand_); if(map_[zombies_[i]->getPos()].getStood() && ! map_[zombies_[i]->getPos()].getPlant()->beAttacked(*zombies_[i]) ) { map_[zombies_[i]->getPos()].recycle(); } if (zombies_[i]->getHP()<=0) { zombies_.erase(zombies_.begin()+i); } } } <|endoftext|>
<commit_before>/** * Dynamically Loaded Object * (C) 2010 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/dyn_load.h> #include <botan/build.h> #if defined(BOTAN_TARGET_OS_HAS_DLOPEN) #include <dlfcn.h> #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY) #include <windows.h> #endif namespace Botan { namespace { void raise_runtime_loader_exception(const std::string& lib_name, const char* msg) { throw Exception("Failed to load " + lib_name + ": " + (msg ? msg : "Unknown error")); } } Dynamically_Loaded_Library::Dynamically_Loaded_Library( const std::string& library) : lib_name(library), lib(nullptr) { #if defined(BOTAN_TARGET_OS_HAS_DLOPEN) lib = ::dlopen(lib_name.c_str(), RTLD_LAZY); if(!lib) raise_runtime_loader_exception(lib_name, dlerror()); #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY) lib = ::LoadLibraryA(lib_name.c_str()); if(!lib) raise_runtime_loader_exception(lib_name, "LoadLibrary failed"); #endif if(!lib) raise_runtime_loader_exception(lib_name, "Dynamic load not supported"); } Dynamically_Loaded_Library::~Dynamically_Loaded_Library() { #if defined(BOTAN_TARGET_OS_HAS_DLOPEN) ::dlclose(lib); #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY) ::FreeLibrary((HMODULE)lib); #endif } void* Dynamically_Loaded_Library::resolve_symbol(const std::string& symbol) { void* addr = nullptr; #if defined(BOTAN_TARGET_OS_HAS_DLOPEN) addr = ::dlsym(lib, symbol.c_str()); #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY) addr = reinterpret_cast<void*>(::GetProcAddress((HMODULE)lib, symbol.c_str())); #endif if(!addr) throw Exception("Failed to resolve symbol " + symbol + " in " + lib_name); return addr; } } <commit_msg>Add missing include in dyn_load.cpp<commit_after>/** * Dynamically Loaded Object * (C) 2010 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/dyn_load.h> #include <botan/build.h> #include <botan/exceptn.h> #if defined(BOTAN_TARGET_OS_HAS_DLOPEN) #include <dlfcn.h> #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY) #include <windows.h> #endif namespace Botan { namespace { void raise_runtime_loader_exception(const std::string& lib_name, const char* msg) { throw Exception("Failed to load " + lib_name + ": " + (msg ? msg : "Unknown error")); } } Dynamically_Loaded_Library::Dynamically_Loaded_Library( const std::string& library) : lib_name(library), lib(nullptr) { #if defined(BOTAN_TARGET_OS_HAS_DLOPEN) lib = ::dlopen(lib_name.c_str(), RTLD_LAZY); if(!lib) raise_runtime_loader_exception(lib_name, dlerror()); #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY) lib = ::LoadLibraryA(lib_name.c_str()); if(!lib) raise_runtime_loader_exception(lib_name, "LoadLibrary failed"); #endif if(!lib) raise_runtime_loader_exception(lib_name, "Dynamic load not supported"); } Dynamically_Loaded_Library::~Dynamically_Loaded_Library() { #if defined(BOTAN_TARGET_OS_HAS_DLOPEN) ::dlclose(lib); #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY) ::FreeLibrary((HMODULE)lib); #endif } void* Dynamically_Loaded_Library::resolve_symbol(const std::string& symbol) { void* addr = nullptr; #if defined(BOTAN_TARGET_OS_HAS_DLOPEN) addr = ::dlsym(lib, symbol.c_str()); #elif defined(BOTAN_TARGET_OS_HAS_LOADLIBRARY) addr = reinterpret_cast<void*>(::GetProcAddress((HMODULE)lib, symbol.c_str())); #endif if(!addr) throw Exception("Failed to resolve symbol " + symbol + " in " + lib_name); return addr; } } <|endoftext|>
<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // 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 "openMVG/sfm/sfm_data_filters_frustum.hpp" #include "openMVG/cameras/Camera_Pinhole.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/image/pixel_types.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/stl/stl.hpp" #include "third_party/progress/progress_display.hpp" #include <fstream> #include <iomanip> #include <iterator> namespace openMVG { namespace sfm { using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::geometry::halfPlane; std::string RgbPLYString(const image::RGBColor& color); // Constructor Frustum_Filter::Frustum_Filter ( const SfM_Data & sfm_data, const double zNear, const double zFar, const NearFarPlanesT & z_near_z_far ) : z_near_z_far_perView(z_near_z_far) { //-- Init Z_Near & Z_Far for all valid views init_z_near_z_far_depth(sfm_data, zNear, zFar); const bool bComputed_Z = (zNear == -1. && zFar == -1.) && !sfm_data.structure.empty(); _bTruncated = (zNear != -1. && zFar != -1.) || bComputed_Z; initFrustum(sfm_data); } // Init a frustum for each valid views of the SfM scene void Frustum_Filter::initFrustum ( const SfM_Data & sfm_data ) { for (NearFarPlanesT::const_iterator it = z_near_z_far_perView.begin(); it != z_near_z_far_perView.end(); ++it) { const View * view = sfm_data.GetViews().at(it->first).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); if (!isPinhole(iterIntrinsic->second->getType())) continue; const Pose3 pose = sfm_data.GetPoseOrDie(view); const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(iterIntrinsic->second.get()); if (!cam) continue; if (!_bTruncated) // use infinite frustum { const Frustum f( cam->w(), cam->h(), cam->K(), pose.rotation(), pose.center()); frustum_perView[view->id_view] = f; } else // use truncated frustum with defined Near and Far planes { const Frustum f(cam->w(), cam->h(), cam->K(), pose.rotation(), pose.center(), it->second.first, it->second.second); frustum_perView[view->id_view] = f; } } } Pair_Set Frustum_Filter::getFrustumIntersectionPairs ( const std::vector<HalfPlaneObject>& bounding_volume ) const { Pair_Set pairs; // List active view Id std::vector<IndexT> viewIds; viewIds.reserve(z_near_z_far_perView.size()); std::transform(z_near_z_far_perView.cbegin(), z_near_z_far_perView.cend(), std::back_inserter(viewIds), stl::RetrieveKey()); C_Progress_display my_progress_bar( viewIds.size() * (viewIds.size()-1)/2, std::cout, "\nCompute frustum intersection\n"); // Exhaustive comparison (use the fact that the intersect function is symmetric) #ifdef OPENMVG_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < (int)viewIds.size(); ++i) { // Prepare vector of intersecting objects (within loop to keep it // thread-safe) std::vector<HalfPlaneObject> objects = bounding_volume; objects.insert(objects.end(), { frustum_perView.at(viewIds[i]), HalfPlaneObject() }); for (size_t j = i+1; j < viewIds.size(); ++j) { objects.back() = frustum_perView.at(viewIds[j]); if (intersect(objects)) { #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { pairs.insert({viewIds[i], viewIds[j]}); } } // Progress bar update ++my_progress_bar; } } return pairs; } // Export defined frustum in PLY file for viewing bool Frustum_Filter::export_Ply ( const std::string & filename, bool colorize ) const { std::ofstream of(filename.c_str()); if (!of.is_open()) return false; // Vertex count evaluation // Faces count evaluation size_t vertex_count = 0; size_t face_count = 0; for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { if (it->second.isInfinite()) { vertex_count += 5; face_count += 5; // 4 triangles + 1 quad } else // truncated { vertex_count += 8; face_count += 6; // 6 quads } } of << std::fixed << std::setprecision (std::numeric_limits<double>::digits10 + 1); of << "ply" << '\n' << "format ascii 1.0" << '\n' << "element vertex " << vertex_count << '\n' << "property double x" << '\n' << "property double y" << '\n' << "property double z" << '\n' << "element face " << face_count << '\n' << "property list uchar int vertex_index" << '\n'; if (colorize) { of << "property uchar red" << "\n" << "property uchar green" << "\n" << "property uchar blue" << "\n"; } of << "end_header" << '\n'; // Export frustums points for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { const std::vector<Vec3> & points = it->second.frustum_points(); for (size_t i=0; i < points.size(); ++i) of << points[i].transpose() << '\n'; } // Export frustums faces IndexT count = 0; std::string color_top_face = colorize ? RgbPLYString(image::RED) : ""; std::string color_other_face = colorize ? RgbPLYString(image::GRAY) : ""; for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { if (it->second.isInfinite()) // infinite frustum: drawn normalized cone: 4 faces { of << "3 " << count + 0 << ' ' << count + 1 << ' ' << count + 2 << color_other_face << '\n' << "3 " << count + 0 << ' ' << count + 2 << ' ' << count + 3 << color_other_face << '\n' << "3 " << count + 0 << ' ' << count + 3 << ' ' << count + 4 << color_top_face << '\n' << "3 " << count + 0 << ' ' << count + 4 << ' ' << count + 1 << color_other_face << '\n' << "4 " << count + 1 << ' ' << count + 2 << ' ' << count + 3 << ' ' << count + 4 << color_other_face << '\n'; count += 5; } else // truncated frustum: 6 faces { of << "4 " << count + 0 << ' ' << count + 1 << ' ' << count + 2 << ' ' << count + 3 << color_other_face << '\n' << "4 " << count + 0 << ' ' << count + 1 << ' ' << count + 5 << ' ' << count + 4 << color_other_face << '\n' << "4 " << count + 1 << ' ' << count + 5 << ' ' << count + 6 << ' ' << count + 2 << color_top_face << '\n' << "4 " << count + 3 << ' ' << count + 7 << ' ' << count + 6 << ' ' << count + 2 << color_other_face << '\n' << "4 " << count + 0 << ' ' << count + 4 << ' ' << count + 7 << ' ' << count + 3 << color_other_face << '\n' << "4 " << count + 4 << ' ' << count + 5 << ' ' << count + 6 << ' ' << count + 7 << color_other_face << '\n'; count += 8; } } of.flush(); const bool bOk = of.good(); of.close(); return bOk; } void Frustum_Filter::init_z_near_z_far_depth ( const SfM_Data & sfm_data, const double zNear, const double zFar ) { // If z_near & z_far are -1 and structure if not empty, // compute the values for each camera and the structure const bool bComputed_Z = (zNear == -1. && zFar == -1.) && !sfm_data.structure.empty(); if (bComputed_Z) // Compute the near & far planes from the structure and view observations { for (Landmarks::const_iterator itL = sfm_data.GetLandmarks().begin(); itL != sfm_data.GetLandmarks().end(); ++itL) { const Landmark & landmark = itL->second; const Vec3 & X = landmark.X; for (Observations::const_iterator iterO = landmark.obs.begin(); iterO != landmark.obs.end(); ++iterO) { const IndexT id_view = iterO->first; const View * view = sfm_data.GetViews().at(id_view).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; const Pose3 pose = sfm_data.GetPoseOrDie(view); const double z = Depth(pose.rotation(), pose.translation(), X); NearFarPlanesT::iterator itZ = z_near_z_far_perView.find(id_view); if (itZ != z_near_z_far_perView.end()) { if ( z < itZ->second.first) itZ->second.first = z; else if ( z > itZ->second.second) itZ->second.second = z; } else z_near_z_far_perView[id_view] = {z,z}; } } } else { // Init the same near & far limit for all the valid views for (Views::const_iterator it = sfm_data.GetViews().begin(); it != sfm_data.GetViews().end(); ++it) { const View * view = it->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; if (z_near_z_far_perView.find(view->id_view) == z_near_z_far_perView.end()) z_near_z_far_perView[view->id_view] = {zNear, zFar}; } } } std::string RgbPLYString(const image::RGBColor& color) { return ' ' + std::to_string(color.r()) + ' ' + std::to_string(color.g()) + ' ' + std::to_string(color.b()); } } // namespace sfm } // namespace openMVG <commit_msg>(FrustumFilter) Fix top face not being colored correctly (#1773)<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // 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 "openMVG/sfm/sfm_data_filters_frustum.hpp" #include "openMVG/cameras/Camera_Pinhole.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/image/pixel_types.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/stl/stl.hpp" #include "third_party/progress/progress_display.hpp" #include <fstream> #include <iomanip> #include <iterator> namespace openMVG { namespace sfm { using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::geometry::halfPlane; std::string RgbPLYString(const image::RGBColor& color); // Constructor Frustum_Filter::Frustum_Filter ( const SfM_Data & sfm_data, const double zNear, const double zFar, const NearFarPlanesT & z_near_z_far ) : z_near_z_far_perView(z_near_z_far) { //-- Init Z_Near & Z_Far for all valid views init_z_near_z_far_depth(sfm_data, zNear, zFar); const bool bComputed_Z = (zNear == -1. && zFar == -1.) && !sfm_data.structure.empty(); _bTruncated = (zNear != -1. && zFar != -1.) || bComputed_Z; initFrustum(sfm_data); } // Init a frustum for each valid views of the SfM scene void Frustum_Filter::initFrustum ( const SfM_Data & sfm_data ) { for (NearFarPlanesT::const_iterator it = z_near_z_far_perView.begin(); it != z_near_z_far_perView.end(); ++it) { const View * view = sfm_data.GetViews().at(it->first).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); if (!isPinhole(iterIntrinsic->second->getType())) continue; const Pose3 pose = sfm_data.GetPoseOrDie(view); const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(iterIntrinsic->second.get()); if (!cam) continue; if (!_bTruncated) // use infinite frustum { const Frustum f( cam->w(), cam->h(), cam->K(), pose.rotation(), pose.center()); frustum_perView[view->id_view] = f; } else // use truncated frustum with defined Near and Far planes { const Frustum f(cam->w(), cam->h(), cam->K(), pose.rotation(), pose.center(), it->second.first, it->second.second); frustum_perView[view->id_view] = f; } } } Pair_Set Frustum_Filter::getFrustumIntersectionPairs ( const std::vector<HalfPlaneObject>& bounding_volume ) const { Pair_Set pairs; // List active view Id std::vector<IndexT> viewIds; viewIds.reserve(z_near_z_far_perView.size()); std::transform(z_near_z_far_perView.cbegin(), z_near_z_far_perView.cend(), std::back_inserter(viewIds), stl::RetrieveKey()); C_Progress_display my_progress_bar( viewIds.size() * (viewIds.size()-1)/2, std::cout, "\nCompute frustum intersection\n"); // Exhaustive comparison (use the fact that the intersect function is symmetric) #ifdef OPENMVG_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < (int)viewIds.size(); ++i) { // Prepare vector of intersecting objects (within loop to keep it // thread-safe) std::vector<HalfPlaneObject> objects = bounding_volume; objects.insert(objects.end(), { frustum_perView.at(viewIds[i]), HalfPlaneObject() }); for (size_t j = i+1; j < viewIds.size(); ++j) { objects.back() = frustum_perView.at(viewIds[j]); if (intersect(objects)) { #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { pairs.insert({viewIds[i], viewIds[j]}); } } // Progress bar update ++my_progress_bar; } } return pairs; } // Export defined frustum in PLY file for viewing bool Frustum_Filter::export_Ply ( const std::string & filename, bool colorize ) const { std::ofstream of(filename.c_str()); if (!of.is_open()) return false; // Vertex count evaluation // Faces count evaluation size_t vertex_count = 0; size_t face_count = 0; for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { if (it->second.isInfinite()) { vertex_count += 5; face_count += 5; // 4 triangles + 1 quad } else // truncated { vertex_count += 8; face_count += 6; // 6 quads } } of << std::fixed << std::setprecision (std::numeric_limits<double>::digits10 + 1); of << "ply" << '\n' << "format ascii 1.0" << '\n' << "element vertex " << vertex_count << '\n' << "property double x" << '\n' << "property double y" << '\n' << "property double z" << '\n' << "element face " << face_count << '\n' << "property list uchar int vertex_index" << '\n'; if (colorize) { of << "property uchar red" << "\n" << "property uchar green" << "\n" << "property uchar blue" << "\n"; } of << "end_header" << '\n'; // Export frustums points for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { const std::vector<Vec3> & points = it->second.frustum_points(); for (size_t i=0; i < points.size(); ++i) of << points[i].transpose() << '\n'; } // Export frustums faces IndexT count = 0; std::string color_top_face = colorize ? RgbPLYString(image::RED) : ""; std::string color_other_face = colorize ? RgbPLYString(image::GRAY) : ""; for (FrustumsT::const_iterator it = frustum_perView.begin(); it != frustum_perView.end(); ++it) { if (it->second.isInfinite()) // infinite frustum: drawn normalized cone: 4 faces { of << "3 " << count + 0 << ' ' << count + 1 << ' ' << count + 2 << color_top_face << '\n' << "3 " << count + 0 << ' ' << count + 2 << ' ' << count + 3 << color_other_face << '\n' << "3 " << count + 0 << ' ' << count + 3 << ' ' << count + 4 << color_other_face << '\n' << "3 " << count + 0 << ' ' << count + 4 << ' ' << count + 1 << color_other_face << '\n' << "4 " << count + 1 << ' ' << count + 2 << ' ' << count + 3 << ' ' << count + 4 << color_other_face << '\n'; count += 5; } else // truncated frustum: 6 faces { of << "4 " << count + 0 << ' ' << count + 1 << ' ' << count + 2 << ' ' << count + 3 << color_other_face << '\n' << "4 " << count + 0 << ' ' << count + 1 << ' ' << count + 5 << ' ' << count + 4 << color_top_face << '\n' << "4 " << count + 1 << ' ' << count + 5 << ' ' << count + 6 << ' ' << count + 2 << color_other_face << '\n' << "4 " << count + 3 << ' ' << count + 7 << ' ' << count + 6 << ' ' << count + 2 << color_other_face << '\n' << "4 " << count + 0 << ' ' << count + 4 << ' ' << count + 7 << ' ' << count + 3 << color_other_face << '\n' << "4 " << count + 4 << ' ' << count + 5 << ' ' << count + 6 << ' ' << count + 7 << color_other_face << '\n'; count += 8; } } of.flush(); const bool bOk = of.good(); of.close(); return bOk; } void Frustum_Filter::init_z_near_z_far_depth ( const SfM_Data & sfm_data, const double zNear, const double zFar ) { // If z_near & z_far are -1 and structure if not empty, // compute the values for each camera and the structure const bool bComputed_Z = (zNear == -1. && zFar == -1.) && !sfm_data.structure.empty(); if (bComputed_Z) // Compute the near & far planes from the structure and view observations { for (Landmarks::const_iterator itL = sfm_data.GetLandmarks().begin(); itL != sfm_data.GetLandmarks().end(); ++itL) { const Landmark & landmark = itL->second; const Vec3 & X = landmark.X; for (Observations::const_iterator iterO = landmark.obs.begin(); iterO != landmark.obs.end(); ++iterO) { const IndexT id_view = iterO->first; const View * view = sfm_data.GetViews().at(id_view).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; const Pose3 pose = sfm_data.GetPoseOrDie(view); const double z = Depth(pose.rotation(), pose.translation(), X); NearFarPlanesT::iterator itZ = z_near_z_far_perView.find(id_view); if (itZ != z_near_z_far_perView.end()) { if ( z < itZ->second.first) itZ->second.first = z; else if ( z > itZ->second.second) itZ->second.second = z; } else z_near_z_far_perView[id_view] = {z,z}; } } } else { // Init the same near & far limit for all the valid views for (Views::const_iterator it = sfm_data.GetViews().begin(); it != sfm_data.GetViews().end(); ++it) { const View * view = it->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; if (z_near_z_far_perView.find(view->id_view) == z_near_z_far_perView.end()) z_near_z_far_perView[view->id_view] = {zNear, zFar}; } } } std::string RgbPLYString(const image::RGBColor& color) { return ' ' + std::to_string(color.r()) + ' ' + std::to_string(color.g()) + ' ' + std::to_string(color.b()); } } // namespace sfm } // namespace openMVG <|endoftext|>
<commit_before>// Copyright (c) 2011 libmv authors. // // 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. #define V3DLIB_ENABLE_SUITESPARSE 1 #include <map> #include "libmv/base/vector.h" #include "libmv/logging/logging.h" #include "libmv/multiview/fundamental.h" #include "libmv/multiview/projection.h" #include "libmv/numeric/numeric.h" #include "libmv/simple_pipeline/camera_intrinsics.h" #include "libmv/simple_pipeline/bundle.h" #include "libmv/simple_pipeline/reconstruction.h" #include "libmv/simple_pipeline/tracks.h" #include "third_party/ssba/Geometry/v3d_cameramatrix.h" #include "third_party/ssba/Geometry/v3d_metricbundle.h" #include "third_party/ssba/Math/v3d_linear.h" #include "third_party/ssba/Math/v3d_linear_utils.h" namespace libmv { void EuclideanBundle(const Tracks &tracks, EuclideanReconstruction *reconstruction) { CameraIntrinsics intrinsics; EuclideanBundleCommonIntrinsics(tracks, BUNDLE_NO_INTRINSICS, reconstruction, &intrinsics); } void EuclideanBundleCommonIntrinsics(const Tracks &tracks, int bundle_intrinsics, EuclideanReconstruction *reconstruction, CameraIntrinsics *intrinsics) { LG << "Original intrinsics: " << *intrinsics; vector<Marker> markers = tracks.AllMarkers(); // "index" in this context is the index that V3D's optimizer will see. The // V3D index must be dense in that the cameras are numbered 0...n-1, which is // not the case for the "image" numbering that arises from the tracks // structure. The complicated mapping is necessary to convert between the two // representations. std::map<EuclideanCamera *, int> camera_to_index; std::map<EuclideanPoint *, int> point_to_index; vector<EuclideanCamera *> index_to_camera; vector<EuclideanPoint *> index_to_point; int num_cameras = 0; int num_points = 0; for (int i = 0; i < markers.size(); ++i) { const Marker &marker = markers[i]; EuclideanCamera *camera = reconstruction->CameraForImage(marker.image); EuclideanPoint *point = reconstruction->PointForTrack(marker.track); if (camera && point) { if (camera_to_index.find(camera) == camera_to_index.end()) { camera_to_index[camera] = num_cameras; index_to_camera.push_back(camera); num_cameras++; } if (point_to_index.find(point) == point_to_index.end()) { point_to_index[point] = num_points; index_to_point.push_back(point); num_points++; } } } // Convert libmv's K matrix to V3d's K matrix. V3D::Matrix3x3d v3d_K; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { v3d_K[i][j] = intrinsics->K()(i, j); } } // Convert libmv's distortion to v3d distortion. V3D::StdDistortionFunction v3d_distortion; v3d_distortion.k1 = intrinsics->k1(); v3d_distortion.k2 = intrinsics->k2(); v3d_distortion.p1 = intrinsics->p1(); v3d_distortion.p2 = intrinsics->p2(); // Convert libmv's cameras to V3D's cameras. std::vector<V3D::CameraMatrix> v3d_cameras(index_to_camera.size()); for (int k = 0; k < index_to_camera.size(); ++k) { V3D::Matrix3x3d R; V3D::Vector3d t; // Libmv's rotation matrix type. const Mat3 &R_libmv = index_to_camera[k]->R; const Vec3 &t_libmv = index_to_camera[k]->t; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { R[i][j] = R_libmv(i, j); } t[i] = t_libmv(i); } v3d_cameras[k].setIntrinsic(v3d_K); v3d_cameras[k].setRotation(R); v3d_cameras[k].setTranslation(t); } LG << "Number of cameras: " << index_to_camera.size(); // Convert libmv's points to V3D's points. std::vector<V3D::Vector3d> v3d_points(index_to_point.size()); for (int i = 0; i < index_to_point.size(); i++) { v3d_points[i][0] = index_to_point[i]->X(0); v3d_points[i][1] = index_to_point[i]->X(1); v3d_points[i][2] = index_to_point[i]->X(2); } LG << "Number of points: " << index_to_point.size(); // Convert libmv's measurements to v3d measurements. int num_residuals = 0; std::vector<V3D::Vector2d> v3d_measurements; std::vector<int> v3d_camera_for_measurement; std::vector<int> v3d_point_for_measurement; for (int i = 0; i < markers.size(); ++i) { EuclideanCamera *camera = reconstruction->CameraForImage(markers[i].image); EuclideanPoint *point = reconstruction->PointForTrack(markers[i].track); if (!camera || !point) { continue; } V3D::Vector2d v3d_point; v3d_point[0] = markers[i].x; v3d_point[1] = markers[i].y; v3d_measurements.push_back(v3d_point); v3d_camera_for_measurement.push_back(camera_to_index[camera]); v3d_point_for_measurement.push_back(point_to_index[point]); num_residuals++; } LG << "Number of residuals: " << num_residuals; // Convert from libmv's specification for which intrinsics to bundle to V3D's. int v3d_bundle_intrinsics; if (bundle_intrinsics == BUNDLE_NO_INTRINSICS) { LG << "Bundling only camera positions."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_METRIC; } else if (bundle_intrinsics == BUNDLE_FOCAL_LENGTH) { LG << "Bundling f."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_FOCAL_LENGTH; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_PRINCIPAL_POINT)) { LG << "Bundling f, px, py."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_FOCAL_LENGTH_PP; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_PRINCIPAL_POINT | BUNDLE_RADIAL)) { LG << "Bundling f, px, py, k1, k2."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_RADIAL; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_PRINCIPAL_POINT | BUNDLE_RADIAL | BUNDLE_TANGENTIAL)) { LG << "Bundling f, px, py, k1, k2, p1, p2."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_RADIAL_TANGENTIAL; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_RADIAL | BUNDLE_TANGENTIAL)) { LG << "Bundling f, px, py, k1, k2, p1, p2."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_RADIAL_TANGENTIAL; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_RADIAL)) { LG << "Bundling f, k1, k2."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_FOCAL_AND_RADIAL; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_RADIAL_K1)) { LG << "Bundling f, k1."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_FOCAL_AND_RADIAL_K1; } else { LOG(FATAL) << "Unsupported bundle combination."; } // Ignore any outliers; assume supervised tracking. double v3d_inlier_threshold = 500000.0; // Finally, run the bundle adjustment. V3D::CommonInternalsMetricBundleOptimizer opt(v3d_bundle_intrinsics, v3d_inlier_threshold, v3d_K, v3d_distortion, v3d_cameras, v3d_points, v3d_measurements, v3d_camera_for_measurement, v3d_point_for_measurement); opt.maxIterations = 500; opt.minimize(); if (opt.status == V3D::LEVENBERG_OPTIMIZER_TIMEOUT) { LG << "Bundle status: Timed out."; } else if (opt.status == V3D::LEVENBERG_OPTIMIZER_SMALL_UPDATE) { LG << "Bundle status: Small update."; } else if (opt.status == V3D::LEVENBERG_OPTIMIZER_CONVERGED) { LG << "Bundle status: Converged."; } // Convert V3D's K matrix back to libmv's K matrix. Mat3 K; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { K(i, j) = v3d_K[i][j]; } } intrinsics->SetK(K); // Convert V3D's distortion back to libmv's distortion. intrinsics->SetRadialDistortion(v3d_distortion.k1, v3d_distortion.k2, 0.0); intrinsics->SetTangentialDistortion(v3d_distortion.p1, v3d_distortion.p2); // Convert V3D's cameras back to libmv's cameras. for (int k = 0; k < num_cameras; k++) { V3D::Matrix3x4d const Rt = v3d_cameras[k].getOrientation(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { index_to_camera[k]->R(i, j) = Rt[i][j]; } index_to_camera[k]->t(i) = Rt[i][3]; } } // Convert V3D's points back to libmv's points. for (int k = 0; k < num_points; k++) { for (int i = 0; i < 3; ++i) { index_to_point[k]->X(i) = v3d_points[k][i]; } } LG << "Final intrinsics: " << *intrinsics; } void ProjectiveBundle(const Tracks & /*tracks*/, ProjectiveReconstruction * /*reconstruction*/) { // TODO(keir): Implement this! This can't work until we have a better bundler // than SSBA, since SSBA has no support for projective bundling. } } // namespace libmv <commit_msg>Made V3D verbose again by default<commit_after>// Copyright (c) 2011 libmv authors. // // 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. #define V3DLIB_ENABLE_SUITESPARSE 1 #include <map> #include "libmv/base/vector.h" #include "libmv/logging/logging.h" #include "libmv/multiview/fundamental.h" #include "libmv/multiview/projection.h" #include "libmv/numeric/numeric.h" #include "libmv/simple_pipeline/camera_intrinsics.h" #include "libmv/simple_pipeline/bundle.h" #include "libmv/simple_pipeline/reconstruction.h" #include "libmv/simple_pipeline/tracks.h" #include "third_party/ssba/Geometry/v3d_cameramatrix.h" #include "third_party/ssba/Geometry/v3d_metricbundle.h" #include "third_party/ssba/Math/v3d_linear.h" #include "third_party/ssba/Math/v3d_linear_utils.h" namespace libmv { void EuclideanBundle(const Tracks &tracks, EuclideanReconstruction *reconstruction) { CameraIntrinsics intrinsics; EuclideanBundleCommonIntrinsics(tracks, BUNDLE_NO_INTRINSICS, reconstruction, &intrinsics); } void EuclideanBundleCommonIntrinsics(const Tracks &tracks, int bundle_intrinsics, EuclideanReconstruction *reconstruction, CameraIntrinsics *intrinsics) { LG << "Original intrinsics: " << *intrinsics; vector<Marker> markers = tracks.AllMarkers(); // "index" in this context is the index that V3D's optimizer will see. The // V3D index must be dense in that the cameras are numbered 0...n-1, which is // not the case for the "image" numbering that arises from the tracks // structure. The complicated mapping is necessary to convert between the two // representations. std::map<EuclideanCamera *, int> camera_to_index; std::map<EuclideanPoint *, int> point_to_index; vector<EuclideanCamera *> index_to_camera; vector<EuclideanPoint *> index_to_point; int num_cameras = 0; int num_points = 0; for (int i = 0; i < markers.size(); ++i) { const Marker &marker = markers[i]; EuclideanCamera *camera = reconstruction->CameraForImage(marker.image); EuclideanPoint *point = reconstruction->PointForTrack(marker.track); if (camera && point) { if (camera_to_index.find(camera) == camera_to_index.end()) { camera_to_index[camera] = num_cameras; index_to_camera.push_back(camera); num_cameras++; } if (point_to_index.find(point) == point_to_index.end()) { point_to_index[point] = num_points; index_to_point.push_back(point); num_points++; } } } // Convert libmv's K matrix to V3d's K matrix. V3D::Matrix3x3d v3d_K; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { v3d_K[i][j] = intrinsics->K()(i, j); } } // Convert libmv's distortion to v3d distortion. V3D::StdDistortionFunction v3d_distortion; v3d_distortion.k1 = intrinsics->k1(); v3d_distortion.k2 = intrinsics->k2(); v3d_distortion.p1 = intrinsics->p1(); v3d_distortion.p2 = intrinsics->p2(); // Convert libmv's cameras to V3D's cameras. std::vector<V3D::CameraMatrix> v3d_cameras(index_to_camera.size()); for (int k = 0; k < index_to_camera.size(); ++k) { V3D::Matrix3x3d R; V3D::Vector3d t; // Libmv's rotation matrix type. const Mat3 &R_libmv = index_to_camera[k]->R; const Vec3 &t_libmv = index_to_camera[k]->t; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { R[i][j] = R_libmv(i, j); } t[i] = t_libmv(i); } v3d_cameras[k].setIntrinsic(v3d_K); v3d_cameras[k].setRotation(R); v3d_cameras[k].setTranslation(t); } LG << "Number of cameras: " << index_to_camera.size(); // Convert libmv's points to V3D's points. std::vector<V3D::Vector3d> v3d_points(index_to_point.size()); for (int i = 0; i < index_to_point.size(); i++) { v3d_points[i][0] = index_to_point[i]->X(0); v3d_points[i][1] = index_to_point[i]->X(1); v3d_points[i][2] = index_to_point[i]->X(2); } LG << "Number of points: " << index_to_point.size(); // Convert libmv's measurements to v3d measurements. int num_residuals = 0; std::vector<V3D::Vector2d> v3d_measurements; std::vector<int> v3d_camera_for_measurement; std::vector<int> v3d_point_for_measurement; for (int i = 0; i < markers.size(); ++i) { EuclideanCamera *camera = reconstruction->CameraForImage(markers[i].image); EuclideanPoint *point = reconstruction->PointForTrack(markers[i].track); if (!camera || !point) { continue; } V3D::Vector2d v3d_point; v3d_point[0] = markers[i].x; v3d_point[1] = markers[i].y; v3d_measurements.push_back(v3d_point); v3d_camera_for_measurement.push_back(camera_to_index[camera]); v3d_point_for_measurement.push_back(point_to_index[point]); num_residuals++; } LG << "Number of residuals: " << num_residuals; // Convert from libmv's specification for which intrinsics to bundle to V3D's. int v3d_bundle_intrinsics; if (bundle_intrinsics == BUNDLE_NO_INTRINSICS) { LG << "Bundling only camera positions."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_METRIC; } else if (bundle_intrinsics == BUNDLE_FOCAL_LENGTH) { LG << "Bundling f."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_FOCAL_LENGTH; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_PRINCIPAL_POINT)) { LG << "Bundling f, px, py."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_FOCAL_LENGTH_PP; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_PRINCIPAL_POINT | BUNDLE_RADIAL)) { LG << "Bundling f, px, py, k1, k2."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_RADIAL; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_PRINCIPAL_POINT | BUNDLE_RADIAL | BUNDLE_TANGENTIAL)) { LG << "Bundling f, px, py, k1, k2, p1, p2."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_RADIAL_TANGENTIAL; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_RADIAL | BUNDLE_TANGENTIAL)) { LG << "Bundling f, px, py, k1, k2, p1, p2."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_RADIAL_TANGENTIAL; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_RADIAL)) { LG << "Bundling f, k1, k2."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_FOCAL_AND_RADIAL; } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH | BUNDLE_RADIAL_K1)) { LG << "Bundling f, k1."; v3d_bundle_intrinsics = V3D::FULL_BUNDLE_FOCAL_AND_RADIAL_K1; } else { LOG(FATAL) << "Unsupported bundle combination."; } // Ignore any outliers; assume supervised tracking. double v3d_inlier_threshold = 500000.0; // Finally, run the bundle adjustment. V3D::optimizerVerbosenessLevel = 1; V3D::CommonInternalsMetricBundleOptimizer opt(v3d_bundle_intrinsics, v3d_inlier_threshold, v3d_K, v3d_distortion, v3d_cameras, v3d_points, v3d_measurements, v3d_camera_for_measurement, v3d_point_for_measurement); opt.maxIterations = 500; opt.minimize(); if (opt.status == V3D::LEVENBERG_OPTIMIZER_TIMEOUT) { LG << "Bundle status: Timed out."; } else if (opt.status == V3D::LEVENBERG_OPTIMIZER_SMALL_UPDATE) { LG << "Bundle status: Small update."; } else if (opt.status == V3D::LEVENBERG_OPTIMIZER_CONVERGED) { LG << "Bundle status: Converged."; } // Convert V3D's K matrix back to libmv's K matrix. Mat3 K; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { K(i, j) = v3d_K[i][j]; } } intrinsics->SetK(K); // Convert V3D's distortion back to libmv's distortion. intrinsics->SetRadialDistortion(v3d_distortion.k1, v3d_distortion.k2, 0.0); intrinsics->SetTangentialDistortion(v3d_distortion.p1, v3d_distortion.p2); // Convert V3D's cameras back to libmv's cameras. for (int k = 0; k < num_cameras; k++) { V3D::Matrix3x4d const Rt = v3d_cameras[k].getOrientation(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { index_to_camera[k]->R(i, j) = Rt[i][j]; } index_to_camera[k]->t(i) = Rt[i][3]; } } // Convert V3D's points back to libmv's points. for (int k = 0; k < num_points; k++) { for (int i = 0; i < 3; ++i) { index_to_point[k]->X(i) = v3d_points[k][i]; } } LG << "Final intrinsics: " << *intrinsics; } void ProjectiveBundle(const Tracks & /*tracks*/, ProjectiveReconstruction * /*reconstruction*/) { // TODO(keir): Implement this! This can't work until we have a better bundler // than SSBA, since SSBA has no support for projective bundling. } } // namespace libmv <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of Qt Creator. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "sshconnection.h" #include "ne7sshobject.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QThread> #include <ne7ssh.h> #include <exception> namespace Core { namespace { class GenericSshConnection { Q_DECLARE_TR_FUNCTIONS(GenericSshConnection) public: GenericSshConnection(const SshServerInfo &server) : ssh(Internal::Ne7SshObject::instance()->get()), m_server(server), m_channel(-1) { } ~GenericSshConnection() { quit(); } bool start(bool shell) { Q_ASSERT(m_channel == -1); try { const QString *authString; int (ne7ssh::*connFunc)(const char *, int, const char *, const char *, bool, int); if (m_server.authType == SshServerInfo::AuthByPwd) { authString = &m_server.pwd; connFunc = &ne7ssh::connectWithPassword; } else { authString = &m_server.privateKeyFile; connFunc = &ne7ssh::connectWithKey; } m_channel = (ssh.data()->*connFunc)(m_server.host.toLatin1(), m_server.port, m_server.uname.toAscii(), authString->toLatin1(), shell, m_server.timeout); if (m_channel == -1) { setError(tr("Could not connect to host."), false); return false; } } catch (const std::exception &e) { // Should in theory not be necessary, but Net7 leaks Botan exceptions. setError(tr("Error in cryptography backend: %1") .arg(QLatin1String(e.what())), false); return false; } return true; } void quit() { const int channel = m_channel; if (channel != -1) { m_channel = -1; if (!ssh->close(channel)) qWarning("%s: close() failed.", Q_FUNC_INFO); } } bool hasError() const { return !m_error.isEmpty(); } QString error() const { return m_error; } int channel() const { return m_channel; } QString lastNe7Error() { return ssh->errors()->pop(channel()); } const SshServerInfo &server() { return m_server; } void setError(const QString error, bool appendNe7ErrMsg) { m_error = error; if (appendNe7ErrMsg) m_error += QLatin1String(": ") + lastNe7Error(); } QSharedPointer<ne7ssh> ssh; private: const SshServerInfo m_server; QString m_error; int m_channel; }; char *alloc(size_t n) { return new char[n]; } } // anonymous namespace namespace Internal { struct InteractiveSshConnectionPrivate { InteractiveSshConnectionPrivate(const SshServerInfo &server) : conn(server), outputReader(0) {} GenericSshConnection conn; ConnectionOutputReader *outputReader; }; struct NonInteractiveSshConnectionPrivate { NonInteractiveSshConnectionPrivate(const SshServerInfo &server) : conn(server) {} GenericSshConnection conn; Ne7SftpSubsystem sftp; }; class ConnectionOutputReader : public QThread { public: ConnectionOutputReader(InteractiveSshConnection *parent) : QThread(parent), m_conn(parent), m_stopRequested(false) {} ~ConnectionOutputReader() { stop(); wait(); } // TODO: Use a wakeup mechanism here as soon as we no longer poll for output // from Net7. void stop() { m_stopRequested = true; } private: virtual void run() { while (!m_stopRequested) { const int channel = m_conn->d->conn.channel(); if (channel != -1) { QScopedPointer<char, QScopedPointerArrayDeleter<char> > output(m_conn->d->conn.ssh->readAndReset(channel, alloc)); if (output) emit m_conn->remoteOutput(QByteArray(output.data())); } sleep(1); // TODO: Hack Net7 to enable wait() functionality. } } InteractiveSshConnection *m_conn; bool m_stopRequested; }; } // namespace Internal InteractiveSshConnection::InteractiveSshConnection(const SshServerInfo &server) : d(new Internal::InteractiveSshConnectionPrivate(server)) { d->outputReader = new Internal::ConnectionOutputReader(this); } InteractiveSshConnection::~InteractiveSshConnection() { d->conn.ssh->send("exit\n", d->conn.channel()); quit(); delete d; } bool InteractiveSshConnection::start() { if (!d->conn.start(true)) return false; d->outputReader->start(); return true; } bool InteractiveSshConnection::sendInput(const QByteArray &input) { if (!d->conn.ssh->send(input.data(), d->conn.channel())) { d->conn.setError(tr("Error sending input"), true); return false; } return true; } void InteractiveSshConnection::quit() { d->outputReader->stop(); d->conn.quit(); } InteractiveSshConnection::Ptr InteractiveSshConnection::create(const SshServerInfo &server) { return Ptr(new InteractiveSshConnection(server)); } bool InteractiveSshConnection::hasError() const { return d->conn.hasError(); } QString InteractiveSshConnection::error() const { return d->conn.error(); } namespace { class FileMgr { public: FileMgr(const QString &filePath, const char *mode) : m_file(fopen(filePath.toLatin1().data(), mode)) {} ~FileMgr() { if (m_file) fclose(m_file); } FILE *file() const { return m_file; } private: FILE * const m_file; }; } // Anonymous namespace SftpConnection::SftpConnection(const SshServerInfo &server) : d(new Internal::NonInteractiveSshConnectionPrivate(server)) { } SftpConnection::~SftpConnection() { quit(); delete d; } bool SftpConnection::start() { if (!d->conn.start(false)) return false; if (!d->conn.ssh->initSftp(d->sftp, d->conn.channel()) || !d->sftp.setTimeout(d->conn.server().timeout)) { d->conn.setError(tr("Error setting up SFTP subsystem"), true); return false; } return true; } bool SftpConnection::transferFiles(const QList<SftpTransferInfo> &transferList) { for (int i = 0; i < transferList.count(); ++i) { const SftpTransferInfo &transfer = transferList.at(i); bool success; if (transfer.type == SftpTransferInfo::Upload) { success = upload(transfer.localFilePath, transfer.remoteFilePath); } else { success = download(transfer.remoteFilePath, transfer.localFilePath); } if (!success) return false; } return true; } bool SftpConnection::upload(const QString &localFilePath, const QByteArray &remoteFilePath) { FileMgr fileMgr(localFilePath, "rb"); if (!fileMgr.file()) { d->conn.setError(tr("Could not open file '%1'").arg(localFilePath), false); return false; } if (!d->sftp.put(fileMgr.file(), remoteFilePath.data())) { d->conn.setError(tr("Could not uplodad file '%1'") .arg(localFilePath), true); return false; } emit fileCopied(localFilePath); return true; } bool SftpConnection::download(const QByteArray &remoteFilePath, const QString &localFilePath) { FileMgr fileMgr(localFilePath, "wb"); if (!fileMgr.file()) { d->conn.setError(tr("Could not open file '%1'").arg(localFilePath), false); return false; } if (!d->sftp.get(remoteFilePath.data(), fileMgr.file())) { d->conn.setError(tr("Could not copy remote file '%1' to local file '%2'") .arg(remoteFilePath, localFilePath), false); return false; } emit fileCopied(remoteFilePath); return true; } bool SftpConnection::createRemoteDir(const QByteArray &remoteDir) { if (!d->sftp.mkdir(remoteDir.data())) { d->conn.setError(tr("Could not create remote directory"), true); return false; } return true; } bool SftpConnection::removeRemoteDir(const QByteArray &remoteDir) { if (!d->sftp.rmdir(remoteDir.data())) { d->conn.setError(tr("Could not remove remote directory"), true); return false; } return true; } QByteArray SftpConnection::listRemoteDirContents(const QByteArray &remoteDir, bool withAttributes, bool &ok) { const char * const buffer = d->sftp.ls(remoteDir.data(), withAttributes); if (!buffer) { d->conn.setError(tr("Could not get remote directory contents"), true); ok = false; return QByteArray(); } ok = true; return QByteArray(buffer); } bool SftpConnection::removeRemoteFile(const QByteArray &remoteFile) { if (!d->sftp.rm(remoteFile.data())) { d->conn.setError(tr("Could not remove remote file"), true); return false; } return true; } bool SftpConnection::changeRemoteWorkingDir(const QByteArray &newRemoteDir) { if (!d->sftp.cd(newRemoteDir.data())) { d->conn.setError(tr("Could not change remote working directory"), true); return false; } return true; } void SftpConnection::quit() { d->conn.quit(); } bool SftpConnection::hasError() const { return d->conn.hasError(); } QString SftpConnection::error() const { return d->conn.error(); } SftpConnection::Ptr SftpConnection::create(const SshServerInfo &server) { return Ptr(new SftpConnection(server)); } } // namespace Core <commit_msg>SSH: Increase poll frequency.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of Qt Creator. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "sshconnection.h" #include "ne7sshobject.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QThread> #include <ne7ssh.h> #include <exception> namespace Core { namespace { class GenericSshConnection { Q_DECLARE_TR_FUNCTIONS(GenericSshConnection) public: GenericSshConnection(const SshServerInfo &server) : ssh(Internal::Ne7SshObject::instance()->get()), m_server(server), m_channel(-1) { } ~GenericSshConnection() { quit(); } bool start(bool shell) { Q_ASSERT(m_channel == -1); try { const QString *authString; int (ne7ssh::*connFunc)(const char *, int, const char *, const char *, bool, int); if (m_server.authType == SshServerInfo::AuthByPwd) { authString = &m_server.pwd; connFunc = &ne7ssh::connectWithPassword; } else { authString = &m_server.privateKeyFile; connFunc = &ne7ssh::connectWithKey; } m_channel = (ssh.data()->*connFunc)(m_server.host.toLatin1(), m_server.port, m_server.uname.toAscii(), authString->toLatin1(), shell, m_server.timeout); if (m_channel == -1) { setError(tr("Could not connect to host."), false); return false; } } catch (const std::exception &e) { // Should in theory not be necessary, but Net7 leaks Botan exceptions. setError(tr("Error in cryptography backend: %1") .arg(QLatin1String(e.what())), false); return false; } return true; } void quit() { const int channel = m_channel; if (channel != -1) { m_channel = -1; if (!ssh->close(channel)) qWarning("%s: close() failed.", Q_FUNC_INFO); } } bool hasError() const { return !m_error.isEmpty(); } QString error() const { return m_error; } int channel() const { return m_channel; } QString lastNe7Error() { return ssh->errors()->pop(channel()); } const SshServerInfo &server() { return m_server; } void setError(const QString error, bool appendNe7ErrMsg) { m_error = error; if (appendNe7ErrMsg) m_error += QLatin1String(": ") + lastNe7Error(); } QSharedPointer<ne7ssh> ssh; private: const SshServerInfo m_server; QString m_error; int m_channel; }; char *alloc(size_t n) { return new char[n]; } } // anonymous namespace namespace Internal { struct InteractiveSshConnectionPrivate { InteractiveSshConnectionPrivate(const SshServerInfo &server) : conn(server), outputReader(0) {} GenericSshConnection conn; ConnectionOutputReader *outputReader; }; struct NonInteractiveSshConnectionPrivate { NonInteractiveSshConnectionPrivate(const SshServerInfo &server) : conn(server) {} GenericSshConnection conn; Ne7SftpSubsystem sftp; }; class ConnectionOutputReader : public QThread { public: ConnectionOutputReader(InteractiveSshConnection *parent) : QThread(parent), m_conn(parent), m_stopRequested(false) {} ~ConnectionOutputReader() { stop(); wait(); } // TODO: Use a wakeup mechanism here as soon as we no longer poll for output // from Net7. void stop() { m_stopRequested = true; } private: virtual void run() { while (!m_stopRequested) { const int channel = m_conn->d->conn.channel(); if (channel != -1) { QScopedPointer<char, QScopedPointerArrayDeleter<char> > output(m_conn->d->conn.ssh->readAndReset(channel, alloc)); if (output) emit m_conn->remoteOutput(QByteArray(output.data())); } usleep(100000); // TODO: Hack Net7 to enable wait() functionality. } } InteractiveSshConnection *m_conn; bool m_stopRequested; }; } // namespace Internal InteractiveSshConnection::InteractiveSshConnection(const SshServerInfo &server) : d(new Internal::InteractiveSshConnectionPrivate(server)) { d->outputReader = new Internal::ConnectionOutputReader(this); } InteractiveSshConnection::~InteractiveSshConnection() { d->conn.ssh->send("exit\n", d->conn.channel()); quit(); delete d; } bool InteractiveSshConnection::start() { if (!d->conn.start(true)) return false; d->outputReader->start(); return true; } bool InteractiveSshConnection::sendInput(const QByteArray &input) { if (!d->conn.ssh->send(input.data(), d->conn.channel())) { d->conn.setError(tr("Error sending input"), true); return false; } return true; } void InteractiveSshConnection::quit() { d->outputReader->stop(); d->conn.quit(); } InteractiveSshConnection::Ptr InteractiveSshConnection::create(const SshServerInfo &server) { return Ptr(new InteractiveSshConnection(server)); } bool InteractiveSshConnection::hasError() const { return d->conn.hasError(); } QString InteractiveSshConnection::error() const { return d->conn.error(); } namespace { class FileMgr { public: FileMgr(const QString &filePath, const char *mode) : m_file(fopen(filePath.toLatin1().data(), mode)) {} ~FileMgr() { if (m_file) fclose(m_file); } FILE *file() const { return m_file; } private: FILE * const m_file; }; } // Anonymous namespace SftpConnection::SftpConnection(const SshServerInfo &server) : d(new Internal::NonInteractiveSshConnectionPrivate(server)) { } SftpConnection::~SftpConnection() { quit(); delete d; } bool SftpConnection::start() { if (!d->conn.start(false)) return false; if (!d->conn.ssh->initSftp(d->sftp, d->conn.channel()) || !d->sftp.setTimeout(d->conn.server().timeout)) { d->conn.setError(tr("Error setting up SFTP subsystem"), true); return false; } return true; } bool SftpConnection::transferFiles(const QList<SftpTransferInfo> &transferList) { for (int i = 0; i < transferList.count(); ++i) { const SftpTransferInfo &transfer = transferList.at(i); bool success; if (transfer.type == SftpTransferInfo::Upload) { success = upload(transfer.localFilePath, transfer.remoteFilePath); } else { success = download(transfer.remoteFilePath, transfer.localFilePath); } if (!success) return false; } return true; } bool SftpConnection::upload(const QString &localFilePath, const QByteArray &remoteFilePath) { FileMgr fileMgr(localFilePath, "rb"); if (!fileMgr.file()) { d->conn.setError(tr("Could not open file '%1'").arg(localFilePath), false); return false; } if (!d->sftp.put(fileMgr.file(), remoteFilePath.data())) { d->conn.setError(tr("Could not uplodad file '%1'") .arg(localFilePath), true); return false; } emit fileCopied(localFilePath); return true; } bool SftpConnection::download(const QByteArray &remoteFilePath, const QString &localFilePath) { FileMgr fileMgr(localFilePath, "wb"); if (!fileMgr.file()) { d->conn.setError(tr("Could not open file '%1'").arg(localFilePath), false); return false; } if (!d->sftp.get(remoteFilePath.data(), fileMgr.file())) { d->conn.setError(tr("Could not copy remote file '%1' to local file '%2'") .arg(remoteFilePath, localFilePath), false); return false; } emit fileCopied(remoteFilePath); return true; } bool SftpConnection::createRemoteDir(const QByteArray &remoteDir) { if (!d->sftp.mkdir(remoteDir.data())) { d->conn.setError(tr("Could not create remote directory"), true); return false; } return true; } bool SftpConnection::removeRemoteDir(const QByteArray &remoteDir) { if (!d->sftp.rmdir(remoteDir.data())) { d->conn.setError(tr("Could not remove remote directory"), true); return false; } return true; } QByteArray SftpConnection::listRemoteDirContents(const QByteArray &remoteDir, bool withAttributes, bool &ok) { const char * const buffer = d->sftp.ls(remoteDir.data(), withAttributes); if (!buffer) { d->conn.setError(tr("Could not get remote directory contents"), true); ok = false; return QByteArray(); } ok = true; return QByteArray(buffer); } bool SftpConnection::removeRemoteFile(const QByteArray &remoteFile) { if (!d->sftp.rm(remoteFile.data())) { d->conn.setError(tr("Could not remove remote file"), true); return false; } return true; } bool SftpConnection::changeRemoteWorkingDir(const QByteArray &newRemoteDir) { if (!d->sftp.cd(newRemoteDir.data())) { d->conn.setError(tr("Could not change remote working directory"), true); return false; } return true; } void SftpConnection::quit() { d->conn.quit(); } bool SftpConnection::hasError() const { return d->conn.hasError(); } QString SftpConnection::error() const { return d->conn.error(); } SftpConnection::Ptr SftpConnection::create(const SshServerInfo &server) { return Ptr(new SftpConnection(server)); } } // namespace Core <|endoftext|>
<commit_before>#include "NoJoystickState.h" #include <iostream> const std::string NoJoystickState::s_menuID = "NO_JOYSTICK"; void NoJoystickState::update() { // nothing for now } void NoJoystickState::render() { // nothing for now } bool NoJoystickState::onEnter() { std::cout << "entering NoJoystickState\n"; return true; } bool NoJoystickState::onExit() { std::cout << "exiting NoJoystickState\n"; return true; } std::string NoJoystickState::getStateID() const { return s_menuID; } <commit_msg>leave the NoJoystickState when the joysticks are initialised<commit_after>#include "NoJoystickState.h" #include "Game.h" #include "InputHandler.h" #include <iostream> const std::string NoJoystickState::s_menuID = "NO_JOYSTICK"; void NoJoystickState::update() { if (InputHandler::Instance()->joysticksInitialised()) { Game::Instance()->getStateMachine()->popState(); } } void NoJoystickState::render() { // nothing for now } bool NoJoystickState::onEnter() { std::cout << "entering NoJoystickState\n"; return true; } bool NoJoystickState::onExit() { std::cout << "exiting NoJoystickState\n"; return true; } std::string NoJoystickState::getStateID() const { return s_menuID; } <|endoftext|>
<commit_before>// stl includes #include <exception> #include <cstring> // Local Hyperion includes #include "LedDeviceLightpack.h" // from USB_ID.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/USB_ID.h) #define USB_OLD_VENDOR_ID 0x03EB #define USB_OLD_PRODUCT_ID 0x204F #define USB_VENDOR_ID 0x1D50 #define USB_PRODUCT_ID 0x6022 #define LIGHTPACK_INTERFACE 0 // from commands.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/commands.h) // Commands to device, sends it in first byte of data[] enum COMMANDS{ CMD_UPDATE_LEDS = 1, CMD_OFF_ALL, CMD_SET_TIMER_OPTIONS, CMD_SET_PWM_LEVEL_MAX_VALUE, /* deprecated */ CMD_SET_SMOOTH_SLOWDOWN, CMD_SET_BRIGHTNESS, CMD_NOP = 0x0F }; // from commands.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/commands.h) enum DATA_VERSION_INDEXES{ INDEX_FW_VER_MAJOR = 1, INDEX_FW_VER_MINOR }; LedDeviceLightpack::LedDeviceLightpack(const std::string &serialNumber) : LedDevice(), _libusbContext(nullptr), _deviceHandle(nullptr), _busNumber(-1), _addressNumber(-1), _serialNumber(serialNumber), _firmwareVersion({-1,-1}), _ledCount(-1), _bitsPerChannel(-1), _ledBuffer() { } LedDeviceLightpack::~LedDeviceLightpack() { if (_deviceHandle != nullptr) { libusb_release_interface(_deviceHandle, LIGHTPACK_INTERFACE); libusb_attach_kernel_driver(_deviceHandle, LIGHTPACK_INTERFACE); libusb_close(_deviceHandle); _deviceHandle = nullptr; } if (_libusbContext != nullptr) { libusb_exit(_libusbContext); _libusbContext = nullptr; } } int LedDeviceLightpack::open() { int error; // initialize the usb context if ((error = libusb_init(&_libusbContext)) != LIBUSB_SUCCESS) { std::cerr << "Error while initializing USB context(" << error << "): " << libusb_error_name(error) << std::endl; _libusbContext = nullptr; return -1; } std::cout << "USB context initialized" << std::endl; // retrieve the list of usb devices libusb_device ** deviceList; ssize_t deviceCount = libusb_get_device_list(_libusbContext, &deviceList); // iterate the list of devices for (ssize_t i = 0 ; i < deviceCount; ++i) { libusb_device_descriptor deviceDescriptor; error = libusb_get_device_descriptor(deviceList[i], &deviceDescriptor); if (error != LIBUSB_SUCCESS) { std::cerr << "Error while retrieving device descriptor(" << error << "): " << libusb_error_name(error) << std::endl; // continue with next usb device continue; } if ((deviceDescriptor.idVendor == USB_VENDOR_ID && deviceDescriptor.idProduct == USB_PRODUCT_ID) || (deviceDescriptor.idVendor == USB_OLD_VENDOR_ID && deviceDescriptor.idProduct == USB_OLD_PRODUCT_ID)) { // get the hardware address int busNumber = libusb_get_bus_number(deviceList[i]); int addressNumber = libusb_get_device_address(deviceList[i]); // get the serial number std::string serialNumber; if (deviceDescriptor.iSerialNumber != 0) { try { serialNumber = LedDeviceLightpack::getString(deviceList[i], deviceDescriptor.iSerialNumber); } catch (int e) { std::cerr << "unable to retrieve serial number from Lightpack device(" << e << "): " << libusb_error_name(e) << std::endl; } } // get the firmware version Version version = {-1,-1}; try { version = LedDeviceLightpack::getVersion(deviceList[i]); } catch (int e) { std::cerr << "unable to retrieve firmware version number from Lightpack device(" << e << "): " << libusb_error_name(e) << std::endl; } std::cout << "Lightpack device found: bus=" << busNumber << " address=" << addressNumber << " serial=" << serialNumber << " version=" << version.majorVersion << "." << version.minorVersion << std::endl; // check if this is the device we are looking for if (_serialNumber.empty() || _serialNumber == serialNumber) { // This is it! try { _deviceHandle = openDevice(deviceList[i]); _serialNumber = serialNumber; _busNumber = busNumber; _addressNumber = addressNumber; std::cout << "Lightpack device successfully opened" << std::endl; // break from the search loop break; } catch(int e) { std::cerr << "unable to retrieve open Lightpack device(" << e << "): " << libusb_error_name(e) << std::endl; } } } } // free the device list libusb_free_device_list(deviceList, 1); if (_deviceHandle != nullptr) { // FOR TESTING PURPOSE: FORCE MAJOR VERSION TO 6 _firmwareVersion.majorVersion = 6; // disable smoothing of the chosen device disableSmoothing(); // determine the number of leds if (_firmwareVersion.majorVersion == 4) { _ledCount = 8; } else { _ledCount = 10; } // determine the bits per channel if (_firmwareVersion.majorVersion == 6) { // maybe also or version 7? The firmware suggest this is only for 6... (2013-11-13) _bitsPerChannel = 12; } else { _bitsPerChannel = 8; } // set the led buffer size (command + 6 bytes per led) _ledBuffer.resize(1 + _ledCount * 6, 0); _ledBuffer[0] = CMD_UPDATE_LEDS; } return _deviceHandle == nullptr ? -1 : 0; } int LedDeviceLightpack::write(const std::vector<ColorRgb> &ledValues) { int count = std::min(_ledCount, (int) ledValues.size()); for (int i = 0; i < count ; ++i) { const ColorRgb & color = ledValues[i]; // copy the most significant bits of the rgb values to the first three bytes // offset 1 to accomodate for the command byte _ledBuffer[6*i+1] = color.red; _ledBuffer[6*i+2] = color.green; _ledBuffer[6*i+3] = color.blue; // leave the next three bytes on zero... // 12-bit values have zeros in the lowest 4 bits which is almost correct, but it saves extra // switches to determine what to do and some bit shuffling } return writeBytes(_ledBuffer.data(), _ledBuffer.size()); } int LedDeviceLightpack::switchOff() { unsigned char buf[1] = {CMD_OFF_ALL}; return writeBytes(buf, sizeof(buf)) == sizeof(buf); } int LedDeviceLightpack::writeBytes(uint8_t *data, int size) { return libusb_control_transfer(_deviceHandle, LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0x09, (2 << 8), 0x00, data, size, 100); } int LedDeviceLightpack::disableSmoothing() { unsigned char buf[2] = {CMD_SET_SMOOTH_SLOWDOWN, 0}; return writeBytes(buf, sizeof(buf)) == sizeof(buf); } libusb_device_handle * LedDeviceLightpack::openDevice(libusb_device *device) { libusb_device_handle * handle = nullptr; int error = libusb_open(device, &handle); if (error != LIBUSB_SUCCESS) { throw error; } error = libusb_detach_kernel_driver(handle, LIGHTPACK_INTERFACE); if (error != LIBUSB_SUCCESS) { throw error; } error = libusb_claim_interface(handle, LIGHTPACK_INTERFACE); if (error != LIBUSB_SUCCESS) { throw error; } return handle; } std::string LedDeviceLightpack::getString(libusb_device * device, int stringDescriptorIndex) { libusb_device_handle * deviceHandle = openDevice(device); char buffer[256]; int error = libusb_get_string_descriptor_ascii(deviceHandle, stringDescriptorIndex, reinterpret_cast<unsigned char *>(buffer), sizeof(buffer)); if (error <= 0) { throw error; } libusb_close(deviceHandle); return std::string(buffer, error); } LedDeviceLightpack::Version LedDeviceLightpack::getVersion(libusb_device *device) { libusb_device_handle * deviceHandle = openDevice(device); uint8_t buffer[256]; int error = libusb_get_descriptor(deviceHandle, LIBUSB_DT_REPORT, 0, buffer, sizeof(buffer)); if (error <= 3) { throw error; } libusb_close(deviceHandle); return Version{buffer[INDEX_FW_VER_MAJOR], buffer[INDEX_FW_VER_MINOR]}; } <commit_msg>Code formatting and comments<commit_after>// stl includes #include <exception> #include <cstring> // Local Hyperion includes #include "LedDeviceLightpack.h" // from USB_ID.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/USB_ID.h) #define USB_OLD_VENDOR_ID 0x03EB #define USB_OLD_PRODUCT_ID 0x204F #define USB_VENDOR_ID 0x1D50 #define USB_PRODUCT_ID 0x6022 #define LIGHTPACK_INTERFACE 0 // from commands.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/commands.h) // Commands to device, sends it in first byte of data[] enum COMMANDS{ CMD_UPDATE_LEDS = 1, CMD_OFF_ALL, CMD_SET_TIMER_OPTIONS, CMD_SET_PWM_LEVEL_MAX_VALUE, /* deprecated */ CMD_SET_SMOOTH_SLOWDOWN, CMD_SET_BRIGHTNESS, CMD_NOP = 0x0F }; // from commands.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/commands.h) enum DATA_VERSION_INDEXES{ INDEX_FW_VER_MAJOR = 1, INDEX_FW_VER_MINOR }; LedDeviceLightpack::LedDeviceLightpack(const std::string &serialNumber) : LedDevice(), _libusbContext(nullptr), _deviceHandle(nullptr), _busNumber(-1), _addressNumber(-1), _serialNumber(serialNumber), _firmwareVersion({-1,-1}), _ledCount(-1), _bitsPerChannel(-1), _ledBuffer() { } LedDeviceLightpack::~LedDeviceLightpack() { if (_deviceHandle != nullptr) { libusb_release_interface(_deviceHandle, LIGHTPACK_INTERFACE); libusb_attach_kernel_driver(_deviceHandle, LIGHTPACK_INTERFACE); libusb_close(_deviceHandle); _deviceHandle = nullptr; } if (_libusbContext != nullptr) { libusb_exit(_libusbContext); _libusbContext = nullptr; } } int LedDeviceLightpack::open() { int error; // initialize the usb context if ((error = libusb_init(&_libusbContext)) != LIBUSB_SUCCESS) { std::cerr << "Error while initializing USB context(" << error << "): " << libusb_error_name(error) << std::endl; _libusbContext = nullptr; return -1; } std::cout << "USB context initialized" << std::endl; // retrieve the list of usb devices libusb_device ** deviceList; ssize_t deviceCount = libusb_get_device_list(_libusbContext, &deviceList); // iterate the list of devices for (ssize_t i = 0 ; i < deviceCount; ++i) { libusb_device_descriptor deviceDescriptor; error = libusb_get_device_descriptor(deviceList[i], &deviceDescriptor); if (error != LIBUSB_SUCCESS) { std::cerr << "Error while retrieving device descriptor(" << error << "): " << libusb_error_name(error) << std::endl; // continue with next usb device continue; } if ((deviceDescriptor.idVendor == USB_VENDOR_ID && deviceDescriptor.idProduct == USB_PRODUCT_ID) || (deviceDescriptor.idVendor == USB_OLD_VENDOR_ID && deviceDescriptor.idProduct == USB_OLD_PRODUCT_ID)) { // get the hardware address int busNumber = libusb_get_bus_number(deviceList[i]); int addressNumber = libusb_get_device_address(deviceList[i]); // get the serial number std::string serialNumber; if (deviceDescriptor.iSerialNumber != 0) { try { serialNumber = LedDeviceLightpack::getString(deviceList[i], deviceDescriptor.iSerialNumber); } catch (int e) { std::cerr << "unable to retrieve serial number from Lightpack device(" << e << "): " << libusb_error_name(e) << std::endl; } } // get the firmware version Version version = {-1,-1}; try { version = LedDeviceLightpack::getVersion(deviceList[i]); } catch (int e) { std::cerr << "unable to retrieve firmware version number from Lightpack device(" << e << "): " << libusb_error_name(e) << std::endl; } std::cout << "Lightpack device found: bus=" << busNumber << " address=" << addressNumber << " serial=" << serialNumber << " version=" << version.majorVersion << "." << version.minorVersion << std::endl; // check if this is the device we are looking for if (_serialNumber.empty() || _serialNumber == serialNumber) { // This is it! try { _deviceHandle = openDevice(deviceList[i]); _serialNumber = serialNumber; _busNumber = busNumber; _addressNumber = addressNumber; std::cout << "Lightpack device successfully opened" << std::endl; // break from the search loop break; } catch(int e) { std::cerr << "unable to retrieve open Lightpack device(" << e << "): " << libusb_error_name(e) << std::endl; } } } } // free the device list libusb_free_device_list(deviceList, 1); if (_deviceHandle != nullptr) { // FOR TESTING PURPOSE: FORCE MAJOR VERSION TO 6 _firmwareVersion.majorVersion = 6; // disable smoothing of the chosen device disableSmoothing(); // determine the number of leds if (_firmwareVersion.majorVersion == 4) { _ledCount = 8; } else { _ledCount = 10; } // determine the bits per channel if (_firmwareVersion.majorVersion == 6) { // maybe also or version 7? The firmware suggest this is only for 6... (2013-11-13) _bitsPerChannel = 12; } else { _bitsPerChannel = 8; } // set the led buffer size (command + 6 bytes per led) _ledBuffer = std::vector<uint8_t>(1 + _ledCount * 6, 0); _ledBuffer[0] = CMD_UPDATE_LEDS; } return _deviceHandle == nullptr ? -1 : 0; } int LedDeviceLightpack::write(const std::vector<ColorRgb> &ledValues) { int count = std::min(_ledCount, (int) ledValues.size()); for (int i = 0; i < count ; ++i) { const ColorRgb & color = ledValues[i]; // copy the most significant bits of the rgb values to the first three bytes // offset 1 to accomodate for the command byte _ledBuffer[6*i+1] = color.red; _ledBuffer[6*i+2] = color.green; _ledBuffer[6*i+3] = color.blue; // leave the next three bytes on zero... // 12-bit values have zeros in the lowest 4 bits which is almost correct, but it saves extra // switches to determine what to do and some bit shuffling } return writeBytes(_ledBuffer.data(), _ledBuffer.size()); } int LedDeviceLightpack::switchOff() { unsigned char buf[1] = {CMD_OFF_ALL}; return writeBytes(buf, sizeof(buf)) == sizeof(buf); } int LedDeviceLightpack::writeBytes(uint8_t *data, int size) { return libusb_control_transfer(_deviceHandle, LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0x09, (2 << 8), 0x00, data, size, 100); } int LedDeviceLightpack::disableSmoothing() { unsigned char buf[2] = {CMD_SET_SMOOTH_SLOWDOWN, 0}; return writeBytes(buf, sizeof(buf)) == sizeof(buf); } libusb_device_handle * LedDeviceLightpack::openDevice(libusb_device *device) { libusb_device_handle * handle = nullptr; int error = libusb_open(device, &handle); if (error != LIBUSB_SUCCESS) { throw error; } error = libusb_detach_kernel_driver(handle, LIGHTPACK_INTERFACE); if (error != LIBUSB_SUCCESS) { throw error; } error = libusb_claim_interface(handle, LIGHTPACK_INTERFACE); if (error != LIBUSB_SUCCESS) { throw error; } return handle; } std::string LedDeviceLightpack::getString(libusb_device * device, int stringDescriptorIndex) { libusb_device_handle * deviceHandle = openDevice(device); char buffer[256]; int error = libusb_get_string_descriptor_ascii(deviceHandle, stringDescriptorIndex, reinterpret_cast<unsigned char *>(buffer), sizeof(buffer)); if (error <= 0) { throw error; } libusb_close(deviceHandle); return std::string(buffer, error); } LedDeviceLightpack::Version LedDeviceLightpack::getVersion(libusb_device *device) { libusb_device_handle * deviceHandle = openDevice(device); uint8_t buffer[256]; int error = libusb_get_descriptor(deviceHandle, LIBUSB_DT_REPORT, 0, buffer, sizeof(buffer)); if (error <= 3) { throw error; } libusb_close(deviceHandle); return Version{buffer[INDEX_FW_VER_MAJOR], buffer[INDEX_FW_VER_MINOR]}; } <|endoftext|>
<commit_before>/** * @file LoaderUtils.cpp * @brief Utils to load Dart objects */ #include "DartLoader.h" #include <dynamics/SkeletonDynamics.h> #include <kinematics/TrfmTranslate.h> #include <kinematics/TrfmRotateEuler.h> #include <kinematics/TrfmRotateAxis.h> #include <kinematics/Dof.h> #include <kinematics/Joint.h> #include <kinematics/Shape.h> #include <kinematics/ShapeMesh.h> #include <kinematics/ShapeSphere.h> #include <kinematics/ShapeBox.h> #include <kinematics/ShapeCylinder.h> #include <dynamics/BodyNodeDynamics.h> #include <iostream> /** * @function add_XyzRpy */ void DartLoader::add_XyzRpy( kinematics::Joint* _joint, double _x, double _y, double _z, double _rr, double _rp, double _ry ) { kinematics::Transformation* trans; trans = new kinematics::TrfmTranslateX( new kinematics::Dof(_x) ); _joint->addTransform( trans, false ); trans = new kinematics::TrfmTranslateY( new kinematics::Dof(_y) ); _joint->addTransform( trans, false ); trans = new kinematics::TrfmTranslateZ( new kinematics::Dof(_z) ); _joint->addTransform( trans, false ); trans = new kinematics::TrfmRotateEulerZ(new ::kinematics::Dof(_ry )); _joint->addTransform(trans, false); trans = new kinematics::TrfmRotateEulerY(new ::kinematics::Dof( _rp )); _joint->addTransform(trans, false); trans = new kinematics::TrfmRotateEulerX(new ::kinematics::Dof( _rr )); _joint->addTransform(trans, false); } /** * @function add_DOF */ void DartLoader::add_DOF( dynamics::SkeletonDynamics* _skel, kinematics::Joint* _joint, double _val, double _min, double _max, int _DOF_TYPE, double _x, double _y, double _z ) { kinematics::Transformation* trans; if(_DOF_TYPE == GOLEM_X) { trans = new kinematics::TrfmTranslateX(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_Y) { trans = new kinematics::TrfmTranslateY(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_Z) { trans = new kinematics::TrfmTranslateZ(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_YAW) { trans = new kinematics::TrfmRotateEulerZ(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_PITCH) { trans = new kinematics::TrfmRotateEulerY(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_ROLL) { trans = new kinematics::TrfmRotateEulerX(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if( _DOF_TYPE == GOLEM_ARBITRARY_ROTATION ) { Eigen::Vector3d axis; axis << _x, _y, _z; trans = new kinematics::TrfmRotateAxis( axis, new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if( _DOF_TYPE == GOLEM_FLOATING ) { trans = new kinematics::TrfmTranslateX( new kinematics::Dof( 0, "floatingX" ), "Tfx" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmTranslateY( new kinematics::Dof( 0, "floatingY" ), "Tfy" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmTranslateZ( new kinematics::Dof( 0, "floatingZ" ), "Tfz" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmRotateEulerZ( new kinematics::Dof( 0, "floatingYaw" ), "Tfry" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmRotateEulerY( new kinematics::Dof( 0, "floatingPitch" ), "Tfrp" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmRotateEulerX( new kinematics::Dof( 0, "floatingRoll" ), "Tfrr" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); } else { if(debug) std::cerr << " WATCH OUT! THIS SHOULD NOT HAPPEN, NO DOF SET" << std::endl; } } /** * @function add_VizShape */ bool DartLoader::add_VizShape( dynamics::BodyNodeDynamics* _node, boost::shared_ptr<urdf::Visual> _viz, std::string _rootToSkelPath ) { // Variables to use kinematics::Shape* shape; const aiScene* model; urdf::Pose pose; // Origin pose = _viz->origin; // Type of Geometry //-- SPHERE if( _viz->geometry->type == urdf::Geometry::SPHERE ) { boost::shared_ptr<urdf::Sphere> sphere = boost::static_pointer_cast<urdf::Sphere>( _viz->geometry ); shape = new kinematics::ShapeSphere( sphere->radius ); // Set its pose Eigen::Affine3d transform; transform = pose2Affine3d( pose ); // Set it into shape shape->setTransform( transform ); // Set in node _node->setVizShape(shape); } //-- BOX else if( _viz->geometry->type == urdf::Geometry::BOX ) { } else if( _viz->geometry->type == urdf::Geometry::CYLINDER ) { } //-- Mesh : Save the path else if( _viz->geometry->type == urdf::Geometry::MESH ) { boost::shared_ptr<urdf::Mesh> mesh = boost::static_pointer_cast<urdf::Mesh>( _viz->geometry ); std::string fullPath = _rootToSkelPath; fullPath.append( mesh->filename ); // Load aiScene visualization model = kinematics::ShapeMesh::loadMesh( fullPath ); if( model == NULL ) { std::cout<< "[add_VizShape] [ERROR] Not loading model "<< fullPath<<" (NULL) \n"; return false; } // Set shape as mesh shape = new kinematics::ShapeMesh( Eigen::Vector3d( 1, 1, 1), model ); // Set its pose Eigen::Affine3d transform; transform = pose2Affine3d( pose ); // Set it into shape shape->setTransform( transform ); if(debug) std::cerr << "[debug] Loading visual model: " << fullPath << std::endl; // Set in node _node->setVizShape(shape); } // end if (mesh) else { std::cout<< "[set_VizShape] No MESH, BOX, CYLINDER OR SPHERE! Exiting"<<std::endl; return false; } return true; } /** * @function pose2Affine3d */ Eigen::Affine3d DartLoader::pose2Affine3d( urdf::Pose _pose ) { Eigen::Affine3d transform = Eigen::Affine3d::Identity(); // Set xyz Eigen::Vector3d t; t[0] = _pose.position.x; t[1] = _pose.position.y; t[2] = _pose.position.z; transform.translation() = t; // Set rpy double roll, pitch, yaw; _pose.rotation.getRPY( roll, pitch, yaw ); Eigen::Matrix3d rot; rot = Eigen::AngleAxisd( yaw, Eigen::Vector3d::UnitZ())* Eigen::AngleAxisd( pitch, Eigen::Vector3d::UnitY())* Eigen::AngleAxisd( roll, Eigen::Vector3d::UnitX() ); transform.matrix().block(0,0,3,3) = rot; return transform; } /** * @function add_ColShape */ bool DartLoader::add_ColShape( dynamics::BodyNodeDynamics* _node, boost::shared_ptr<urdf::Collision> _col, std::string _rootToSkelPath ) { // Variables to use kinematics::Shape* shape; const aiScene* model; urdf::Pose pose; // Origin pose = _col->origin; // Type of Geometry //-- Mesh : Save the path if( _col->geometry->type == urdf::Geometry::MESH ) { boost::shared_ptr<urdf::Mesh> mesh = boost::static_pointer_cast<urdf::Mesh>( _col->geometry ); std::string fullPath = _rootToSkelPath; fullPath.append( mesh->filename ); // Load aiScene visualization model = kinematics::ShapeMesh::loadMesh( fullPath ); if( model == NULL ) { std::cout<< "[add_ColShape] [ERROR] Not loading model "<< fullPath<<" (NULL) \n"; return false; } // Set shape as mesh shape = new kinematics::ShapeMesh( Eigen::Vector3d( 1, 1, 1), model ); // Set its pose Eigen::Affine3d transform = Eigen::Affine3d::Identity(); // Set xyz Eigen::Vector3d t; t[0] = pose.position.x; t[1] = pose.position.y; t[2] = pose.position.z; transform.translation() = t; // Set rpy double roll, pitch, yaw; pose.rotation.getRPY( roll, pitch, yaw ); Eigen::Matrix3d rot; rot = Eigen::AngleAxisd( yaw, Eigen::Vector3d::UnitZ())* Eigen::AngleAxisd( pitch, Eigen::Vector3d::UnitY())* Eigen::AngleAxisd( roll, Eigen::Vector3d::UnitX() ); transform.matrix().block(0,0,3,3) = rot; // Set it into shape shape->setTransform( transform ); if(debug) std::cerr << "[debug] Loading visual model: " << fullPath << std::endl; // Set in node _node->setColShape(shape); } // end if (mesh) else { std::cout<< "[set_ColShape] No MESH, BOX, CYLINDER OR SPHERE! Exiting"<<std::endl; return false; } return true; } <commit_msg>Added BOX and CYLINDER for VizShape parsing<commit_after>/** * @file LoaderUtils.cpp * @brief Utils to load Dart objects */ #include "DartLoader.h" #include <dynamics/SkeletonDynamics.h> #include <kinematics/TrfmTranslate.h> #include <kinematics/TrfmRotateEuler.h> #include <kinematics/TrfmRotateAxis.h> #include <kinematics/Dof.h> #include <kinematics/Joint.h> #include <kinematics/Shape.h> #include <kinematics/ShapeMesh.h> #include <kinematics/ShapeSphere.h> #include <kinematics/ShapeBox.h> #include <kinematics/ShapeCylinder.h> #include <dynamics/BodyNodeDynamics.h> #include <iostream> /** * @function add_XyzRpy */ void DartLoader::add_XyzRpy( kinematics::Joint* _joint, double _x, double _y, double _z, double _rr, double _rp, double _ry ) { kinematics::Transformation* trans; trans = new kinematics::TrfmTranslateX( new kinematics::Dof(_x) ); _joint->addTransform( trans, false ); trans = new kinematics::TrfmTranslateY( new kinematics::Dof(_y) ); _joint->addTransform( trans, false ); trans = new kinematics::TrfmTranslateZ( new kinematics::Dof(_z) ); _joint->addTransform( trans, false ); trans = new kinematics::TrfmRotateEulerZ(new ::kinematics::Dof(_ry )); _joint->addTransform(trans, false); trans = new kinematics::TrfmRotateEulerY(new ::kinematics::Dof( _rp )); _joint->addTransform(trans, false); trans = new kinematics::TrfmRotateEulerX(new ::kinematics::Dof( _rr )); _joint->addTransform(trans, false); } /** * @function add_DOF */ void DartLoader::add_DOF( dynamics::SkeletonDynamics* _skel, kinematics::Joint* _joint, double _val, double _min, double _max, int _DOF_TYPE, double _x, double _y, double _z ) { kinematics::Transformation* trans; if(_DOF_TYPE == GOLEM_X) { trans = new kinematics::TrfmTranslateX(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_Y) { trans = new kinematics::TrfmTranslateY(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_Z) { trans = new kinematics::TrfmTranslateZ(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_YAW) { trans = new kinematics::TrfmRotateEulerZ(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_PITCH) { trans = new kinematics::TrfmRotateEulerY(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if(_DOF_TYPE == GOLEM_ROLL) { trans = new kinematics::TrfmRotateEulerX(new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if( _DOF_TYPE == GOLEM_ARBITRARY_ROTATION ) { Eigen::Vector3d axis; axis << _x, _y, _z; trans = new kinematics::TrfmRotateAxis( axis, new kinematics::Dof(0, _joint->getName() ), "T_dof"); _joint->addTransform(trans, true); _joint->getDof(0)->setMin(_min); _joint->getDof(0)->setMax(_max); _skel->addTransform(trans); } else if( _DOF_TYPE == GOLEM_FLOATING ) { trans = new kinematics::TrfmTranslateX( new kinematics::Dof( 0, "floatingX" ), "Tfx" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmTranslateY( new kinematics::Dof( 0, "floatingY" ), "Tfy" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmTranslateZ( new kinematics::Dof( 0, "floatingZ" ), "Tfz" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmRotateEulerZ( new kinematics::Dof( 0, "floatingYaw" ), "Tfry" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmRotateEulerY( new kinematics::Dof( 0, "floatingPitch" ), "Tfrp" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); trans = new kinematics::TrfmRotateEulerX( new kinematics::Dof( 0, "floatingRoll" ), "Tfrr" ); _joint->addTransform( trans, true ); _skel->addTransform( trans ); } else { if(debug) std::cerr << " WATCH OUT! THIS SHOULD NOT HAPPEN, NO DOF SET" << std::endl; } } /** * @function add_VizShape */ bool DartLoader::add_VizShape( dynamics::BodyNodeDynamics* _node, boost::shared_ptr<urdf::Visual> _viz, std::string _rootToSkelPath ) { // Variables to use kinematics::Shape* shape; const aiScene* model; urdf::Pose pose; // Origin pose = _viz->origin; // Type of Geometry //-- SPHERE if( _viz->geometry->type == urdf::Geometry::SPHERE ) { boost::shared_ptr<urdf::Sphere> sphere = boost::static_pointer_cast<urdf::Sphere>( _viz->geometry ); shape = new kinematics::ShapeSphere( sphere->radius ); // Set its pose Eigen::Affine3d transform; transform = pose2Affine3d( pose ); // Set it into shape shape->setTransform( transform ); // Set in node _node->setVizShape(shape); } //-- BOX else if( _viz->geometry->type == urdf::Geometry::BOX ) { boost::shared_ptr<urdf::Box> box = boost::static_pointer_cast<urdf::Box>( _viz->geometry ); Eigen::Vector3d dim; dim<< box->dim.x, box->dim.y, box->dim.z; shape = new kinematics::ShapeBox( dim ); // Set its pose Eigen::Affine3d transform; transform = pose2Affine3d( pose ); // Set it into shape shape->setTransform( transform ); // Set in node _node->setVizShape(shape); } //-- CYLINDER else if( _viz->geometry->type == urdf::Geometry::CYLINDER ) { boost::shared_ptr<urdf::Cylinder> cylinder = boost::static_pointer_cast<urdf::Cylinder>( _viz->geometry ); shape = new kinematics::ShapeCylinder( cylinder->radius, cylinder->length ); // Set its pose Eigen::Affine3d transform; transform = pose2Affine3d( pose ); // Set it into shape shape->setTransform( transform ); // Set in node _node->setVizShape(shape); } //-- Mesh : Save the path else if( _viz->geometry->type == urdf::Geometry::MESH ) { boost::shared_ptr<urdf::Mesh> mesh = boost::static_pointer_cast<urdf::Mesh>( _viz->geometry ); std::string fullPath = _rootToSkelPath; fullPath.append( mesh->filename ); // Load aiScene visualization model = kinematics::ShapeMesh::loadMesh( fullPath ); if( model == NULL ) { std::cout<< "[add_VizShape] [ERROR] Not loading model "<< fullPath<<" (NULL) \n"; return false; } // Set shape as mesh shape = new kinematics::ShapeMesh( Eigen::Vector3d( 1, 1, 1), model ); // Set its pose Eigen::Affine3d transform; transform = pose2Affine3d( pose ); // Set it into shape shape->setTransform( transform ); if(debug) std::cerr << "[debug] Loading visual model: " << fullPath << std::endl; // Set in node _node->setVizShape(shape); } // end if (mesh) else { std::cout<< "[set_VizShape] No MESH, BOX, CYLINDER OR SPHERE! Exiting"<<std::endl; return false; } return true; } /** * @function pose2Affine3d */ Eigen::Affine3d DartLoader::pose2Affine3d( urdf::Pose _pose ) { Eigen::Affine3d transform = Eigen::Affine3d::Identity(); // Set xyz Eigen::Vector3d t; t[0] = _pose.position.x; t[1] = _pose.position.y; t[2] = _pose.position.z; transform.translation() = t; // Set rpy double roll, pitch, yaw; _pose.rotation.getRPY( roll, pitch, yaw ); Eigen::Matrix3d rot; rot = Eigen::AngleAxisd( yaw, Eigen::Vector3d::UnitZ())* Eigen::AngleAxisd( pitch, Eigen::Vector3d::UnitY())* Eigen::AngleAxisd( roll, Eigen::Vector3d::UnitX() ); transform.matrix().block(0,0,3,3) = rot; return transform; } /** * @function add_ColShape */ bool DartLoader::add_ColShape( dynamics::BodyNodeDynamics* _node, boost::shared_ptr<urdf::Collision> _col, std::string _rootToSkelPath ) { // Variables to use kinematics::Shape* shape; const aiScene* model; urdf::Pose pose; // Origin pose = _col->origin; // Type of Geometry //-- Mesh : Save the path if( _col->geometry->type == urdf::Geometry::MESH ) { boost::shared_ptr<urdf::Mesh> mesh = boost::static_pointer_cast<urdf::Mesh>( _col->geometry ); std::string fullPath = _rootToSkelPath; fullPath.append( mesh->filename ); // Load aiScene visualization model = kinematics::ShapeMesh::loadMesh( fullPath ); if( model == NULL ) { std::cout<< "[add_ColShape] [ERROR] Not loading model "<< fullPath<<" (NULL) \n"; return false; } // Set shape as mesh shape = new kinematics::ShapeMesh( Eigen::Vector3d( 1, 1, 1), model ); // Set its pose Eigen::Affine3d transform = Eigen::Affine3d::Identity(); // Set xyz Eigen::Vector3d t; t[0] = pose.position.x; t[1] = pose.position.y; t[2] = pose.position.z; transform.translation() = t; // Set rpy double roll, pitch, yaw; pose.rotation.getRPY( roll, pitch, yaw ); Eigen::Matrix3d rot; rot = Eigen::AngleAxisd( yaw, Eigen::Vector3d::UnitZ())* Eigen::AngleAxisd( pitch, Eigen::Vector3d::UnitY())* Eigen::AngleAxisd( roll, Eigen::Vector3d::UnitX() ); transform.matrix().block(0,0,3,3) = rot; // Set it into shape shape->setTransform( transform ); if(debug) std::cerr << "[debug] Loading visual model: " << fullPath << std::endl; // Set in node _node->setColShape(shape); } // end if (mesh) else { std::cout<< "[set_ColShape] No MESH, BOX, CYLINDER OR SPHERE! Exiting"<<std::endl; return false; } return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #include "HlsMaker.h" namespace mediakit { HlsMaker::HlsMaker(float seg_duration, uint32_t seg_number) { //最小允许设置为0,0个切片代表点播 seg_number = MAX(0,seg_number); seg_duration = MAX(1,seg_duration); _seg_number = seg_number; _seg_duration = seg_duration; } HlsMaker::~HlsMaker() { } void HlsMaker::makeIndexFile(bool eof) { char file_content[1024]; int maxSegmentDuration = 0; for (auto &tp : _seg_dur_list) { int dur = std::get<0>(tp); if (dur > maxSegmentDuration) { maxSegmentDuration = dur; } } string m3u8; snprintf(file_content,sizeof(file_content), "#EXTM3U\n" "#EXT-X-VERSION:3\n" "#EXT-X-ALLOW-CACHE:NO\n" "#EXT-X-TARGETDURATION:%u\n" "#EXT-X-MEDIA-SEQUENCE:%llu\n", (maxSegmentDuration + 999) / 1000, _seg_number ? _file_index : 0); m3u8.assign(file_content); for (auto &tp : _seg_dur_list) { snprintf(file_content,sizeof(file_content), "#EXTINF:%.3f,\n%s\n", std::get<0>(tp) / 1000.0, std::get<1>(tp).data()); m3u8.append(file_content); } if (eof) { snprintf(file_content,sizeof(file_content),"#EXT-X-ENDLIST\n"); m3u8.append(file_content); } onWriteHls(m3u8.data(), m3u8.size()); } void HlsMaker::inputData(void *data, uint32_t len, uint32_t timestamp, bool is_idr_fast_packet) { if (data && len) { if(is_idr_fast_packet){ addNewSegment(timestamp); } onWriteSegment((char *) data, len); //记录上次写入数据时间 _ticker_last_data.resetTime(); } else { //resetTracks时触发此逻辑 flushLastSegment(true); } } void HlsMaker::delOldSegment() { if(_seg_number == 0){ //如果设置为保留0个切片,则认为是保存为点播 return; } //在hls m3u8索引文件中,我们保存的切片个数跟_seg_number相关设置一致 if (_file_index > _seg_number) { _seg_dur_list.pop_front(); } GET_CONFIG(uint32_t,segRetain,Hls::kSegmentRetain); //但是实际保存的切片个数比m3u8所述多若干个,这样做的目的是防止播放器在切片删除前能下载完毕 if (_file_index > _seg_number + segRetain) { onDelSegment(_file_index - _seg_number - segRetain - 1); } } void HlsMaker::addNewSegment(uint32_t) { if(!_last_file_name.empty() && _ticker.elapsedTime() < _seg_duration * 1000){ //存在上个切片,并且未到分片时间 return; } //关闭并保存上一个切片,如果_seg_number==0,那么是点播。 flushLastSegment(_seg_number == 0); //新增切片 _last_file_name = onOpenSegment(_file_index++); //重置切片计时器 _ticker.resetTime(); } void HlsMaker::flushLastSegment(bool eof){ if(_last_file_name.empty()){ //不存在上个切片 return; } //文件创建到最后一次数据写入的时间即为切片长度 auto seg_dur = _ticker.elapsedTime() - _ticker_last_data.elapsedTime(); if(seg_dur <= 0){ seg_dur = 100; } _seg_dur_list.push_back(std::make_tuple(seg_dur, _last_file_name)); delOldSegment(); makeIndexFile(eof); _last_file_name.clear(); } bool HlsMaker::isLive() { return _seg_number != 0; } }//namespace mediakit<commit_msg>修复m3u8起始阶段SEQUENCE错误的bug:#288<commit_after>/* * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #include "HlsMaker.h" namespace mediakit { HlsMaker::HlsMaker(float seg_duration, uint32_t seg_number) { //最小允许设置为0,0个切片代表点播 _seg_number = seg_number; _seg_duration = seg_duration; } HlsMaker::~HlsMaker() { } void HlsMaker::makeIndexFile(bool eof) { char file_content[1024]; int maxSegmentDuration = 0; for (auto &tp : _seg_dur_list) { int dur = std::get<0>(tp); if (dur > maxSegmentDuration) { maxSegmentDuration = dur; } } auto sequence = _seg_number ? (_file_index > _seg_number ? _file_index - _seg_number : 0LL) : 0LL; string m3u8; snprintf(file_content,sizeof(file_content), "#EXTM3U\n" "#EXT-X-VERSION:3\n" "#EXT-X-ALLOW-CACHE:NO\n" "#EXT-X-TARGETDURATION:%u\n" "#EXT-X-MEDIA-SEQUENCE:%llu\n", (maxSegmentDuration + 999) / 1000, sequence); m3u8.assign(file_content); for (auto &tp : _seg_dur_list) { snprintf(file_content,sizeof(file_content), "#EXTINF:%.3f,\n%s\n", std::get<0>(tp) / 1000.0, std::get<1>(tp).data()); m3u8.append(file_content); } if (eof) { snprintf(file_content,sizeof(file_content),"#EXT-X-ENDLIST\n"); m3u8.append(file_content); } onWriteHls(m3u8.data(), m3u8.size()); } void HlsMaker::inputData(void *data, uint32_t len, uint32_t timestamp, bool is_idr_fast_packet) { if (data && len) { if(is_idr_fast_packet){ addNewSegment(timestamp); } onWriteSegment((char *) data, len); //记录上次写入数据时间 _ticker_last_data.resetTime(); } else { //resetTracks时触发此逻辑 flushLastSegment(true); } } void HlsMaker::delOldSegment() { if(_seg_number == 0){ //如果设置为保留0个切片,则认为是保存为点播 return; } //在hls m3u8索引文件中,我们保存的切片个数跟_seg_number相关设置一致 if (_file_index > _seg_number) { _seg_dur_list.pop_front(); } GET_CONFIG(uint32_t,segRetain,Hls::kSegmentRetain); //但是实际保存的切片个数比m3u8所述多若干个,这样做的目的是防止播放器在切片删除前能下载完毕 if (_file_index > _seg_number + segRetain) { onDelSegment(_file_index - _seg_number - segRetain - 1); } } void HlsMaker::addNewSegment(uint32_t) { if(!_last_file_name.empty() && _ticker.elapsedTime() < _seg_duration * 1000){ //存在上个切片,并且未到分片时间 return; } //关闭并保存上一个切片,如果_seg_number==0,那么是点播。 flushLastSegment(_seg_number == 0); //新增切片 _last_file_name = onOpenSegment(_file_index++); //重置切片计时器 _ticker.resetTime(); } void HlsMaker::flushLastSegment(bool eof){ if(_last_file_name.empty()){ //不存在上个切片 return; } //文件创建到最后一次数据写入的时间即为切片长度 auto seg_dur = _ticker.elapsedTime() - _ticker_last_data.elapsedTime(); if(seg_dur <= 0){ seg_dur = 100; } _seg_dur_list.push_back(std::make_tuple(seg_dur, _last_file_name)); delOldSegment(); makeIndexFile(eof); _last_file_name.clear(); } bool HlsMaker::isLive() { return _seg_number != 0; } }//namespace mediakit<|endoftext|>
<commit_before>#pragma once #include "opencv2/objdetect.hpp" #include "opencv2/imgproc.hpp" #include "FrameDerivatives.hpp" #include "FaceTracker.hpp" using namespace std; using namespace cv; namespace YerFace { class SeparateMarkers { public: SeparateMarkers(FrameDerivatives *myFrameDerivatives, FaceTracker *myFaceTracker, float myFaceSizePercentage = 1.25); void setHSVThreshold(Scalar myHSVThreshold, Scalar myHSVThresholdTolerance); void processCurrentFrame(void); void doPickColor(void); private: FrameDerivatives *frameDerivatives; FaceTracker *faceTracker; float faceSizePercentage; Scalar HSVThreshold; Scalar HSVThresholdTolerance; Mat searchFrameBGR; Mat searchFrameHSV; }; }; //namespace YerFace <commit_msg>improve default faceSizePercentage for marker separation<commit_after>#pragma once #include "opencv2/objdetect.hpp" #include "opencv2/imgproc.hpp" #include "FrameDerivatives.hpp" #include "FaceTracker.hpp" using namespace std; using namespace cv; namespace YerFace { class SeparateMarkers { public: SeparateMarkers(FrameDerivatives *myFrameDerivatives, FaceTracker *myFaceTracker, float myFaceSizePercentage = 1.5); void setHSVThreshold(Scalar myHSVThreshold, Scalar myHSVThresholdTolerance); void processCurrentFrame(void); void doPickColor(void); private: FrameDerivatives *frameDerivatives; FaceTracker *faceTracker; float faceSizePercentage; Scalar HSVThreshold; Scalar HSVThresholdTolerance; Mat searchFrameBGR; Mat searchFrameHSV; }; }; //namespace YerFace <|endoftext|>
<commit_before>// // Copyright (C) 2015 Marcus Comstedt <marcus@mc.pp.se> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include <fstream> #include <iostream> #include <cstdint> #include <memory> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define log(...) fprintf(stderr, __VA_ARGS__); #define info(...) do { if (log_level > 0) fprintf(stderr, __VA_ARGS__); } while (0) #define error(...) do { fprintf(stderr, "%s: ", program_short_name); fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); } while (0) static char *program_short_name; int log_level = 0; static const int NUM_IMAGES = 4; static const int NUM_HEADERS = NUM_IMAGES + 1; static const int HEADER_SIZE = 32; static void align_offset(uint32_t &offset, int bits) { uint32_t mask = (1 << bits) - 1; if (offset & mask) offset = (offset | mask) + 1; } static void write_byte(std::ostream &ofs, uint32_t &file_offset, uint8_t byte) { ofs << byte; file_offset++; } static void write_bytes(std::ostream &ofs, uint32_t &file_offset, const uint8_t *buf, size_t n) { if (n > 0) { ofs.write(reinterpret_cast<const char*>(buf), n); file_offset += n; } } static void write_file(std::ostream &ofs, uint32_t &file_offset, std::istream &ifs, const char *filename) { const size_t bufsize = 8192; uint8_t *buffer = new uint8_t[bufsize]; while(!ifs.eof()) { ifs.read(reinterpret_cast<char *>(buffer), bufsize); if (ifs.bad()) error("can't read input image `%s': %s\n", filename, strerror(errno)); write_bytes(ofs, file_offset, buffer, ifs.gcount()); } delete[] buffer; } static void pad_to(std::ostream &ofs, uint32_t &file_offset, uint32_t target) { if (target < file_offset) error("Trying to pad backwards!\n"); while(file_offset < target) write_byte(ofs, file_offset, 0xff); } class Image { const char *filename; std::ifstream ifs; uint32_t offs; public: Image(const char *filename); size_t size(); void write(std::ostream &ofs, uint32_t &file_offset); void place(uint32_t o) { offs = o; } uint32_t offset() const { return offs; } }; Image::Image(const char *filename) : filename(filename), ifs(filename, std::ifstream::binary) { if (ifs.fail()) error("can't open input image `%s': %s\n", filename, strerror(errno)); } size_t Image::size() { ifs.seekg (0, ifs.end); if (ifs.fail()) error("can't seek on input image `%s': %s\n", filename, strerror(errno)); size_t length = ifs.tellg(); ifs.seekg (0, ifs.beg); if (ifs.fail()) error("can't seek on input image `%s': %s\n", filename, strerror(errno)); if (length == 0) error("input image `%s' doesn't contain any data\n", filename); return length; } void Image::write(std::ostream &ofs, uint32_t &file_offset) { write_file(ofs, file_offset, ifs, filename); } class Header { public: Image const *image; void write(std::ostream &ofs, uint32_t &file_offset, bool coldboot); }; void Header::write(std::ostream &ofs, uint32_t &file_offset, bool coldboot) { // Preamble write_byte(ofs, file_offset, 0x7e); write_byte(ofs, file_offset, 0xaa); write_byte(ofs, file_offset, 0x99); write_byte(ofs, file_offset, 0x7e); // Boot mode write_byte(ofs, file_offset, 0x92); write_byte(ofs, file_offset, 0x00); write_byte(ofs, file_offset, coldboot ? 0x10 : 0x00); // Boot address write_byte(ofs, file_offset, 0x44); write_byte(ofs, file_offset, 0x03); write_byte(ofs, file_offset, (image->offset() >> 16) & 0xff); write_byte(ofs, file_offset, (image->offset() >> 8) & 0xff); write_byte(ofs, file_offset, image->offset() & 0xff); // Bank offset write_byte(ofs, file_offset, 0x82); write_byte(ofs, file_offset, 0x00); write_byte(ofs, file_offset, 0x00); // Reboot write_byte(ofs, file_offset, 0x01); write_byte(ofs, file_offset, 0x08); // Zero out any unused bytes while (file_offset & (HEADER_SIZE - 1)) write_byte(ofs, file_offset, 0x00); } void usage() { log("\n"); log("Usage: icemulti [options] input-files\n"); log("\n"); log(" -c\n"); log(" coldboot mode, power on reset image is selected by CBSEL0/CBSEL1\n"); log("\n"); log(" -p0, -p1, -p2, -p3\n"); log(" select power on reset image when not using coldboot mode\n"); log("\n"); log(" -a<n>, -A<n>\n"); log(" align images at 2^<n> bytes. -A also aligns image 0.\n"); log("\n"); log(" -o filename\n"); log(" write output image to file instead of stdout\n"); log("\n"); log(" -v\n"); log(" verbose (repeat to increase verbosity)\n"); log("\n"); exit(EXIT_FAILURE); } int main(int argc, char **argv) { int c; char *endptr = NULL; bool coldboot = false; int por_image = 0; int image_count = 0; int align_bits = 0; bool align_first = false; Header headers[NUM_HEADERS]; std::unique_ptr<Image> images[NUM_IMAGES]; const char *outfile_name = NULL; static struct option long_options[] = { {NULL, 0, NULL, 0} }; program_short_name = strrchr(argv[0], '/'); if (program_short_name == NULL) program_short_name = argv[0]; else program_short_name++; while ((c = getopt_long(argc, argv, "cp:a:A:o:v", long_options, NULL)) != -1) switch (c) { case 'c': coldboot = true; break; case 'p': if (optarg[0] == '0' && optarg[1] == '\0') por_image = 0; else if (optarg[0] == '1' && optarg[1] == '\0') por_image = 1; else if (optarg[0] == '2' && optarg[1] == '\0') por_image = 2; else if (optarg[0] == '3' && optarg[1] == '\0') por_image = 3; else error("`%s' is not a valid power-on/reset image (must be 0, 1, 2, or 3)\n", optarg); break; case 'A': align_first = true; /* fallthrough */ case 'a': align_bits = strtol(optarg, &endptr, 0); if (*endptr != '\0') error("`%s' is not a valid number\n", optarg); if (align_bits < 0) error("argument to `-%c' must be non-negative\n", c); break; case 'o': outfile_name = optarg; break; case 'v': log_level++; break; default: usage(); } if (optind == argc) { fprintf(stderr, "%s: missing argument\n", program_short_name); usage(); } while (optind != argc) { if (image_count >= NUM_IMAGES) error("Too many images supplied\n"); images[image_count++].reset(new Image(argv[optind++])); } if (coldboot && por_image != 0) error("Can't select power on reset boot image in cold boot mode\n"); if (por_image >= image_count) error("Specified non-existing image for power on reset\n"); // Place images uint32_t offs = NUM_HEADERS * HEADER_SIZE; if (align_first) align_offset(offs, align_bits); for (int i=0; i<image_count; i++) { images[i]->place(offs); offs += images[i]->size(); align_offset(offs, align_bits); info("Place image %d at %06x .. %06x.\n", i, int(images[i]->offset()), int(offs)); } // Populate headers for (int i=0; i<image_count; i++) headers[i + 1].image = &*images[i]; headers[0].image = headers[por_image + 1].image; for (int i=image_count; i < NUM_IMAGES; i++) headers[i + 1].image = headers[0].image; std::ofstream ofs; std::ostream *osp; if (outfile_name != NULL) { ofs.open(outfile_name, std::ofstream::binary); if (!ofs.is_open()) error("can't open output file `%s': %s\n", outfile_name, strerror(errno)); osp = &ofs; } else { osp = &std::cout; } uint32_t file_offset = 0; for (int i=0; i<NUM_HEADERS; i++) { pad_to(*osp, file_offset, i * HEADER_SIZE); headers[i].write(*osp, file_offset, i == 0 && coldboot); } for (int i=0; i<image_count; i++) { pad_to(*osp, file_offset, images[i]->offset()); images[i]->write(*osp, file_offset); } info("Done.\n"); return EXIT_SUCCESS; } <commit_msg>icemulti: Make function `write_header' global<commit_after>// // Copyright (C) 2015 Marcus Comstedt <marcus@mc.pp.se> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include <fstream> #include <iostream> #include <cstdint> #include <memory> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define log(...) fprintf(stderr, __VA_ARGS__); #define info(...) do { if (log_level > 0) fprintf(stderr, __VA_ARGS__); } while (0) #define error(...) do { fprintf(stderr, "%s: ", program_short_name); fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); } while (0) static char *program_short_name; int log_level = 0; static const int NUM_IMAGES = 4; static const int NUM_HEADERS = NUM_IMAGES + 1; static const int HEADER_SIZE = 32; static void align_offset(uint32_t &offset, int bits) { uint32_t mask = (1 << bits) - 1; if (offset & mask) offset = (offset | mask) + 1; } static void write_byte(std::ostream &ofs, uint32_t &file_offset, uint8_t byte) { ofs << byte; file_offset++; } static void write_bytes(std::ostream &ofs, uint32_t &file_offset, const uint8_t *buf, size_t n) { if (n > 0) { ofs.write(reinterpret_cast<const char*>(buf), n); file_offset += n; } } static void write_file(std::ostream &ofs, uint32_t &file_offset, std::istream &ifs, const char *filename) { const size_t bufsize = 8192; uint8_t *buffer = new uint8_t[bufsize]; while(!ifs.eof()) { ifs.read(reinterpret_cast<char *>(buffer), bufsize); if (ifs.bad()) error("can't read input image `%s': %s\n", filename, strerror(errno)); write_bytes(ofs, file_offset, buffer, ifs.gcount()); } delete[] buffer; } static void pad_to(std::ostream &ofs, uint32_t &file_offset, uint32_t target) { if (target < file_offset) error("Trying to pad backwards!\n"); while(file_offset < target) write_byte(ofs, file_offset, 0xff); } class Image { const char *filename; std::ifstream ifs; uint32_t offs; public: Image(const char *filename); size_t size(); void write(std::ostream &ofs, uint32_t &file_offset); void place(uint32_t o) { offs = o; } uint32_t offset() const { return offs; } }; Image::Image(const char *filename) : filename(filename), ifs(filename, std::ifstream::binary) { if (ifs.fail()) error("can't open input image `%s': %s\n", filename, strerror(errno)); } size_t Image::size() { ifs.seekg (0, ifs.end); if (ifs.fail()) error("can't seek on input image `%s': %s\n", filename, strerror(errno)); size_t length = ifs.tellg(); ifs.seekg (0, ifs.beg); if (ifs.fail()) error("can't seek on input image `%s': %s\n", filename, strerror(errno)); if (length == 0) error("input image `%s' doesn't contain any data\n", filename); return length; } void Image::write(std::ostream &ofs, uint32_t &file_offset) { write_file(ofs, file_offset, ifs, filename); } class Header { public: Image const *image; }; static void write_header(std::ostream &ofs, uint32_t &file_offset, Image const *image, bool coldboot) { // Preamble write_byte(ofs, file_offset, 0x7e); write_byte(ofs, file_offset, 0xaa); write_byte(ofs, file_offset, 0x99); write_byte(ofs, file_offset, 0x7e); // Boot mode write_byte(ofs, file_offset, 0x92); write_byte(ofs, file_offset, 0x00); write_byte(ofs, file_offset, coldboot ? 0x10 : 0x00); // Boot address write_byte(ofs, file_offset, 0x44); write_byte(ofs, file_offset, 0x03); write_byte(ofs, file_offset, (image->offset() >> 16) & 0xff); write_byte(ofs, file_offset, (image->offset() >> 8) & 0xff); write_byte(ofs, file_offset, image->offset() & 0xff); // Bank offset write_byte(ofs, file_offset, 0x82); write_byte(ofs, file_offset, 0x00); write_byte(ofs, file_offset, 0x00); // Reboot write_byte(ofs, file_offset, 0x01); write_byte(ofs, file_offset, 0x08); // Zero out any unused bytes while (file_offset & (HEADER_SIZE - 1)) write_byte(ofs, file_offset, 0x00); } void usage() { log("\n"); log("Usage: icemulti [options] input-files\n"); log("\n"); log(" -c\n"); log(" coldboot mode, power on reset image is selected by CBSEL0/CBSEL1\n"); log("\n"); log(" -p0, -p1, -p2, -p3\n"); log(" select power on reset image when not using coldboot mode\n"); log("\n"); log(" -a<n>, -A<n>\n"); log(" align images at 2^<n> bytes. -A also aligns image 0.\n"); log("\n"); log(" -o filename\n"); log(" write output image to file instead of stdout\n"); log("\n"); log(" -v\n"); log(" verbose (repeat to increase verbosity)\n"); log("\n"); exit(EXIT_FAILURE); } int main(int argc, char **argv) { int c; char *endptr = NULL; bool coldboot = false; int por_image = 0; int image_count = 0; int align_bits = 0; bool align_first = false; Header headers[NUM_HEADERS]; std::unique_ptr<Image> images[NUM_IMAGES]; const char *outfile_name = NULL; static struct option long_options[] = { {NULL, 0, NULL, 0} }; program_short_name = strrchr(argv[0], '/'); if (program_short_name == NULL) program_short_name = argv[0]; else program_short_name++; while ((c = getopt_long(argc, argv, "cp:a:A:o:v", long_options, NULL)) != -1) switch (c) { case 'c': coldboot = true; break; case 'p': if (optarg[0] == '0' && optarg[1] == '\0') por_image = 0; else if (optarg[0] == '1' && optarg[1] == '\0') por_image = 1; else if (optarg[0] == '2' && optarg[1] == '\0') por_image = 2; else if (optarg[0] == '3' && optarg[1] == '\0') por_image = 3; else error("`%s' is not a valid power-on/reset image (must be 0, 1, 2, or 3)\n", optarg); break; case 'A': align_first = true; /* fallthrough */ case 'a': align_bits = strtol(optarg, &endptr, 0); if (*endptr != '\0') error("`%s' is not a valid number\n", optarg); if (align_bits < 0) error("argument to `-%c' must be non-negative\n", c); break; case 'o': outfile_name = optarg; break; case 'v': log_level++; break; default: usage(); } if (optind == argc) { fprintf(stderr, "%s: missing argument\n", program_short_name); usage(); } while (optind != argc) { if (image_count >= NUM_IMAGES) error("Too many images supplied\n"); images[image_count++].reset(new Image(argv[optind++])); } if (coldboot && por_image != 0) error("Can't select power on reset boot image in cold boot mode\n"); if (por_image >= image_count) error("Specified non-existing image for power on reset\n"); // Place images uint32_t offs = NUM_HEADERS * HEADER_SIZE; if (align_first) align_offset(offs, align_bits); for (int i=0; i<image_count; i++) { images[i]->place(offs); offs += images[i]->size(); align_offset(offs, align_bits); info("Place image %d at %06x .. %06x.\n", i, int(images[i]->offset()), int(offs)); } // Populate headers for (int i=0; i<image_count; i++) headers[i + 1].image = &*images[i]; headers[0].image = headers[por_image + 1].image; for (int i=image_count; i < NUM_IMAGES; i++) headers[i + 1].image = headers[0].image; std::ofstream ofs; std::ostream *osp; if (outfile_name != NULL) { ofs.open(outfile_name, std::ofstream::binary); if (!ofs.is_open()) error("can't open output file `%s': %s\n", outfile_name, strerror(errno)); osp = &ofs; } else { osp = &std::cout; } uint32_t file_offset = 0; for (int i=0; i<NUM_HEADERS; i++) { pad_to(*osp, file_offset, i * HEADER_SIZE); write_header(*osp, file_offset, headers[i].image, i == 0 && coldboot); } for (int i=0; i<image_count; i++) { pad_to(*osp, file_offset, images[i]->offset()); images[i]->write(*osp, file_offset); } info("Done.\n"); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <windows.h> #include <gl\gl.h> #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include <math.h> #include "Window.h" #include "Body.h" #include "Error.h" #include "Info.h" #define NAME_FONT_NAME "Arial" #define NAME_FONT_SIZE_AT_H600 24 #define NAME_FONT_SIZE (NAME_FONT_SIZE_AT_H600*scrheight/600) #define NAME_TEXT_COLOR_R 1.00f #define NAME_TEXT_COLOR_G 1.00f #define NAME_TEXT_COLOR_B 1.00f #define NAME_TEXT_COLOR_A 0.50f #define INFO_FONT_NAME "Arial" #define INFO_FONT_SIZE_AT_H600 16 #define INFO_FONT_SIZE (INFO_FONT_SIZE_AT_H600*scrheight/600) #define INFO_TEXT_COLOR_R 1.00f #define INFO_TEXT_COLOR_G 1.00f #define INFO_TEXT_COLOR_B 1.00f #define INFO_TEXT_COLOR_A 0.50f #define SPACING_COEF 1.15f #define LINES_AFTER_NAME 1.00f #define WINDOW_COLOR_R 0.50f #define WINDOW_COLOR_G 0.50f #define WINDOW_COLOR_B 0.50f #define WINDOW_COLOR_A 0.25f #define MAX_FADE_TIME 3.0f #define FADE_TIME_RATIO 0.10f #define FADE_TIME(totaltime) min(MAX_FADE_TIME, (totaltime)*FADE_TIME_RATIO) #define WINDOW_BORDER_REL 0.0125f #define WINDOW_BORDER (WINDOW_BORDER_REL*scrheight) #define WINDOW_WIDTH_REL_Y (0.3075f*4.0f/3.0f) #define WINDOW_WIDTH (WINDOW_WIDTH_REL_Y*scrheight) #define WINDOW_HEIGHT_REL 0.2575f #define WINDOW_HEIGHT (WINDOW_HEIGHT_REL*scrheight) #define WINDOW_POS_X1 (WINDOW_BORDER) #define WINDOW_POS_Y1 (WINDOW_BORDER) #define WINDOW_POS_X2 (WINDOW_POS_X1+WINDOW_WIDTH) #define WINDOW_POS_Y2 (WINDOW_POS_Y1+WINDOW_HEIGHT) #define MARGIN_TOP_REL 0.100f #define MARGIN_LEFT_REL 0.075f #define MARGIN_WIDTH (WINDOW_WIDTH*MARGIN_LEFT_REL) #define MARGIN_HEIGHT (WINDOW_HEIGHT*MARGIN_TOP_REL) CInfo::CInfo() { Init(); } CInfo::~CInfo() { Free(); } void CInfo::Init() { loaded=false; scrwidth=0; scrheight=0; winlist=0; namelist=infolist=0; time=0; starttime=endtime=0; fadetime=1; alpha=0; } void CInfo::Free() { nametext.Free(); infotext.Free(); if (winlist) { if (glIsList(winlist)) glDeleteLists(winlist,3); } Init(); } bool CInfo::Load() { Free(); scrwidth=(float)CWindow::GetWidth(); scrheight=(float)CWindow::GetHeight(); winlist=glGenLists(3); if (!winlist) { CError::LogError(WARNING_CODE,"Unable to load planet info - failed to generate display lists."); Free(); return false; } namelist=winlist+1; infolist=namelist+1; MakeWindow(winlist); loaded=true; loaded&=nametext.BuildFTFont(NAME_FONT_NAME,(int)NAME_FONT_SIZE); loaded&=infotext.BuildFTFont(INFO_FONT_NAME,(int)INFO_FONT_SIZE); if (!loaded) { CError::LogError(WARNING_CODE,"Unable to load planet info - failed to load font."); Free(); } return loaded; } void CInfo::MakeWindow(int list) { glNewList(list,GL_COMPILE); { int l=(int)WINDOW_POS_X1; int r=(int)WINDOW_POS_X2; int b=(int)WINDOW_POS_Y1; int t=(int)WINDOW_POS_Y2; glDisable(GL_TEXTURE_2D); glLoadIdentity(); glBegin(GL_QUADS); { glVertex2f((float)l,(float)b); glVertex2f((float)r,(float)b); glVertex2f((float)r,(float)t); glVertex2f((float)l,(float)t); } glEnd(); } glEndList(); } void CInfo::GetNameCoords(const char *text, float *x, float *y) { float tw; nametext.GetTextSize(text,&tw,NULL); if (x) *x=WINDOW_POS_X1+(WINDOW_WIDTH-tw)*0.5f; if (y) *y=WINDOW_POS_Y2-MARGIN_HEIGHT-NAME_FONT_SIZE; } void CInfo::GetInfoCoords(int linenum, float *x, float *y) { float namey; GetNameCoords(" ",NULL,&namey); float nameadd; nametext.GetTextSize(" ",NULL,&nameadd); nameadd*=(SPACING_COEF*LINES_AFTER_NAME); float th; infotext.GetTextSize(" ",NULL,&th); th*=SPACING_COEF*(float)(linenum-1); if (x) *x=WINDOW_POS_X1+MARGIN_WIDTH; if (y) *y=namey-nameadd-th; } void CInfo::MakeName(int list, char *targetname) { if (!targetname) return; if (*targetname==' ') targetname++; float x,y; GetNameCoords(targetname,&x,&y); int xi=(int)x,yi=(int)y; glNewList(list,GL_COMPILE); { glEnable(GL_TEXTURE_2D); glLoadIdentity(); glTranslatef((float)xi,(float)yi,0); nametext.Print(targetname); } glEndList(); } void CInfo::MakeInfoLine(int linenum, char *line) { float x,y; GetInfoCoords(linenum,&x,&y); int xi=(int)x,yi=(int)y; glPushMatrix(); glTranslatef((float)xi,(float)yi,0); infotext.Print(line); glPopMatrix(); } void CInfo::MakeInfo(int list, CBody *targetbody) { bool star=(targetbody==NULL); if (star) targetbody=CBody::bodycache[0]; glNewList(list,GL_COMPILE); { int n=0; glEnable(GL_TEXTURE_2D); glLoadIdentity(); if (star) { char line[64]; n++; sprintf(line,"star name: %s",targetbody->name); MakeInfoLine(n,line); } for (int i=0;i<targetbody->info.numlines;i++) { if (targetbody->info.textlines[i][0]=='/') continue; n++; MakeInfoLine(n,targetbody->info.textlines[i]); } } glEndList(); } void CInfo::Start(float seconds, float duration, char *targetname, CBody *targetbody) { if (!loaded) return; char name[32]; strcpy(name,targetname); int l=strlen(name); for (int i=0;i<l;i++) if (name[i]=='_') name[i]=' '; starttime=seconds; endtime=starttime+duration; fadetime=FADE_TIME(duration); MakeName(namelist,name); MakeInfo(infolist,targetbody); } void CInfo::Update(float seconds) { time=seconds; if (time<(endtime-fadetime)) alpha=min(1,(time-starttime)/fadetime); else alpha=max(0,(endtime-time)/fadetime); } void CInfo::Restart() { starttime-=time; endtime-=time; time=0; } void CInfo::Draw() { if (!alpha || !loaded) return; glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glColor4f(WINDOW_COLOR_R,WINDOW_COLOR_G,WINDOW_COLOR_B,WINDOW_COLOR_A*alpha); glCallList(winlist); glColor4f(NAME_TEXT_COLOR_R,NAME_TEXT_COLOR_G,NAME_TEXT_COLOR_B,NAME_TEXT_COLOR_A*alpha); glCallList(namelist); glColor4f(INFO_TEXT_COLOR_R,INFO_TEXT_COLOR_G,INFO_TEXT_COLOR_B,INFO_TEXT_COLOR_A*alpha); glCallList(infolist); } <commit_msg>Small correction to text coordinates.<commit_after>#include <windows.h> #include <gl\gl.h> #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include <math.h> #include "Window.h" #include "Body.h" #include "Error.h" #include "Info.h" #define NAME_FONT_NAME "Arial" #define NAME_FONT_SIZE_AT_H600 24 #define NAME_FONT_SIZE (NAME_FONT_SIZE_AT_H600*scrheight/600) #define NAME_TEXT_COLOR_R 1.00f #define NAME_TEXT_COLOR_G 1.00f #define NAME_TEXT_COLOR_B 1.00f #define NAME_TEXT_COLOR_A 0.50f #define INFO_FONT_NAME "Arial" #define INFO_FONT_SIZE_AT_H600 16 #define INFO_FONT_SIZE (INFO_FONT_SIZE_AT_H600*scrheight/600) #define INFO_TEXT_COLOR_R 1.00f #define INFO_TEXT_COLOR_G 1.00f #define INFO_TEXT_COLOR_B 1.00f #define INFO_TEXT_COLOR_A 0.50f #define SPACING_COEF 1.15f #define LINES_AFTER_NAME 1.00f #define WINDOW_COLOR_R 0.50f #define WINDOW_COLOR_G 0.50f #define WINDOW_COLOR_B 0.50f #define WINDOW_COLOR_A 0.25f #define MAX_FADE_TIME 3.0f #define FADE_TIME_RATIO 0.10f #define FADE_TIME(totaltime) min(MAX_FADE_TIME, (totaltime)*FADE_TIME_RATIO) #define WINDOW_BORDER_REL 0.0125f #define WINDOW_BORDER (WINDOW_BORDER_REL*scrheight) #define WINDOW_WIDTH_REL_Y (0.3075f*4.0f/3.0f) #define WINDOW_WIDTH (WINDOW_WIDTH_REL_Y*scrheight) #define WINDOW_HEIGHT_REL 0.2575f #define WINDOW_HEIGHT (WINDOW_HEIGHT_REL*scrheight) #define WINDOW_POS_X1 (WINDOW_BORDER) #define WINDOW_POS_Y1 (WINDOW_BORDER) #define WINDOW_POS_X2 (WINDOW_POS_X1+WINDOW_WIDTH) #define WINDOW_POS_Y2 (WINDOW_POS_Y1+WINDOW_HEIGHT) #define MARGIN_TOP_REL 0.100f #define MARGIN_LEFT_REL 0.075f #define MARGIN_WIDTH (WINDOW_WIDTH*MARGIN_LEFT_REL) #define MARGIN_HEIGHT (WINDOW_HEIGHT*MARGIN_TOP_REL) CInfo::CInfo() { Init(); } CInfo::~CInfo() { Free(); } void CInfo::Init() { loaded=false; scrwidth=0; scrheight=0; winlist=0; namelist=infolist=0; time=0; starttime=endtime=0; fadetime=1; alpha=0; } void CInfo::Free() { nametext.Free(); infotext.Free(); if (winlist) { if (glIsList(winlist)) glDeleteLists(winlist,3); } Init(); } bool CInfo::Load() { Free(); scrwidth=(float)CWindow::GetWidth(); scrheight=(float)CWindow::GetHeight(); winlist=glGenLists(3); if (!winlist) { CError::LogError(WARNING_CODE,"Unable to load planet info - failed to generate display lists."); Free(); return false; } namelist=winlist+1; infolist=namelist+1; MakeWindow(winlist); loaded=true; loaded&=nametext.BuildFTFont(NAME_FONT_NAME,(int)NAME_FONT_SIZE); loaded&=infotext.BuildFTFont(INFO_FONT_NAME,(int)INFO_FONT_SIZE); if (!loaded) { CError::LogError(WARNING_CODE,"Unable to load planet info - failed to load font."); Free(); } return loaded; } void CInfo::MakeWindow(int list) { glNewList(list,GL_COMPILE); { int l=(int)WINDOW_POS_X1; int r=(int)WINDOW_POS_X2; int b=(int)WINDOW_POS_Y1; int t=(int)WINDOW_POS_Y2; glDisable(GL_TEXTURE_2D); glLoadIdentity(); glBegin(GL_QUADS); { glVertex2f((float)l,(float)b); glVertex2f((float)r,(float)b); glVertex2f((float)r,(float)t); glVertex2f((float)l,(float)t); } glEnd(); } glEndList(); } void CInfo::GetNameCoords(const char *text, float *x, float *y) { float tw; nametext.GetTextSize(text,&tw,NULL); int th=(int)NAME_FONT_SIZE; if (x) *x=WINDOW_POS_X1+(WINDOW_WIDTH-tw)*0.5f; if (y) *y=WINDOW_POS_Y2-MARGIN_HEIGHT-(float)th; } void CInfo::GetInfoCoords(int linenum, float *x, float *y) { float namey; GetNameCoords(" ",NULL,&namey); float nameadd; nametext.GetTextSize(" ",NULL,&nameadd); nameadd*=(SPACING_COEF*LINES_AFTER_NAME); float th; infotext.GetTextSize(" ",NULL,&th); th*=SPACING_COEF*(float)(linenum-1); if (x) *x=WINDOW_POS_X1+MARGIN_WIDTH; if (y) *y=namey-nameadd-th; } void CInfo::MakeName(int list, char *targetname) { if (!targetname) return; if (*targetname==' ') targetname++; float x,y; GetNameCoords(targetname,&x,&y); int xi=(int)x,yi=(int)y; glNewList(list,GL_COMPILE); { glEnable(GL_TEXTURE_2D); glLoadIdentity(); glTranslatef((float)xi,(float)yi,0); nametext.Print(targetname); } glEndList(); } void CInfo::MakeInfoLine(int linenum, char *line) { float x,y; GetInfoCoords(linenum,&x,&y); int xi=(int)x,yi=(int)y; glPushMatrix(); glTranslatef((float)xi,(float)yi,0); infotext.Print(line); glPopMatrix(); } void CInfo::MakeInfo(int list, CBody *targetbody) { bool star=(targetbody==NULL); if (star) targetbody=CBody::bodycache[0]; glNewList(list,GL_COMPILE); { int n=0; glEnable(GL_TEXTURE_2D); glLoadIdentity(); if (star) { char line[64]; n++; sprintf(line,"star name: %s",targetbody->name); MakeInfoLine(n,line); } for (int i=0;i<targetbody->info.numlines;i++) { if (targetbody->info.textlines[i][0]=='/') continue; n++; MakeInfoLine(n,targetbody->info.textlines[i]); } } glEndList(); } void CInfo::Start(float seconds, float duration, char *targetname, CBody *targetbody) { if (!loaded) return; char name[32]; strcpy(name,targetname); int l=strlen(name); for (int i=0;i<l;i++) if (name[i]=='_') name[i]=' '; starttime=seconds; endtime=starttime+duration; fadetime=FADE_TIME(duration); MakeName(namelist,name); MakeInfo(infolist,targetbody); } void CInfo::Update(float seconds) { time=seconds; if (time<(endtime-fadetime)) alpha=min(1,(time-starttime)/fadetime); else alpha=max(0,(endtime-time)/fadetime); } void CInfo::Restart() { starttime-=time; endtime-=time; time=0; } void CInfo::Draw() { if (!alpha || !loaded) return; glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glColor4f(WINDOW_COLOR_R,WINDOW_COLOR_G,WINDOW_COLOR_B,WINDOW_COLOR_A*alpha); glCallList(winlist); glColor4f(NAME_TEXT_COLOR_R,NAME_TEXT_COLOR_G,NAME_TEXT_COLOR_B,NAME_TEXT_COLOR_A*alpha); glCallList(namelist); glColor4f(INFO_TEXT_COLOR_R,INFO_TEXT_COLOR_G,INFO_TEXT_COLOR_B,INFO_TEXT_COLOR_A*alpha); glCallList(infolist); } <|endoftext|>
<commit_before>/* Copyright 2019 Alain Dargelas 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: FileUtils.cpp * Author: alain * * Created on March 16, 2017, 11:02 PM */ #include "Utils/FileUtils.h" #include <errno.h> #include <limits.h> /* PATH_MAX */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <algorithm> #include <fstream> #include <iostream> #include <regex> #include <sstream> #include <string> #include "SourceCompile/SymbolTable.h" #include "Utils/StringUtils.h" #if defined(_MSC_VER) #include <direct.h> #define PATH_MAX _MAX_PATH #else #include <dirent.h> #include <unistd.h> #endif #if (__cplusplus >= 201703L) && __has_include(<filesystem>) #include <filesystem> namespace fs = std::filesystem; #else #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #endif using namespace SURELOG; bool FileUtils::fileExists(const std::string& name) { std::error_code ec; return fs::exists(name, ec); } unsigned long FileUtils::fileSize(const std::string& name) { std::error_code ec; return fs::file_size(name, ec); } bool FileUtils::fileIsDirectory(const std::string& name) { return fs::is_directory(name); } bool FileUtils::fileIsRegular(const std::string& name) { return fs::is_regular_file(name); } SymbolId FileUtils::locateFile(SymbolId file, SymbolTable* symbols, const std::vector<SymbolId>& paths) { const std::string& fileName = symbols->getSymbol(file); if (fileExists(fileName)) { return file; } for (auto id : paths) { const std::string& path = symbols->getSymbol(id); std::string filePath; if (path.size() && (path[path.size() - 1] == '/')) filePath = path + fileName; else filePath = path + "/" + fileName; if (fileExists(filePath)) { return symbols->registerSymbol(filePath); } } return symbols->getBadId(); } int FileUtils::mkDir(const char* path) { // CAUTION: There is a known bug in VC compiler where a trailing // slash in the path will cause a false return from a call to // fs::create_directories. const std::string dirpath(path); fs::create_directories(dirpath); return fs::is_directory(dirpath) ? 0 : -1; } int FileUtils::rmDir(const char* path) { const std::string dirpath(path); return fs::remove_all(dirpath); } std::string FileUtils::getFullPath(const std::string& path) { std::error_code ec; fs::path fullPath = fs::canonical(path, ec); return ec ? path : fullPath.string(); } bool FileUtils::getFullPath(const std::string& path, std::string* result) { std::error_code ec; fs::path fullPath = fs::canonical(path, ec); bool found = (!ec && fileIsRegular(fullPath.string())); if (result != nullptr) { *result = found ? fullPath.string() : path; } return found; } static bool has_suffix(const std::string& s, const std::string& suffix) { return (s.size() >= suffix.size()) && equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } std::vector<SymbolId> FileUtils::collectFiles(SymbolId dirPath, SymbolId ext, SymbolTable* symbols) { return collectFiles(symbols->getSymbol(dirPath), symbols->getSymbol(ext), symbols); } std::vector<SymbolId> FileUtils::collectFiles(const std::string& dirPath, const std::string& ext, SymbolTable* symbols) { std::vector<SymbolId> result; if (fileIsDirectory(dirPath)) { for (fs::directory_entry entry : fs::directory_iterator(dirPath)) { const std::string filepath = entry.path().string(); if (has_suffix(filepath, ext)) { result.push_back(symbols->registerSymbol(filepath)); } } } return result; } std::vector<SymbolId> FileUtils::collectFiles(const std::string& pathSpec, SymbolTable* const symbols) { // ? single character wildcard (matches any single character) // * multiple character wildcard (matches any number of characters in a // directory/file name) // ... hierarchical wildcard (matches any number of hierarchical directories) // .. specifies the parent directory // . specifies the directory containing the lib.map // Paths that end in / shall include all files in the specified directory. // Identical to / * Paths that do not begin with / are relative to the // directory in which the current lib.map file is located. std::vector<SymbolId> result; std::error_code ec; fs::path path(pathSpec); if (!path.is_absolute()) { path = fs::current_path(ec) / path; if (ec) return result; } path.make_preferred(); fs::path prefix; fs::path suffix; for (const fs::path& subpath : path) { const std::string substr = subpath.string(); if (substr.compare(".") == 0) continue; else if (!suffix.empty()) suffix /= subpath; else if (substr.find_first_of(".?*") == std::string::npos) prefix /= subpath; else suffix /= subpath; } prefix = fs::canonical(prefix, ec); if (ec) return result; if (suffix.empty()) suffix /= "*"; const std::string separator(1, fs::path::preferred_separator); const std::string escaped = "\\" + separator; std::string regexp = suffix.string(); regexp = StringUtils::replaceAll(regexp, separator, escaped); // escape separators regexp = StringUtils::replaceAll( regexp, "..." + escaped, R"([a-zA-Z0-9_\-.)" + escaped + R"(]+)" + escaped); // separator allowed regexp = StringUtils::replaceAll(regexp, ".." + escaped, R"([a-zA-Z0-9_\-.]+)" + escaped + R"([a-zA-Z0-9_\-.]+)" + escaped); // separator NOT allowed regexp = StringUtils::replaceAll(regexp, ".", "\\."); // escape it regexp = StringUtils::replaceAll(regexp, "?", R"([a-zA-Z0-9_\-\.])"); // at most one regexp = StringUtils::replaceAll(regexp, "*", "[^" + escaped + "]*"); // free for all const std::regex regex(regexp); const fs::directory_options options = fs::directory_options::skip_permission_denied | fs::directory_options::follow_directory_symlink; for (fs::directory_entry entry : fs::recursive_directory_iterator(prefix, options)) { if (fs::is_regular_file(entry.path())) { const std::string relative = entry.path().string().substr(prefix.string().length() + 1); std::smatch match; if (!ec && std::regex_match(relative, match, regex)) { result.push_back(symbols->registerSymbol(entry.path().string())); } } } return result; } std::string FileUtils::getFileContent(const std::string& filename) { std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { std::string result; result.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()); return result; } return "FAILED_TO_LOAD_CONTENT"; } std::string FileUtils::getPathName(const std::string& path) { fs::path fs_path(path); return fs_path.has_parent_path() ? (fs::path(path).parent_path() += fs::path::preferred_separator) .string() : ""; } std::string FileUtils::basename(const std::string& str) { return fs::path(str).filename().string(); } std::string FileUtils::getPreferredPath(const std::string& path) { return fs::path(path).make_preferred().string(); } std::string FileUtils::hashPath(const std::string& path) { const std::string separator(1, fs::path::preferred_separator); std::string hashedpath; std::size_t val = std::hash<std::string>{}(path); std::string last_dir = path; if (last_dir.size()) last_dir.erase(last_dir.end() - 1); char c = separator[0]; auto it1 = std::find_if(last_dir.rbegin(), last_dir.rend(), [](char ch) { return (ch == '/' || ch == '\\'); }); if (it1 != last_dir.rend()) last_dir.erase(last_dir.begin(), it1.base()); hashedpath = last_dir + "_" + std::to_string(val) + separator; return hashedpath; } std::string FileUtils::makeRelativePath(const std::string& in_path) { const std::string separator(1, fs::path::preferred_separator); // Standardize it so we can avoid special cases and wildcards! fs::path p(in_path); std::string path = p.make_preferred().string(); // Handle Windows specific absolute paths if (p.is_absolute() && (path.length() > 1) && (path[1] == ':')) path[1] = '$'; // Swap "..\" (or "../") for "__\" (or "__/") path = StringUtils::replaceAll(path, ".." + separator, "__" + separator); // Swap "\.\" (or "/./") for "\" (or "/") path = StringUtils::replaceAll(path, separator + "." + separator, separator); if (path[0] != '.') { if (path[0] != fs::path::preferred_separator) path = separator + path; path = "." + path; } return path; } <commit_msg>Fix compile warnings<commit_after>/* Copyright 2019 Alain Dargelas 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: FileUtils.cpp * Author: alain * * Created on March 16, 2017, 11:02 PM */ #include "Utils/FileUtils.h" #include <errno.h> #include <limits.h> /* PATH_MAX */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <algorithm> #include <fstream> #include <iostream> #include <regex> #include <sstream> #include <string> #include "SourceCompile/SymbolTable.h" #include "Utils/StringUtils.h" #if defined(_MSC_VER) #include <direct.h> #define PATH_MAX _MAX_PATH #else #include <dirent.h> #include <unistd.h> #endif #if (__cplusplus >= 201703L) && __has_include(<filesystem>) #include <filesystem> namespace fs = std::filesystem; #else #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #endif using namespace SURELOG; bool FileUtils::fileExists(const std::string& name) { std::error_code ec; return fs::exists(name, ec); } unsigned long FileUtils::fileSize(const std::string& name) { std::error_code ec; return fs::file_size(name, ec); } bool FileUtils::fileIsDirectory(const std::string& name) { return fs::is_directory(name); } bool FileUtils::fileIsRegular(const std::string& name) { return fs::is_regular_file(name); } SymbolId FileUtils::locateFile(SymbolId file, SymbolTable* symbols, const std::vector<SymbolId>& paths) { const std::string& fileName = symbols->getSymbol(file); if (fileExists(fileName)) { return file; } for (auto id : paths) { const std::string& path = symbols->getSymbol(id); std::string filePath; if (path.size() && (path[path.size() - 1] == '/')) filePath = path + fileName; else filePath = path + "/" + fileName; if (fileExists(filePath)) { return symbols->registerSymbol(filePath); } } return symbols->getBadId(); } int FileUtils::mkDir(const char* path) { // CAUTION: There is a known bug in VC compiler where a trailing // slash in the path will cause a false return from a call to // fs::create_directories. const std::string dirpath(path); fs::create_directories(dirpath); return fs::is_directory(dirpath) ? 0 : -1; } int FileUtils::rmDir(const char* path) { const std::string dirpath(path); return fs::remove_all(dirpath); } std::string FileUtils::getFullPath(const std::string& path) { std::error_code ec; fs::path fullPath = fs::canonical(path, ec); return ec ? path : fullPath.string(); } bool FileUtils::getFullPath(const std::string& path, std::string* result) { std::error_code ec; fs::path fullPath = fs::canonical(path, ec); bool found = (!ec && fileIsRegular(fullPath.string())); if (result != nullptr) { *result = found ? fullPath.string() : path; } return found; } static bool has_suffix(const std::string& s, const std::string& suffix) { return (s.size() >= suffix.size()) && equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } std::vector<SymbolId> FileUtils::collectFiles(SymbolId dirPath, SymbolId ext, SymbolTable* symbols) { return collectFiles(symbols->getSymbol(dirPath), symbols->getSymbol(ext), symbols); } std::vector<SymbolId> FileUtils::collectFiles(const std::string& dirPath, const std::string& ext, SymbolTable* symbols) { std::vector<SymbolId> result; if (fileIsDirectory(dirPath)) { for (fs::directory_entry entry : fs::directory_iterator(dirPath)) { const std::string filepath = entry.path().string(); if (has_suffix(filepath, ext)) { result.push_back(symbols->registerSymbol(filepath)); } } } return result; } std::vector<SymbolId> FileUtils::collectFiles(const std::string& pathSpec, SymbolTable* const symbols) { // ? single character wildcard (matches any single character) // * multiple character wildcard (matches any number of characters in a // directory/file name) // ... hierarchical wildcard (matches any number of hierarchical directories) // .. specifies the parent directory // . specifies the directory containing the lib.map // Paths that end in / shall include all files in the specified directory. // Identical to / * Paths that do not begin with / are relative to the // directory in which the current lib.map file is located. std::vector<SymbolId> result; std::error_code ec; fs::path path(pathSpec); if (!path.is_absolute()) { path = fs::current_path(ec) / path; if (ec) return result; } path.make_preferred(); fs::path prefix; fs::path suffix; for (const fs::path& subpath : path) { const std::string substr = subpath.string(); if (substr.compare(".") == 0) continue; else if (!suffix.empty()) suffix /= subpath; else if (substr.find_first_of(".?*") == std::string::npos) prefix /= subpath; else suffix /= subpath; } prefix = fs::canonical(prefix, ec); if (ec) return result; if (suffix.empty()) suffix /= "*"; const std::string separator(1, fs::path::preferred_separator); const std::string escaped = "\\" + separator; std::string regexp = suffix.string(); regexp = StringUtils::replaceAll(regexp, separator, escaped); // escape separators regexp = StringUtils::replaceAll( regexp, "..." + escaped, R"([a-zA-Z0-9_\-.)" + escaped + R"(]+)" + escaped); // separator allowed regexp = StringUtils::replaceAll(regexp, ".." + escaped, R"([a-zA-Z0-9_\-.]+)" + escaped + R"([a-zA-Z0-9_\-.]+)" + escaped); // separator NOT allowed regexp = StringUtils::replaceAll(regexp, ".", "\\."); // escape it regexp = StringUtils::replaceAll(regexp, "?", R"([a-zA-Z0-9_\-\.])"); // at most one regexp = StringUtils::replaceAll(regexp, "*", "[^" + escaped + "]*"); // free for all const std::regex regex(regexp); const fs::directory_options options = fs::directory_options::skip_permission_denied | fs::directory_options::follow_directory_symlink; for (fs::directory_entry entry : fs::recursive_directory_iterator(prefix, options)) { if (fs::is_regular_file(entry.path())) { const std::string relative = entry.path().string().substr(prefix.string().length() + 1); std::smatch match; if (!ec && std::regex_match(relative, match, regex)) { result.push_back(symbols->registerSymbol(entry.path().string())); } } } return result; } std::string FileUtils::getFileContent(const std::string& filename) { std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { std::string result; result.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()); return result; } return "FAILED_TO_LOAD_CONTENT"; } std::string FileUtils::getPathName(const std::string& path) { fs::path fs_path(path); return fs_path.has_parent_path() ? (fs::path(path).parent_path() += fs::path::preferred_separator) .string() : ""; } std::string FileUtils::basename(const std::string& str) { return fs::path(str).filename().string(); } std::string FileUtils::getPreferredPath(const std::string& path) { return fs::path(path).make_preferred().string(); } std::string FileUtils::hashPath(const std::string& path) { const std::string separator(1, fs::path::preferred_separator); std::string hashedpath; std::size_t val = std::hash<std::string>{}(path); std::string last_dir = path; if (last_dir.size()) last_dir.erase(last_dir.end() - 1); auto it1 = std::find_if(last_dir.rbegin(), last_dir.rend(), [](char ch) { return (ch == '/' || ch == '\\'); }); if (it1 != last_dir.rend()) last_dir.erase(last_dir.begin(), it1.base()); hashedpath = last_dir + "_" + std::to_string(val) + separator; return hashedpath; } std::string FileUtils::makeRelativePath(const std::string& in_path) { const std::string separator(1, fs::path::preferred_separator); // Standardize it so we can avoid special cases and wildcards! fs::path p(in_path); std::string path = p.make_preferred().string(); // Handle Windows specific absolute paths if (p.is_absolute() && (path.length() > 1) && (path[1] == ':')) path[1] = '$'; // Swap "..\" (or "../") for "__\" (or "__/") path = StringUtils::replaceAll(path, ".." + separator, "__" + separator); // Swap "\.\" (or "/./") for "\" (or "/") path = StringUtils::replaceAll(path, separator + "." + separator, separator); if (path[0] != '.') { if (path[0] != fs::path::preferred_separator) path = separator + path; path = "." + path; } return path; } <|endoftext|>
<commit_before>#include "VideoCaptureWrap.h" #include "Matrix.h" #include "OpenCV.h" #include <iostream> using namespace std; void AsyncRead(uv_work_t *req); void AfterAsyncRead(uv_work_t *req); v8::Persistent<FunctionTemplate> VideoCaptureWrap::constructor; struct videocapture_baton { Persistent<Function> cb; VideoCaptureWrap *vc; Matrix *im; uv_work_t request; }; void VideoCaptureWrap::Init(Handle<Object> target) { NanScope(); // Prototype //Local<ObjectTemplate> proto = constructor->PrototypeTemplate(); //Class Local<FunctionTemplate> ctor = NanNew<FunctionTemplate>(VideoCaptureWrap::New); NanAssignPersistent(constructor, ctor); ctor->InstanceTemplate()->SetInternalFieldCount(1); ctor->SetClassName(NanNew("VideoCapture")); NODE_SET_PROTOTYPE_METHOD(ctor, "read", Read); NODE_SET_PROTOTYPE_METHOD(ctor, "setWidth", SetWidth); NODE_SET_PROTOTYPE_METHOD(ctor, "setHeight", SetHeight); NODE_SET_PROTOTYPE_METHOD(ctor, "setPosition", SetPosition); NODE_SET_PROTOTYPE_METHOD(ctor, "close", Close); NODE_SET_PROTOTYPE_METHOD(ctor, "ReadSync", ReadSync); target->Set(NanNew("VideoCapture"), ctor->GetFunction()); }; NAN_METHOD(VideoCaptureWrap::New) { NanScope(); if (args.This()->InternalFieldCount() == 0) return NanThrowTypeError("Cannot Instantiate without new"); VideoCaptureWrap *v; if (args[0]->IsNumber()){ v = new VideoCaptureWrap(args[0]->NumberValue()); } else { //TODO - assumes that we have string, verify v = new VideoCaptureWrap(std::string(*NanAsciiString(args[0]->ToString()))); } v->Wrap(args.This()); NanReturnValue(args.This()); } VideoCaptureWrap::VideoCaptureWrap(int device){ NanScope(); cap.open(device); if(!cap.isOpened()){ NanThrowError("Camera could not be opened"); } } VideoCaptureWrap::VideoCaptureWrap(const std::string& filename){ NanScope(); cap.open(filename); // TODO! At the moment this only takes a full path - do relative too. if(!cap.isOpened()){ NanThrowError("Video file could not be opened (opencv reqs. non relative paths)"); } } NAN_METHOD(VideoCaptureWrap::SetWidth){ NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); if(args.Length() != 1) NanReturnUndefined(); int w = args[0]->IntegerValue(); if(v->cap.isOpened()) v->cap.set(CV_CAP_PROP_FRAME_WIDTH, w); NanReturnUndefined(); } NAN_METHOD(VideoCaptureWrap::SetHeight){ NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); if(args.Length() != 1) NanReturnUndefined(); int h = args[0]->IntegerValue(); v->cap.set(CV_CAP_PROP_FRAME_HEIGHT, h); NanReturnUndefined(); } NAN_METHOD(VideoCaptureWrap::SetPosition){ NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); if(args.Length() != 1) NanReturnUndefined(); int pos = args[0]->IntegerValue(); v->cap.set(CV_CAP_PROP_POS_FRAMES, pos); NanReturnUndefined(); } NAN_METHOD(VideoCaptureWrap::Close){ NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); v->cap.release(); NanReturnUndefined(); } /*FIXME: migrate async method NAN_METHOD(VideoCaptureWrap::Read) { NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); REQ_FUN_ARG(0, cb); videocapture_baton *baton = new videocapture_baton(); baton->vc = v; baton->cb = Persistent<Function>::New(cb); baton->im = new Matrix(); baton->request.data = baton; uv_queue_work(uv_default_loop(), &baton->request, AsyncRead, (uv_after_work_cb)AfterAsyncRead); NanReturnUndefined(); } void AsyncRead(uv_work_t *req) { videocapture_baton *baton = static_cast<videocapture_baton *>(req->data); baton->vc->cap.read(baton->im->mat); } void AfterAsyncRead(uv_work_t *req) { NanScope(); videocapture_baton *baton = static_cast<videocapture_baton *>(req->data); Local<Object> im_to_return= Matrix::constructor->GetFunction()->NewInstance(); Matrix *img = ObjectWrap::Unwrap<Matrix>(im_to_return); cv::Mat mat; mat = baton->im->mat; img->mat = mat; Local<Value> argv[2]; argv[0] = Local<Value>::New(Null()); argv[1] = im_to_return; baton->cb->Call(Context::GetCurrent()->Global(), 2, argv); baton->cb.Dispose(); delete baton; } */ NAN_METHOD(VideoCaptureWrap::ReadSync) { NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); Local<Object> im_to_return= NanNew(Matrix::constructor)->GetFunction()->NewInstance(); Matrix *img = ObjectWrap::Unwrap<Matrix>(im_to_return); v->cap.read(img->mat); NanReturnValue(im_to_return); } <commit_msg>- migrate the async methods of VideoCaptureWrap to NAN<commit_after>#include "VideoCaptureWrap.h" #include "Matrix.h" #include "OpenCV.h" #include <iostream> using namespace std; void AsyncRead(uv_work_t *req); void AfterAsyncRead(uv_work_t *req); v8::Persistent<FunctionTemplate> VideoCaptureWrap::constructor; struct videocapture_baton { Persistent<Function> cb; VideoCaptureWrap *vc; Matrix *im; uv_work_t request; }; void VideoCaptureWrap::Init(Handle<Object> target) { NanScope(); //Class Local<FunctionTemplate> ctor = NanNew<FunctionTemplate>(VideoCaptureWrap::New); NanAssignPersistent(constructor, ctor); ctor->InstanceTemplate()->SetInternalFieldCount(1); ctor->SetClassName(NanNew("VideoCapture")); // Prototype //Local<ObjectTemplate> proto = constructor->PrototypeTemplate(); NODE_SET_PROTOTYPE_METHOD(ctor, "read", Read); NODE_SET_PROTOTYPE_METHOD(ctor, "setWidth", SetWidth); NODE_SET_PROTOTYPE_METHOD(ctor, "setHeight", SetHeight); NODE_SET_PROTOTYPE_METHOD(ctor, "setPosition", SetPosition); NODE_SET_PROTOTYPE_METHOD(ctor, "close", Close); NODE_SET_PROTOTYPE_METHOD(ctor, "ReadSync", ReadSync); target->Set(NanNew("VideoCapture"), ctor->GetFunction()); }; NAN_METHOD(VideoCaptureWrap::New) { NanScope(); if (args.This()->InternalFieldCount() == 0) return NanThrowTypeError("Cannot Instantiate without new"); VideoCaptureWrap *v; if (args[0]->IsNumber()){ v = new VideoCaptureWrap(args[0]->NumberValue()); } else { //TODO - assumes that we have string, verify v = new VideoCaptureWrap(std::string(*NanAsciiString(args[0]->ToString()))); } v->Wrap(args.This()); NanReturnValue(args.This()); } VideoCaptureWrap::VideoCaptureWrap(int device){ NanScope(); cap.open(device); if(!cap.isOpened()){ NanThrowError("Camera could not be opened"); } } VideoCaptureWrap::VideoCaptureWrap(const std::string& filename){ NanScope(); cap.open(filename); // TODO! At the moment this only takes a full path - do relative too. if(!cap.isOpened()){ NanThrowError("Video file could not be opened (opencv reqs. non relative paths)"); } } NAN_METHOD(VideoCaptureWrap::SetWidth){ NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); if(args.Length() != 1) NanReturnUndefined(); int w = args[0]->IntegerValue(); if(v->cap.isOpened()) v->cap.set(CV_CAP_PROP_FRAME_WIDTH, w); NanReturnUndefined(); } NAN_METHOD(VideoCaptureWrap::SetHeight){ NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); if(args.Length() != 1) NanReturnUndefined(); int h = args[0]->IntegerValue(); v->cap.set(CV_CAP_PROP_FRAME_HEIGHT, h); NanReturnUndefined(); } NAN_METHOD(VideoCaptureWrap::SetPosition){ NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); if(args.Length() != 1) NanReturnUndefined(); int pos = args[0]->IntegerValue(); v->cap.set(CV_CAP_PROP_POS_FRAMES, pos); NanReturnUndefined(); } NAN_METHOD(VideoCaptureWrap::Close){ NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); v->cap.release(); NanReturnUndefined(); } class AsyncVCWorker : public NanAsyncWorker { public: AsyncVCWorker(NanCallback *callback, VideoCaptureWrap* vc, Matrix* matrix) : NanAsyncWorker(callback), vc(vc), matrix(matrix) {} ~AsyncVCWorker() {} // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute () { this->vc->cap.read(matrix->mat); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback () { NanScope(); Local<Object> im_to_return= NanNew(Matrix::constructor)->GetFunction()->NewInstance(); Matrix *img = ObjectWrap::Unwrap<Matrix>(im_to_return); cv::Mat mat; mat = this->matrix->mat; img->mat = mat; Local<Value> argv[] = { NanNull() , im_to_return }; TryCatch try_catch; callback->Call(2, argv); if (try_catch.HasCaught()) { FatalException(try_catch); } } private: VideoCaptureWrap *vc; Matrix* matrix; int res; }; NAN_METHOD(VideoCaptureWrap::Read) { NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); REQ_FUN_ARG(0, cb); NanCallback *callback = new NanCallback(cb.As<Function>()); NanAsyncQueueWorker(new AsyncVCWorker(callback, v, new Matrix())); NanReturnUndefined(); } NAN_METHOD(VideoCaptureWrap::ReadSync) { NanScope(); VideoCaptureWrap *v = ObjectWrap::Unwrap<VideoCaptureWrap>(args.This()); Local<Object> im_to_return= NanNew(Matrix::constructor)->GetFunction()->NewInstance(); Matrix *img = ObjectWrap::Unwrap<Matrix>(im_to_return); v->cap.read(img->mat); NanReturnValue(im_to_return); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <stdexcept> #include <string> #include <vector> #include <algorithm> #include <functional> #include <unordered_map> #include <boost/program_options.hpp> #include "global.hpp" #include "operators.hpp" #include "tokens.hpp" #include "nodes.hpp" #include "builtins.hpp" #include "operator_maps.hpp" namespace lang { class Parser { private: std::vector<Token> tokens {}; inline void skipCharacters(unsigned int& i, int by) {i += by;} // If we're already at the next character, but the loop will increment i by 1 inline void preventIncrement(unsigned int& i) {i--;} std::vector<Token> variables {}; std::vector<std::string> keywords {"define", "if", "while"}; std::vector<std::string> constructKeywords {"do", "end", "else"}; public: AST tree = AST(); Parser(std::string code) { if (PARSER_PRINT_INPUT) print(code, "\n"); try { tokenize(code); if (PARSER_PRINT_TOKENS) for (auto tok : tokens) print(tok, "\n"); if (PARSER_PRINT_AS_EXPR) for (auto tok : ExpressionNode(tokens).getRPNOutput()) print(tok.data, " "); buildTree(tokens); } catch (Error &e) { print(e.toString()); } } void tokenize(std::string code) { unsigned int lines = 0; for (unsigned int i = 0; i < code.length(); ++i) { if (code[i] == '/' && code[i + 1] == '/') while(code[i] != '\n' && code[i] != '\0') skipCharacters(i, 1); if (code[i] == '\n') lines++; // Ignore whitespace if (isspace(code[i])) continue; // Block begin/end // Parenthesis // Semicolons if (code[i] == '{' || code[i] == '}' || code[i] == '(' || code[i] == ')' || code[i] == ';') { tokens.push_back(Token(std::string(1, code[i]), CONSTRUCT, lines)); continue; } // Operators auto initTokSize = tokens.size(); std::for_each(opList.begin(), opList.end(), [this, initTokSize, code, i, lines](Operator& op) { if (initTokSize < tokens.size()) return; // If there are more tokens than before for_each, the operator was already added, so return. if (op.toString().length() + i > code.length()) return; // If the operator is longer than the source string, ignore it. if (op.toString() == code.substr(i, op.toString().length())) { Operator* tmp = &op; // TODO: apply DRY on these ifs if (tmp->toString() == "++" || tmp->toString() == "--") { // Prefix version if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = new Operator(tmp->toString(), 12, ASSOCIATE_FROM_RIGHT, UNARY); // Postfix version else tmp = new Operator(tmp->toString(), 13, ASSOCIATE_FROM_LEFT, UNARY); } if (tmp->toString() == "+" || tmp->toString() == "-") { // Unary version if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = new Operator(tmp->toString(), 12, ASSOCIATE_FROM_RIGHT, UNARY); // Binary version else tmp = new Operator(tmp->toString(), 10); } if (PARSER_PRINT_OPERATOR_TOKENS) print("Parser found Token with Operator ", *tmp, ", at address ", tmp, "\n"); tokens.push_back(Token(tmp, OPERATOR, lines)); } }); if (initTokSize < tokens.size()) { skipCharacters(i, tokens.back().data.length() - 1); continue; // Token added, continue. } // Numbers if (isdigit(code[i])) { int base = 10; std::string current = ""; if (code[i] == '0') { switch (code[i + 1]) { case 'x': base = 16; skipCharacters(i, 2); break; case 'b': base = 2; skipCharacters(i, 2); break; case 'o': base = 8; skipCharacters(i, 2); break; default: break; } } bool isFloat = false; while (isdigit(code[i]) || code[i] == '.') { current += code[i]; if (code[i] == '.') { if (isFloat) throw Error("Malformed float, multiple decimal points: \"" + current + "\"", "SyntaxError", lines); isFloat = true; } skipCharacters(i, 1); } preventIncrement(i); if (current[current.length() - 1] == '.') throw Error("Malformed float, missing digits after decimal point: \"" + current + "\"", "SyntaxError", lines); if (base != 10 && isFloat) throw Error("Floating point numbers must be used with base 10 numbers: \"" + current + "\"", "SyntaxError", lines); Token t; if (isFloat) t = Token(new Float(current), FLOAT, lines); else t = Token(new Integer(current, base), INTEGER, lines); tokens.push_back(t); continue; } // String literals if (code[i] == '"') { skipCharacters(i, 1); // Skip the double quote std::string current = ""; while (code[i] != '"') { // TODO: add escape sequences current += code[i]; skipCharacters(i, 1); } // Don't call preventIncrement here so the other double quote is skipped tokens.push_back(Token(new String(current), STRING, lines)); continue; } // Others Token token = Token(); while (!isspace(code[i])) { if (isReservedChar(code[i]) || code[i] == '\0') break; token.data += code[i]; skipCharacters(i, 1); } // Check if the thing is a Boolean if (token.data == "true" || token.data == "false") { token.type = BOOLEAN; token.typeData = new Boolean(token.data); } // Check if the thing references a variable for (auto tok : variables) if (tok.data == token.data) { token = tok; break; } // Check if the thing is a new variable if (tokens.size() > 0 && ((tokens.back().type == KEYWORD && tokens.back().data == "define") || tokens.back().type == TYPE)) { token.type = VARIABLE; variables.push_back(token); } // Check if the thing is a keyword if (contains(token.data, keywords)) token.type = KEYWORD; if (contains(token.data, constructKeywords)) token.type = CONSTRUCT; // Push token preventIncrement(i); token.line = lines; tokens.push_back(token); } } ExpressionNode* evaluateCondition(std::vector<Token>& toks) { std::vector<Token> exprToks = std::vector<Token>(toks.begin() + 1, toks.end() - 1); ExpressionNode* condition = new ExpressionNode(exprToks); condition->buildSubtree(); return condition; } void buildTree(std::vector<Token> tokens) { static std::vector<BlockNode*> blockStack {}; auto addToBlock = [this](ASTNode* child) { if (blockStack.size() == 0) tree.addRootChild(child); else blockStack.back()->addChild(child); }; auto logicalLines = splitVector(tokens, isNewLine); for (uint64 i = 0; i < logicalLines.size(); i++) { std::vector<Token>& toks = logicalLines[i]; if (toks.size() == 0) continue; // TODO: check for solid types here as well if (toks[0].data == "define" && toks[0].type == KEYWORD) { DeclarationNode* decl = new DeclarationNode("define", toks[1]); decl->setLineNumber(toks[1].line); if (toks[2].data != ";" || toks[2].type != CONSTRUCT) { std::vector<Token> exprToks(toks.begin() + 1, toks.end()); ExpressionNode* expr = new ExpressionNode(exprToks); expr->buildSubtree(); decl->addChild(expr); } if (PARSER_PRINT_DECL_TREE) decl->printTree(blockStack.size()); addToBlock(decl); } else if (toks[0].data == "while" && toks[0].type == KEYWORD) { auto wBlock = new WhileNode(evaluateCondition(toks), new BlockNode()); if (PARSER_PRINT_WHILE_TREE) wBlock->printTree(blockStack.size()); addToBlock(wBlock); blockStack.push_back(wBlock); } else if (toks[0].data == "if" && toks[0].type == KEYWORD) { auto cBlock = new ConditionalNode(evaluateCondition(toks), new BlockNode(), new BlockNode()); if (PARSER_PRINT_COND_TREE) cBlock->printTree(blockStack.size()); addToBlock(cBlock); blockStack.push_back(cBlock); } else if (toks[0].data == "else" && toks[0].type == CONSTRUCT) { auto cNode = dynamic_cast<ConditionalNode*>(blockStack.back()); if (cNode == nullptr) throw Error("Cannot find conditional structure for token `else`", "SyntaxError", blockStack.back()->getLineNumber()); cNode->nextBlock(); } else if (toks[0].data == "end" && toks[0].type == CONSTRUCT) { blockStack.pop_back(); } else { ExpressionNode* expr = new ExpressionNode(toks); expr->buildSubtree(); expr->setLineNumber(dynamic_cast<ExpressionChildNode*>(expr->getChildren()[0])->t.line); if (PARSER_PRINT_EXPR_TREE) expr->printTree(blockStack.size()); addToBlock(expr); } } } std::vector<Token> getTokens() { return tokens; } }; class Interpreter { private: AST tree; public: Interpreter(AST tree): tree(tree) { interpret(tree.getRootChildren()); } private: void interpret(ChildrenNodes nodes) { for (uint64 i = 0; i < nodes.size(); ++i) { auto nodeType = nodes[i]->getNodeType(); if (nodeType == "ExpressionNode") { interpretExpression(dynamic_cast<ExpressionChildNode*>(nodes[i]->getChildren()[0]))->printTree(0); } else if (nodeType == "DeclarationNode") { registerDeclaration(dynamic_cast<DeclarationNode*>(nodes[i])); } else if (nodeType == "ConditionalNode") { resolveCondition(dynamic_cast<ConditionalNode*>(nodes[i])); } else if (nodeType == "WhileNode") { doWhileLoop(dynamic_cast<WhileNode*>(nodes[i])); } } } void doWhileLoop(WhileNode* node) { while (true) { auto condition = interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getCondition()->getChild())); if (!static_cast<Object*>(condition->t.typeData)->isTruthy()) break; interpret(node->getLoopNode()->getChildren()); } } void resolveCondition(ConditionalNode* node) { auto condRes = interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getCondition()->getChild())); if (static_cast<Object*>(condRes->t.typeData)->isTruthy()) { interpret(node->getTrueBlock()->getChildren()); } else { interpret(node->getFalseBlock()->getChildren()); } } void registerDeclaration(DeclarationNode* node) { node->getParentScope()->insert({node->identifier.data, new Variable()}); if (node->getChildren().size() == 1) { (*node->getParentScope())[node->identifier.data]->assign( static_cast<Object*>(interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getChild()->getChildren()[0]))->t.typeData) ); } } ExpressionChildNode* interpretExpression(ExpressionChildNode* node) { if (node->getChildren().size() == 0) return node; if (node->t.type == OPERATOR) { ExpressionChildNode* processed = new ExpressionChildNode(node->t); processed->setParent(node->getParent()); auto ch = node->getChildren(); std::for_each(ch.begin(), ch.end(), [=](ASTNode*& n) { auto node = dynamic_cast<ExpressionChildNode*>(n); if (node->getChildren().size() != 0) processed->addChild(interpretExpression(node)); else processed->addChild(node); }); return new ExpressionChildNode(Token(runOperator(processed), UNPROCESSED, PHONY_TOKEN)); } throw std::runtime_error("Wrong type of token.\n"); } }; } /* namespace lang */ int interpretCode() { try { lang::Parser a(INPUT); lang::Interpreter in(a.tree); } catch(Error& e) { print(e.toString()); return ERROR_CODE_FAILED; } catch(std::runtime_error& re) { print(re.what(), "\n"); return ERROR_INTERNAL; } return 0; } int main(int argc, char** argv) { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "display this help") ("use-existing,c", "use constants.data and inputs.data") ("evaluate,e", po::value<std::string>(), "use to evaluate code from the command line") ("read-file,f", po::value<std::string>(), "use to evaluate code from a file at the specified path") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { print(desc, "\n"); return 0; } if (vm.count("use-existing")) { getConstants(); return interpretCode(); } else if (vm.count("evaluate")) { INPUT = vm["evaluate"].as<std::string>(); return interpretCode(); } else if (vm.count("read-file")) { std::ifstream in(vm["read-file"].as<std::string>()); std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); INPUT = contents; return interpretCode(); } else { print(desc, "\n"); return ERROR_BAD_INPUT; } return 0; } <commit_msg>Parser and Interpreter now recognize types<commit_after>#include <iostream> #include <fstream> #include <stdexcept> #include <string> #include <vector> #include <algorithm> #include <functional> #include <unordered_map> #include <boost/program_options.hpp> #include "global.hpp" #include "operators.hpp" #include "tokens.hpp" #include "nodes.hpp" #include "builtins.hpp" #include "operator_maps.hpp" namespace lang { class Parser { private: std::vector<Token> tokens {}; inline void skipCharacters(unsigned int& i, int by) {i += by;} // If we're already at the next character, but the loop will increment i by 1 inline void preventIncrement(unsigned int& i) {i--;} std::vector<Token> variables {}; std::vector<std::string> types {"Integer"}; std::vector<std::string> keywords {"define", "if", "while"}; std::vector<std::string> constructKeywords {"do", "end", "else"}; public: AST tree = AST(); Parser(std::string code) { if (PARSER_PRINT_INPUT) print(code, "\n"); try { tokenize(code); if (PARSER_PRINT_TOKENS) for (auto tok : tokens) print(tok, "\n"); if (PARSER_PRINT_AS_EXPR) for (auto tok : ExpressionNode(tokens).getRPNOutput()) print(tok.data, " "); buildTree(tokens); } catch (Error &e) { print(e.toString()); } } void tokenize(std::string code) { unsigned int lines = 0; for (unsigned int i = 0; i < code.length(); ++i) { if (code[i] == '/' && code[i + 1] == '/') while(code[i] != '\n' && code[i] != '\0') skipCharacters(i, 1); if (code[i] == '\n') lines++; // Ignore whitespace if (isspace(code[i])) continue; // Block begin/end // Parenthesis // Semicolons if (code[i] == '{' || code[i] == '}' || code[i] == '(' || code[i] == ')' || code[i] == ';') { tokens.push_back(Token(std::string(1, code[i]), CONSTRUCT, lines)); continue; } // Operators auto initTokSize = tokens.size(); std::for_each(opList.begin(), opList.end(), [this, initTokSize, code, i, lines](Operator& op) { if (initTokSize < tokens.size()) return; // If there are more tokens than before for_each, the operator was already added, so return. if (op.toString().length() + i > code.length()) return; // If the operator is longer than the source string, ignore it. if (op.toString() == code.substr(i, op.toString().length())) { Operator* tmp = &op; // TODO: apply DRY on these ifs if (tmp->toString() == "++" || tmp->toString() == "--") { // Prefix version if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = new Operator(tmp->toString(), 12, ASSOCIATE_FROM_RIGHT, UNARY); // Postfix version else tmp = new Operator(tmp->toString(), 13, ASSOCIATE_FROM_LEFT, UNARY); } if (tmp->toString() == "+" || tmp->toString() == "-") { // Unary version if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = new Operator(tmp->toString(), 12, ASSOCIATE_FROM_RIGHT, UNARY); // Binary version else tmp = new Operator(tmp->toString(), 10); } if (PARSER_PRINT_OPERATOR_TOKENS) print("Parser found Token with Operator ", *tmp, ", at address ", tmp, "\n"); tokens.push_back(Token(tmp, OPERATOR, lines)); } }); if (initTokSize < tokens.size()) { skipCharacters(i, tokens.back().data.length() - 1); continue; // Token added, continue. } // Numbers if (isdigit(code[i])) { int base = 10; std::string current = ""; if (code[i] == '0') { switch (code[i + 1]) { case 'x': base = 16; skipCharacters(i, 2); break; case 'b': base = 2; skipCharacters(i, 2); break; case 'o': base = 8; skipCharacters(i, 2); break; default: break; } } bool isFloat = false; while (isdigit(code[i]) || code[i] == '.') { current += code[i]; if (code[i] == '.') { if (isFloat) throw Error("Malformed float, multiple decimal points: \"" + current + "\"", "SyntaxError", lines); isFloat = true; } skipCharacters(i, 1); } preventIncrement(i); if (current[current.length() - 1] == '.') throw Error("Malformed float, missing digits after decimal point: \"" + current + "\"", "SyntaxError", lines); if (base != 10 && isFloat) throw Error("Floating point numbers must be used with base 10 numbers: \"" + current + "\"", "SyntaxError", lines); Token t; if (isFloat) t = Token(new Float(current), FLOAT, lines); else t = Token(new Integer(current, base), INTEGER, lines); tokens.push_back(t); continue; } // String literals if (code[i] == '"') { skipCharacters(i, 1); // Skip the double quote std::string current = ""; while (code[i] != '"') { // TODO: add escape sequences current += code[i]; skipCharacters(i, 1); } // Don't call preventIncrement here so the other double quote is skipped tokens.push_back(Token(new String(current), STRING, lines)); continue; } // Others Token token = Token(); while (!isspace(code[i])) { if (isReservedChar(code[i]) || code[i] == '\0') break; token.data += code[i]; skipCharacters(i, 1); } // TODO: identify type definitions here // Check if the thing references a type if (contains(token.data, types)) { token.type = TYPE; } // Check if the thing is a Boolean if (token.data == "true" || token.data == "false") { token.type = BOOLEAN; token.typeData = new Boolean(token.data); } // Check if the thing references a variable for (auto tok : variables) if (tok.data == token.data) { token = tok; break; } // Check if the thing is a new variable if (tokens.size() > 0 && ((tokens.back().type == KEYWORD && tokens.back().data == "define") || tokens.back().type == TYPE)) { token.type = VARIABLE; variables.push_back(token); } // Check if the thing is a keyword if (contains(token.data, keywords)) token.type = KEYWORD; if (contains(token.data, constructKeywords)) token.type = CONSTRUCT; // Push token preventIncrement(i); token.line = lines; tokens.push_back(token); } } ExpressionNode* evaluateCondition(std::vector<Token>& toks) { std::vector<Token> exprToks = std::vector<Token>(toks.begin() + 1, toks.end() - 1); ExpressionNode* condition = new ExpressionNode(exprToks); condition->buildSubtree(); return condition; } void buildTree(std::vector<Token> tokens) { static std::vector<BlockNode*> blockStack {}; auto addToBlock = [this](ASTNode* child) { if (blockStack.size() == 0) tree.addRootChild(child); else blockStack.back()->addChild(child); }; auto logicalLines = splitVector(tokens, isNewLine); for (uint64 i = 0; i < logicalLines.size(); i++) { std::vector<Token>& toks = logicalLines[i]; if (toks.size() == 0) continue; if ((toks[0].data == "define" && toks[0].type == KEYWORD) || toks[0].type == TYPE) { DeclarationNode* decl = new DeclarationNode(toks[0].data, toks[1]); decl->setLineNumber(toks[1].line); if (toks[2].data != ";" || toks[2].type != CONSTRUCT) { std::vector<Token> exprToks(toks.begin() + 1, toks.end()); ExpressionNode* expr = new ExpressionNode(exprToks); expr->buildSubtree(); decl->addChild(expr); } if (PARSER_PRINT_DECL_TREE) decl->printTree(blockStack.size()); addToBlock(decl); } else if (toks[0].data == "while" && toks[0].type == KEYWORD) { auto wBlock = new WhileNode(evaluateCondition(toks), new BlockNode()); if (PARSER_PRINT_WHILE_TREE) wBlock->printTree(blockStack.size()); addToBlock(wBlock); blockStack.push_back(wBlock); } else if (toks[0].data == "if" && toks[0].type == KEYWORD) { auto cBlock = new ConditionalNode(evaluateCondition(toks), new BlockNode(), new BlockNode()); if (PARSER_PRINT_COND_TREE) cBlock->printTree(blockStack.size()); addToBlock(cBlock); blockStack.push_back(cBlock); } else if (toks[0].data == "else" && toks[0].type == CONSTRUCT) { auto cNode = dynamic_cast<ConditionalNode*>(blockStack.back()); if (cNode == nullptr) throw Error("Cannot find conditional structure for token `else`", "SyntaxError", blockStack.back()->getLineNumber()); cNode->nextBlock(); } else if (toks[0].data == "end" && toks[0].type == CONSTRUCT) { blockStack.pop_back(); } else { ExpressionNode* expr = new ExpressionNode(toks); expr->buildSubtree(); expr->setLineNumber(dynamic_cast<ExpressionChildNode*>(expr->getChildren()[0])->t.line); if (PARSER_PRINT_EXPR_TREE) expr->printTree(blockStack.size()); addToBlock(expr); } } } std::vector<Token> getTokens() { return tokens; } }; class Interpreter { private: AST tree; public: Interpreter(AST tree): tree(tree) { interpret(tree.getRootChildren()); } private: void interpret(ChildrenNodes nodes) { for (uint64 i = 0; i < nodes.size(); ++i) { auto nodeType = nodes[i]->getNodeType(); if (nodeType == "ExpressionNode") { interpretExpression(dynamic_cast<ExpressionChildNode*>(nodes[i]->getChildren()[0]))->printTree(0); } else if (nodeType == "DeclarationNode") { registerDeclaration(dynamic_cast<DeclarationNode*>(nodes[i])); } else if (nodeType == "ConditionalNode") { resolveCondition(dynamic_cast<ConditionalNode*>(nodes[i])); } else if (nodeType == "WhileNode") { doWhileLoop(dynamic_cast<WhileNode*>(nodes[i])); } } } void doWhileLoop(WhileNode* node) { while (true) { auto condition = interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getCondition()->getChild())); if (!static_cast<Object*>(condition->t.typeData)->isTruthy()) break; interpret(node->getLoopNode()->getChildren()); } } void resolveCondition(ConditionalNode* node) { auto condRes = interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getCondition()->getChild())); if (static_cast<Object*>(condRes->t.typeData)->isTruthy()) { interpret(node->getTrueBlock()->getChildren()); } else { interpret(node->getFalseBlock()->getChildren()); } } void registerDeclaration(DeclarationNode* node) { if (node->typeName == "define") node->getParentScope()->insert({node->identifier.data, new Variable(nullptr, {"define"})}); else { Type* type = dynamic_cast<Type*>(resolveNameFrom(node, node->typeName)->read()); node->getParentScope()->insert({node->identifier.data, new Variable(type->createInstance(), {node->typeName/*TODO: type list*/})}); } if (node->getChildren().size() == 1) { Variable* variable = (*node->getParentScope())[node->identifier.data]; Object* toAssign = static_cast<Object*>(interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getChild()->getChildren()[0]))->t.typeData); if (!contains(std::string("define"), variable->getTypes()) && !contains(toAssign->getTypeData(), variable->getTypes())) throw Error("Invalid assignment of type " + toAssign->getTypeData() + " to variable " + node->identifier.data, "TypeError", node->getLineNumber()); variable->assign(toAssign); } } ExpressionChildNode* interpretExpression(ExpressionChildNode* node) { if (node->getChildren().size() == 0) return node; if (node->t.type == OPERATOR) { ExpressionChildNode* processed = new ExpressionChildNode(node->t); processed->setParent(node->getParent()); auto ch = node->getChildren(); std::for_each(ch.begin(), ch.end(), [=](ASTNode*& n) { auto node = dynamic_cast<ExpressionChildNode*>(n); if (node->getChildren().size() != 0) processed->addChild(interpretExpression(node)); else processed->addChild(node); }); return new ExpressionChildNode(Token(runOperator(processed), UNPROCESSED, PHONY_TOKEN)); } throw std::runtime_error("Wrong type of token.\n"); } }; } /* namespace lang */ int interpretCode() { try { lang::Parser a(INPUT); lang::Interpreter in(a.tree); } catch(Error& e) { print(e.toString()); return ERROR_CODE_FAILED; } catch(std::runtime_error& re) { print(re.what(), "\n"); return ERROR_INTERNAL; } return 0; } int main(int argc, char** argv) { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "display this help") ("use-existing,c", "use constants.data and inputs.data") ("evaluate,e", po::value<std::string>(), "use to evaluate code from the command line") ("read-file,f", po::value<std::string>(), "use to evaluate code from a file at the specified path") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { print(desc, "\n"); return 0; } if (vm.count("use-existing")) { getConstants(); return interpretCode(); } else if (vm.count("evaluate")) { INPUT = vm["evaluate"].as<std::string>(); return interpretCode(); } else if (vm.count("read-file")) { std::ifstream in(vm["read-file"].as<std::string>()); std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); INPUT = contents; return interpretCode(); } else { print(desc, "\n"); return ERROR_BAD_INPUT; } return 0; } <|endoftext|>
<commit_before>//============================================================================= //File Name: Main.cpp //Description: Handles processing Kinect input //Author: Tyler Veness //============================================================================= /* * TODO Add support for multiple monitors */ #include "TestScreen.hpp" #define _WIN32_WINNT 0x0501 #define WIN32_LEAN_AND_MEAN #include <windows.h> enum { IDC_RECALIBRATE_BUTTON = 101, IDC_STREAM_TOGGLE_BUTTON = 102 }; #include "Kinect.hpp" // global because the drawing is set up to be continuous in CALLBACK OnEvent HWND videoWindow = NULL; HWND depthWindow = NULL; HICON kinectON = NULL; HICON kinectOFF = NULL; Kinect* projectorKinectPtr = NULL; LRESULT CALLBACK OnEvent( HWND Handle , UINT Message , WPARAM WParam , LPARAM LParam ); BOOL CALLBACK MonitorEnumProc( HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData ); INT WINAPI WinMain( HINSTANCE Instance , HINSTANCE , LPSTR , INT ) { const char* mainClassName = "KinectBoard"; kinectON = LoadIcon( Instance , "kinect1-ON" ); kinectOFF = LoadIcon( Instance , "kinect2-OFF" ); HBRUSH mainBrush = CreateSolidBrush( RGB( 0 , 0 , 0 ) ); // Define a class for our main window WNDCLASSEX WindowClass; ZeroMemory( &WindowClass , sizeof(WNDCLASSEX) ); WindowClass.cbSize = sizeof(WNDCLASSEX); WindowClass.style = 0; WindowClass.lpfnWndProc = &OnEvent; WindowClass.cbClsExtra = 0; WindowClass.cbWndExtra = 0; WindowClass.hInstance = Instance; WindowClass.hIcon = kinectOFF; WindowClass.hCursor = NULL; WindowClass.hbrBackground = mainBrush; WindowClass.lpszMenuName = NULL; WindowClass.lpszClassName = mainClassName; WindowClass.hIconSm = kinectOFF; RegisterClassEx(&WindowClass); MSG Message; /* ===== Make a new window that isn't fullscreen ===== */ RECT winSize = { 0 , 0 , static_cast<int>(ImageVars::width) , static_cast<int>(ImageVars::height) }; // set the size, but not the position AdjustWindowRect( &winSize , WS_SYSMENU | WS_CAPTION | WS_VISIBLE | WS_MINIMIZEBOX | WS_CLIPCHILDREN , FALSE ); // adjust the size // Create a new window to be used for the lifetime of the application videoWindow = CreateWindowEx( 0 , mainClassName , "KinectBoard - Video" , WS_SYSMENU | WS_CAPTION | WS_VISIBLE | WS_MINIMIZEBOX | WS_CLIPCHILDREN , ( GetSystemMetrics(SM_CXSCREEN) - ( winSize.right - winSize.left ) ) / 2 , ( GetSystemMetrics(SM_CYSCREEN) - ( winSize.bottom - winSize.top ) ) / 2 , winSize.right - winSize.left , // returns image width (resized as window) winSize.bottom - winSize.top , // returns image height (resized as window) NULL , NULL , Instance , NULL ); depthWindow = CreateWindowEx( 0 , mainClassName , "KinectBoard - Depth" , WS_SYSMENU | WS_CAPTION | WS_VISIBLE | WS_MINIMIZEBOX | WS_CLIPCHILDREN , ( GetSystemMetrics(SM_CXSCREEN) - ( winSize.right - winSize.left ) ) / 2 , ( GetSystemMetrics(SM_CYSCREEN) - ( winSize.bottom - winSize.top ) ) / 2 , winSize.right - winSize.left , // returns image width (resized as window) winSize.bottom - winSize.top , // returns image height (resized as window) NULL , NULL , Instance , NULL ); /* =================================================== */ Kinect projectorKinect; projectorKinectPtr = &projectorKinect; // Make windows receive stream events from Kinect instance projectorKinect.registerVideoWindow( videoWindow ); projectorKinect.registerDepthWindow( depthWindow ); projectorKinect.startVideoStream(); //projectorKinect.startDepthStream(); projectorKinect.enableColor( Processing::Red ); projectorKinect.enableColor( Processing::Blue ); // Calibrate Kinect SendMessage( videoWindow , WM_COMMAND , IDC_RECALIBRATE_BUTTON , 0 ); while ( GetMessage( &Message , NULL , 0 , 0 ) > 0 ) { // If a message was waiting in the message queue, process it TranslateMessage( &Message ); DispatchMessage( &Message ); } UnregisterClass( mainClassName , Instance ); return Message.wParam; } LRESULT CALLBACK OnEvent( HWND Handle , UINT Message , WPARAM WParam , LPARAM LParam ) { switch ( Message ) { case WM_CREATE: { HWND recalibButton = CreateWindowEx( 0, "BUTTON", "Recalibrate", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 9, ImageVars::height - 9 - 24, 100, 24, Handle, reinterpret_cast<HMENU>( IDC_RECALIBRATE_BUTTON ), GetModuleHandle( NULL ), NULL); SendMessage( recalibButton, WM_SETFONT, reinterpret_cast<WPARAM>( GetStockObject( DEFAULT_GUI_FONT ) ), MAKELPARAM( FALSE , 0 ) ); HWND toggleStreamButton = CreateWindowEx( 0, "BUTTON", "Start/Stop", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, ImageVars::width - 9 - 100, ImageVars::height - 9 - 24, 100, 24, Handle, reinterpret_cast<HMENU>( IDC_STREAM_TOGGLE_BUTTON ), GetModuleHandle( NULL ), NULL); SendMessage( toggleStreamButton, WM_SETFONT, reinterpret_cast<WPARAM>( GetStockObject( DEFAULT_GUI_FONT ) ), MAKELPARAM( FALSE , 0 ) ); break; } case WM_COMMAND: { switch( LOWORD(WParam) ) { case IDC_RECALIBRATE_BUTTON: { if ( projectorKinectPtr != NULL ) { // if there is no Kinect connected, don't bother trying to retrieve images if ( projectorKinectPtr->isVideoStreamRunning() ) { sf::TestScreen testWin( "KinectBoard" , Handle , NULL ); testWin.setColor( Processing::Red ); testWin.display(); Sleep( 600 ); // give Kinect time to get image w/ test pattern projectorKinectPtr->setCalibImage( Processing::Red ); testWin.setColor( Processing::Blue ); testWin.display(); Sleep( 600 ); // give Kinect time to get image w/ test pattern projectorKinectPtr->setCalibImage( Processing::Blue ); projectorKinectPtr->calibrate(); testWin.close(); } } break; } case IDC_STREAM_TOGGLE_BUTTON: { if ( projectorKinectPtr != NULL ) { // If button was pressed from video display window if ( Handle == videoWindow ) { if ( projectorKinectPtr->isVideoStreamRunning() ) { projectorKinectPtr->stopVideoStream(); } else { projectorKinectPtr->startVideoStream(); } } // If button was pressed from depth image display window else if ( Handle == depthWindow ) { if ( projectorKinectPtr->isDepthStreamRunning() ) { projectorKinectPtr->stopDepthStream(); } else { projectorKinectPtr->startDepthStream(); } } } break; } } break; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc; hdc = BeginPaint( Handle , &ps ); // If we're painting the video display window if ( Handle == videoWindow ) { projectorKinectPtr->displayVideo( videoWindow , 0 , 0 , hdc ); } // If we're painting the depth image display window else if ( Handle == depthWindow ) { projectorKinectPtr->displayDepth( depthWindow , 0 , 0 , hdc ); } EndPaint( Handle , &ps ); break; } case WM_DESTROY: { // If a display window is being closed, exit the application if ( Handle == videoWindow || Handle == depthWindow ) { PostQuitMessage( 0 ); } break; } case WM_KINECT_VIDEOSTART: { // Change video window icon to green because the stream started PostMessage( Handle , WM_SETICON , ICON_SMALL , (LPARAM)kinectON ); PostMessage( Handle , WM_SETICON , ICON_BIG , (LPARAM)kinectON ); break; } case WM_KINECT_VIDEOSTOP: { // Change video window icon to red because the stream stopped PostMessage( Handle , WM_SETICON , ICON_SMALL , (LPARAM)kinectOFF ); PostMessage( Handle , WM_SETICON , ICON_BIG , (LPARAM)kinectOFF ); break; } case WM_KINECT_DEPTHSTART: { // Change depth window icon to green because the stream started PostMessage( Handle , WM_SETICON , ICON_SMALL , (LPARAM)kinectON ); PostMessage( Handle , WM_SETICON , ICON_BIG , (LPARAM)kinectON ); break; } case WM_KINECT_DEPTHSTOP: { // Change depth window icon to red because the stream stopped PostMessage( Handle , WM_SETICON , ICON_SMALL , (LPARAM)kinectOFF ); PostMessage( Handle , WM_SETICON , ICON_BIG , (LPARAM)kinectOFF ); break; } default: { return DefWindowProc( Handle , Message , WParam , LParam ); } } return 0; } BOOL CALLBACK MonitorEnumProc( HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData ) { return FALSE; } <commit_msg>Made button text change as streams start and stop<commit_after>//============================================================================= //File Name: Main.cpp //Description: Handles processing Kinect input //Author: Tyler Veness //============================================================================= /* * TODO Add support for multiple monitors */ #define _WIN32_WINNT 0x0501 #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <cstring> enum { IDC_RECALIBRATE_BUTTON = 101, IDC_STREAM_TOGGLE_BUTTON = 102 }; #include "TestScreen.hpp" #include "Kinect.hpp" // global because the drawing is set up to be continuous in CALLBACK OnEvent HWND videoWindow = NULL; HWND depthWindow = NULL; HICON kinectON = NULL; HICON kinectOFF = NULL; Kinect* projectorKinectPtr = NULL; LRESULT CALLBACK OnEvent( HWND Handle , UINT Message , WPARAM WParam , LPARAM LParam ); BOOL CALLBACK MonitorEnumProc( HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData ); BOOL CALLBACK StartStreamChildProc( HWND hwndChild, LPARAM lParam ); BOOL CALLBACK StopStreamChildProc( HWND hwndChild, LPARAM lParam ); INT WINAPI WinMain( HINSTANCE Instance , HINSTANCE , LPSTR , INT ) { const char* mainClassName = "KinectBoard"; kinectON = LoadIcon( Instance , "kinect1-ON" ); kinectOFF = LoadIcon( Instance , "kinect2-OFF" ); HBRUSH mainBrush = CreateSolidBrush( RGB( 0 , 0 , 0 ) ); // Define a class for our main window WNDCLASSEX WindowClass; ZeroMemory( &WindowClass , sizeof(WNDCLASSEX) ); WindowClass.cbSize = sizeof(WNDCLASSEX); WindowClass.style = 0; WindowClass.lpfnWndProc = &OnEvent; WindowClass.cbClsExtra = 0; WindowClass.cbWndExtra = 0; WindowClass.hInstance = Instance; WindowClass.hIcon = kinectOFF; WindowClass.hCursor = NULL; WindowClass.hbrBackground = mainBrush; WindowClass.lpszMenuName = NULL; WindowClass.lpszClassName = mainClassName; WindowClass.hIconSm = kinectOFF; RegisterClassEx(&WindowClass); MSG Message; /* ===== Make a new window that isn't fullscreen ===== */ RECT winSize = { 0 , 0 , static_cast<int>(ImageVars::width) , static_cast<int>(ImageVars::height) }; // set the size, but not the position AdjustWindowRect( &winSize , WS_SYSMENU | WS_CAPTION | WS_VISIBLE | WS_MINIMIZEBOX | WS_CLIPCHILDREN , FALSE ); // adjust the size // Create a new window to be used for the lifetime of the application videoWindow = CreateWindowEx( 0 , mainClassName , "KinectBoard - Video" , WS_SYSMENU | WS_CAPTION | WS_VISIBLE | WS_MINIMIZEBOX | WS_CLIPCHILDREN , ( GetSystemMetrics(SM_CXSCREEN) - ( winSize.right - winSize.left ) ) / 2 , ( GetSystemMetrics(SM_CYSCREEN) - ( winSize.bottom - winSize.top ) ) / 2 , winSize.right - winSize.left , // returns image width (resized as window) winSize.bottom - winSize.top , // returns image height (resized as window) NULL , NULL , Instance , NULL ); depthWindow = CreateWindowEx( 0 , mainClassName , "KinectBoard - Depth" , WS_SYSMENU | WS_CAPTION | WS_VISIBLE | WS_MINIMIZEBOX | WS_CLIPCHILDREN , ( GetSystemMetrics(SM_CXSCREEN) - ( winSize.right - winSize.left ) ) / 2 , ( GetSystemMetrics(SM_CYSCREEN) - ( winSize.bottom - winSize.top ) ) / 2 , winSize.right - winSize.left , // returns image width (resized as window) winSize.bottom - winSize.top , // returns image height (resized as window) NULL , NULL , Instance , NULL ); /* =================================================== */ Kinect projectorKinect; projectorKinectPtr = &projectorKinect; // Make windows receive stream events from Kinect instance projectorKinect.registerVideoWindow( videoWindow ); projectorKinect.registerDepthWindow( depthWindow ); projectorKinect.startVideoStream(); //projectorKinect.startDepthStream(); projectorKinect.enableColor( Processing::Red ); projectorKinect.enableColor( Processing::Blue ); // Calibrate Kinect SendMessage( videoWindow , WM_COMMAND , IDC_RECALIBRATE_BUTTON , 0 ); while ( GetMessage( &Message , NULL , 0 , 0 ) > 0 ) { // If a message was waiting in the message queue, process it TranslateMessage( &Message ); DispatchMessage( &Message ); } UnregisterClass( mainClassName , Instance ); return Message.wParam; } LRESULT CALLBACK OnEvent( HWND Handle , UINT Message , WPARAM WParam , LPARAM LParam ) { switch ( Message ) { case WM_CREATE: { HWND recalibButton = CreateWindowEx( 0, "BUTTON", "Recalibrate", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 9, ImageVars::height - 9 - 24, 100, 24, Handle, reinterpret_cast<HMENU>( IDC_RECALIBRATE_BUTTON ), GetModuleHandle( NULL ), NULL); SendMessage( recalibButton, WM_SETFONT, reinterpret_cast<WPARAM>( GetStockObject( DEFAULT_GUI_FONT ) ), MAKELPARAM( FALSE , 0 ) ); HWND toggleStreamButton = CreateWindowEx( 0, "BUTTON", "Start", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, ImageVars::width - 9 - 100, ImageVars::height - 9 - 24, 100, 24, Handle, reinterpret_cast<HMENU>( IDC_STREAM_TOGGLE_BUTTON ), GetModuleHandle( NULL ), NULL); SendMessage( toggleStreamButton, WM_SETFONT, reinterpret_cast<WPARAM>( GetStockObject( DEFAULT_GUI_FONT ) ), MAKELPARAM( FALSE , 0 ) ); break; } case WM_COMMAND: { switch( LOWORD(WParam) ) { case IDC_RECALIBRATE_BUTTON: { if ( projectorKinectPtr != NULL ) { // if there is no Kinect connected, don't bother trying to retrieve images if ( projectorKinectPtr->isVideoStreamRunning() ) { sf::TestScreen testWin( "KinectBoard" , Handle , NULL ); testWin.setColor( Processing::Red ); testWin.display(); Sleep( 600 ); // give Kinect time to get image w/ test pattern projectorKinectPtr->setCalibImage( Processing::Red ); testWin.setColor( Processing::Blue ); testWin.display(); Sleep( 600 ); // give Kinect time to get image w/ test pattern projectorKinectPtr->setCalibImage( Processing::Blue ); projectorKinectPtr->calibrate(); testWin.close(); } } break; } case IDC_STREAM_TOGGLE_BUTTON: { if ( projectorKinectPtr != NULL ) { // If button was pressed from video display window if ( Handle == videoWindow ) { if ( projectorKinectPtr->isVideoStreamRunning() ) { projectorKinectPtr->stopVideoStream(); } else { projectorKinectPtr->startVideoStream(); } } // If button was pressed from depth image display window else if ( Handle == depthWindow ) { if ( projectorKinectPtr->isDepthStreamRunning() ) { projectorKinectPtr->stopDepthStream(); } else { projectorKinectPtr->startDepthStream(); } } } break; } } break; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc; hdc = BeginPaint( Handle , &ps ); // If we're painting the video display window if ( Handle == videoWindow ) { projectorKinectPtr->displayVideo( videoWindow , 0 , 0 , hdc ); } // If we're painting the depth image display window else if ( Handle == depthWindow ) { projectorKinectPtr->displayDepth( depthWindow , 0 , 0 , hdc ); } EndPaint( Handle , &ps ); break; } case WM_DESTROY: { // If a display window is being closed, exit the application if ( Handle == videoWindow || Handle == depthWindow ) { PostQuitMessage( 0 ); } break; } case WM_KINECT_VIDEOSTART: { // Change video window icon to green because the stream started PostMessage( Handle , WM_SETICON , ICON_SMALL , (LPARAM)kinectON ); PostMessage( Handle , WM_SETICON , ICON_BIG , (LPARAM)kinectON ); char* windowText = (char*)std::malloc( 16 ); EnumChildWindows( Handle , StartStreamChildProc , (LPARAM)windowText ); std::free( windowText ); break; } case WM_KINECT_VIDEOSTOP: { // Change video window icon to red because the stream stopped PostMessage( Handle , WM_SETICON , ICON_SMALL , (LPARAM)kinectOFF ); PostMessage( Handle , WM_SETICON , ICON_BIG , (LPARAM)kinectOFF ); char* windowText = (char*)std::malloc( 16 ); EnumChildWindows( Handle , StopStreamChildProc , (LPARAM)windowText ); std::free( windowText ); break; } case WM_KINECT_DEPTHSTART: { // Change depth window icon to green because the stream started PostMessage( Handle , WM_SETICON , ICON_SMALL , (LPARAM)kinectON ); PostMessage( Handle , WM_SETICON , ICON_BIG , (LPARAM)kinectON ); char* windowText = (char*)std::malloc( 16 ); EnumChildWindows( Handle , StartStreamChildProc , (LPARAM)windowText ); std::free( windowText ); break; } case WM_KINECT_DEPTHSTOP: { // Change depth window icon to red because the stream stopped PostMessage( Handle , WM_SETICON , ICON_SMALL , (LPARAM)kinectOFF ); PostMessage( Handle , WM_SETICON , ICON_BIG , (LPARAM)kinectOFF ); char* windowText = (char*)std::malloc( 16 ); EnumChildWindows( Handle , StopStreamChildProc , (LPARAM)windowText ); std::free( windowText ); break; } default: { return DefWindowProc( Handle , Message , WParam , LParam ); } } return 0; } BOOL CALLBACK MonitorEnumProc( HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData ) { return FALSE; } BOOL CALLBACK StartStreamChildProc( HWND hwndChild, LPARAM lParam ) { char* windowText = (char*)lParam; if ( GetWindowText( hwndChild , windowText , 16 ) ) { if ( std::strcmp( windowText , "Start" ) == 0 ) { SetWindowText( hwndChild , "Stop" ); return FALSE; } } return TRUE; } BOOL CALLBACK StopStreamChildProc( HWND hwndChild, LPARAM lParam ) { char* windowText = (char*)lParam; if ( GetWindowText( hwndChild , windowText , 16 ) ) { if ( std::strcmp( windowText , "Stop" ) == 0 ) { SetWindowText( hwndChild , "Start" ); return FALSE; } } return TRUE; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "bbudf.h" #include "curl.h" #include "logger.h" namespace curl { //TODO http://www.openssl.org/docs/crypto/threads.html#DESCRIPTION __thread CURL* ch=NULL; __thread long curl_response_code=0; int curl_global_init_called=0; size_t readfunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){ unsigned short length,actual_length; length=size*nmemb; blobcallback* blob=(blobcallback*) userdata; int res; res=blob->blob_get_segment(blob->blob_handle,(ISC_UCHAR*)ptr,length,&actual_length); logger::syslog(0, "xmlreader::readfunction_blob() len=%d,res=%d,actual_length=%d",length,res,actual_length); return actual_length; } size_t writefunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){ size_t length=size*nmemb; if(length>0){ blobcallback* outblob=(blobcallback*) userdata; outblob->blob_put_segment(outblob->blob_handle, (ISC_UCHAR*) ptr, length); } return length; } } FBUDF_API void fn_curl_exec(const char* method,const char* url, const char* sslcert, const char* sslcertpassword,const char* cainfo, const char* headers, blobcallback* datablob, const char* cookies, blobcallback* outblob) { curl::curl_response_code=0; if (!outblob || !outblob->blob_handle){ return; } CURLcode code; if(!curl::curl_global_init_called) { code=curl_global_init(CURL_GLOBAL_ALL); if(code != CURLE_OK){ logger::blobprinf(outblob,"curl_global_init() failed: %s\n",curl_easy_strerror(code)); return; } curl::curl_global_init_called=1; } CURL* ch; if(curl::ch==NULL){ curl::ch=curl_easy_init(); if(!curl::ch){ logger::blobprinf(outblob,"curl_easy_init() failed\n"); return; } }else{ curl_easy_reset(curl::ch); } ch=curl::ch; curl_easy_setopt(ch,CURLOPT_NOSIGNAL,1); if (strcmp(method,"GET")==0){ curl_easy_setopt(ch,CURLOPT_HTTPGET,1); }else if (strcmp(method,"POST")==0){ curl_easy_setopt(ch,CURLOPT_POST,1); }else if (strcmp(method,"PUT")==0){ curl_easy_setopt(ch,CURLOPT_PUT,1); }else if (strcmp(method,"HEAD")==0){ curl_easy_setopt(ch,CURLOPT_NOBODY,1); }else{ logger::blobprinf(outblob,"unknown method '%s'",method); return; } curl_easy_setopt(ch,CURLOPT_URL,url); curl_easy_setopt(ch,CURLOPT_SSLCERT,sslcert); curl_easy_setopt(ch,CURLOPT_SSLCERTPASSWD,sslcertpassword); curl_easy_setopt(ch,CURLOPT_CAINFO,cainfo); curl_easy_setopt(ch,CURLOPT_WRITEFUNCTION,curl::writefunction_blob); curl_easy_setopt(ch,CURLOPT_WRITEDATA,outblob); struct curl_slist *slist=NULL; if(headers){ #if defined(WIN32) #else char *saveptr; char *headersdup=strdup(headers); char *token=strtok_r(headersdup, "\n", &saveptr); while(token){ slist = curl_slist_append(slist, token); token=strtok_r(NULL, "\n", &saveptr); } free(headersdup); #endif } curl_easy_setopt(ch, CURLOPT_HTTPHEADER, slist); curl_easy_setopt(ch, CURLOPT_COOKIE, cookies); if(datablob && datablob->blob_handle){ //logger::syslog(0, "setup readfunction_blob(), data length=%d",datablob->blob_total_length); curl_easy_setopt(ch,CURLOPT_READFUNCTION,curl::readfunction_blob); curl_easy_setopt(ch,CURLOPT_READDATA,datablob); if (strcmp(method,"PUT")==0) { curl_easy_setopt(ch,CURLOPT_INFILESIZE,datablob->blob_total_length); }else{ curl_easy_setopt(ch,CURLOPT_POSTFIELDSIZE,datablob->blob_total_length); } } code=curl_easy_perform(ch); if(slist){ curl_slist_free_all(slist); } if(code != CURLE_OK){ logger::syslog(1,"curl_easy_perform() failed: %s\nsslcert=%s\nsslcertpassword=(%d chars)\ncainfo=%s",curl_easy_strerror(code),sslcert,strlen(sslcertpassword),cainfo); logger::blobprinf(outblob,"curl_easy_perform() failed: %s",curl_easy_strerror(code)); return; } curl_easy_getinfo(ch, CURLINFO_RESPONSE_CODE, &curl::curl_response_code); } FBUDF_API long fn_curl_get_response_code() { return curl::curl_response_code; }<commit_msg>curl_easy_perform() failed: Problem with the local SSL certificate diagonstic message<commit_after>#include "stdafx.h" #include "bbudf.h" #include "curl.h" #include "logger.h" namespace curl { //TODO http://www.openssl.org/docs/crypto/threads.html#DESCRIPTION __thread CURL* ch=NULL; __thread long curl_response_code=0; int curl_global_init_called=0; size_t readfunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){ unsigned short length,actual_length; length=size*nmemb; blobcallback* blob=(blobcallback*) userdata; int res; res=blob->blob_get_segment(blob->blob_handle,(ISC_UCHAR*)ptr,length,&actual_length); logger::syslog(0, "xmlreader::readfunction_blob() len=%d,res=%d,actual_length=%d",length,res,actual_length); return actual_length; } size_t writefunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){ size_t length=size*nmemb; if(length>0){ blobcallback* outblob=(blobcallback*) userdata; outblob->blob_put_segment(outblob->blob_handle, (ISC_UCHAR*) ptr, length); } return length; } } FBUDF_API void fn_curl_exec(const char* method,const char* url, const char* sslcert, const char* sslcertpassword,const char* cainfo, const char* headers, blobcallback* datablob, const char* cookies, blobcallback* outblob) { curl::curl_response_code=0; if (!outblob || !outblob->blob_handle){ return; } CURLcode code; if(!curl::curl_global_init_called) { code=curl_global_init(CURL_GLOBAL_ALL); if(code != CURLE_OK){ logger::blobprinf(outblob,"curl_global_init() failed: %s\n",curl_easy_strerror(code)); return; } curl::curl_global_init_called=1; } CURL* ch; if(curl::ch==NULL){ curl::ch=curl_easy_init(); if(!curl::ch){ logger::blobprinf(outblob,"curl_easy_init() failed\n"); return; } }else{ curl_easy_reset(curl::ch); } ch=curl::ch; curl_easy_setopt(ch,CURLOPT_NOSIGNAL,1); if (strcmp(method,"GET")==0){ curl_easy_setopt(ch,CURLOPT_HTTPGET,1); }else if (strcmp(method,"POST")==0){ curl_easy_setopt(ch,CURLOPT_POST,1); }else if (strcmp(method,"PUT")==0){ curl_easy_setopt(ch,CURLOPT_PUT,1); }else if (strcmp(method,"HEAD")==0){ curl_easy_setopt(ch,CURLOPT_NOBODY,1); }else{ logger::blobprinf(outblob,"unknown method '%s'",method); return; } curl_easy_setopt(ch,CURLOPT_URL,url); curl_easy_setopt(ch,CURLOPT_SSLCERT,sslcert); curl_easy_setopt(ch,CURLOPT_SSLCERTPASSWD,sslcertpassword); curl_easy_setopt(ch,CURLOPT_CAINFO,cainfo); curl_easy_setopt(ch,CURLOPT_WRITEFUNCTION,curl::writefunction_blob); curl_easy_setopt(ch,CURLOPT_WRITEDATA,outblob); struct curl_slist *slist=NULL; if(headers){ #if defined(WIN32) #else char *saveptr; char *headersdup=strdup(headers); char *token=strtok_r(headersdup, "\n", &saveptr); while(token){ slist = curl_slist_append(slist, token); token=strtok_r(NULL, "\n", &saveptr); } free(headersdup); #endif } curl_easy_setopt(ch, CURLOPT_HTTPHEADER, slist); curl_easy_setopt(ch, CURLOPT_COOKIE, cookies); if(datablob && datablob->blob_handle){ //logger::syslog(0, "setup readfunction_blob(), data length=%d",datablob->blob_total_length); curl_easy_setopt(ch,CURLOPT_READFUNCTION,curl::readfunction_blob); curl_easy_setopt(ch,CURLOPT_READDATA,datablob); if (strcmp(method,"PUT")==0) { curl_easy_setopt(ch,CURLOPT_INFILESIZE,datablob->blob_total_length); }else{ curl_easy_setopt(ch,CURLOPT_POSTFIELDSIZE,datablob->blob_total_length); } } code=curl_easy_perform(ch); if(slist){ curl_slist_free_all(slist); } if(code != CURLE_OK){ logger::syslog(1,"curl_easy_perform() failed: %s, url=%s, sslcert=%s, sslcertpassword=(%d chars), cainfo=%s",curl_easy_strerror(code),url,sslcert,strlen(sslcertpassword),cainfo); logger::blobprinf(outblob,"curl_easy_perform() failed: %s",curl_easy_strerror(code)); return; } curl_easy_getinfo(ch, CURLINFO_RESPONSE_CODE, &curl::curl_response_code); } FBUDF_API long fn_curl_get_response_code() { return curl::curl_response_code; }<|endoftext|>
<commit_before>#ifndef __STAN__GM__PARSER__STATEMENT_2_GRAMMAR__HPP__ #define __STAN__GM__PARSER__STATEMENT_2_GRAMMAR__HPP__ #include <string> #include <sstream> #include <vector> #include <boost/spirit/include/qi.hpp> #include <stan/gm/ast.hpp> #include <stan/gm/grammars/whitespace_grammar.hpp> #include <stan/gm/grammars/expression_grammar.hpp> #include <stan/gm/grammars/var_decls_grammar.hpp> #include <stan/gm/grammars/statement_grammar.hpp> namespace stan { namespace gm { template <typename Iterator> struct statement_grammar; template <typename Iterator> struct statement_2_grammar : boost::spirit::qi::grammar<Iterator, statement(bool,var_origin), whitespace_grammar<Iterator> > { statement_2_grammar(variable_map& var_map, std::stringstream& error_msgs, statement_grammar<Iterator>& sg); // global info for parses variable_map& var_map_; std::stringstream& error_msgs_; // grammars expression_grammar<Iterator> expression_g; statement_grammar<Iterator>& statement_g; // rules boost::spirit::qi::rule<Iterator, conditional_statement(bool,var_origin), whitespace_grammar<Iterator> > conditional_statement_r; boost::spirit::qi::rule<Iterator, statement(bool,var_origin), whitespace_grammar<Iterator> > statement_2_r; }; } } #endif <commit_msg>remove unnecessary #include that created loop<commit_after>#ifndef __STAN__GM__PARSER__STATEMENT_2_GRAMMAR__HPP__ #define __STAN__GM__PARSER__STATEMENT_2_GRAMMAR__HPP__ #include <string> #include <sstream> #include <vector> #include <boost/spirit/include/qi.hpp> #include <stan/gm/ast.hpp> #include <stan/gm/grammars/whitespace_grammar.hpp> #include <stan/gm/grammars/expression_grammar.hpp> #include <stan/gm/grammars/var_decls_grammar.hpp> namespace stan { namespace gm { template <typename Iterator> struct statement_grammar; template <typename Iterator> struct statement_2_grammar : boost::spirit::qi::grammar<Iterator, statement(bool,var_origin), whitespace_grammar<Iterator> > { statement_2_grammar(variable_map& var_map, std::stringstream& error_msgs, statement_grammar<Iterator>& sg); // global info for parses variable_map& var_map_; std::stringstream& error_msgs_; // grammars expression_grammar<Iterator> expression_g; statement_grammar<Iterator>& statement_g; // rules boost::spirit::qi::rule<Iterator, conditional_statement(bool,var_origin), whitespace_grammar<Iterator> > conditional_statement_r; boost::spirit::qi::rule<Iterator, statement(bool,var_origin), whitespace_grammar<Iterator> > statement_2_r; }; } } #endif <|endoftext|>
<commit_before>#include "debug.h" #include <stdio.h> #include <iostream> #include "terminal.h" #include <lldb/API/SBTarget.h> #include <lldb/API/SBProcess.h> #include <lldb/API/SBEvent.h> #include <lldb/API/SBBreakpoint.h> #include <lldb/API/SBThread.h> #include <lldb/API/SBStream.h> #include <lldb/API/SBDeclaration.h> #include <lldb/API/SBCommandInterpreter.h> #include <lldb/API/SBCommandReturnObject.h> #include <lldb/API/SBBreakpointLocation.h> using namespace std; //TODO: remove extern char **environ; void log(const char *msg, void *) { cout << "debugger log: " << msg << endl; } Debug::Debug(): listener("juCi++ lldb listener"), state(lldb::StateType::eStateInvalid), buffer_size(131072) {} void Debug::start(std::shared_ptr<std::vector<std::pair<boost::filesystem::path, int> > > breakpoints, const boost::filesystem::path &executable, const boost::filesystem::path &path, std::function<void(int exit_status)> callback, std::function<void(const std::string &status)> status_callback, std::function<void(const boost::filesystem::path &file_path, int line_nr, int line_index)> stop_callback) { if(!debugger.IsValid()) { lldb::SBDebugger::Initialize(); debugger=lldb::SBDebugger::Create(true, log, nullptr); } auto target=debugger.CreateTarget(executable.string().c_str()); if(!target.IsValid()) { Terminal::get().async_print("Error (debug): Could not create debug target to: "+executable.string()+'\n', true); return; } for(auto &breakpoint: *breakpoints) { if(!(target.BreakpointCreateByLocation(breakpoint.first.string().c_str(), breakpoint.second)).IsValid()) { Terminal::get().async_print("Error (debug): Could not create breakpoint at: "+breakpoint.first.string()+":"+std::to_string(breakpoint.second)+'\n', true); return; } } lldb::SBError error; process = std::unique_ptr<lldb::SBProcess>(new lldb::SBProcess(target.Launch(listener, nullptr, (const char**)environ, nullptr, nullptr, nullptr, path.string().c_str(), lldb::eLaunchFlagNone, false, error))); if(error.Fail()) { Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); return; } if(debug_thread.joinable()) debug_thread.join(); debug_thread=std::thread([this, callback, status_callback, stop_callback]() { lldb::SBEvent event; while(true) { event_mutex.lock(); if(listener.GetNextEvent(event)) { if((event.GetType() & lldb::SBProcess::eBroadcastBitStateChanged)>0) { auto state=process->GetStateFromEvent(event); this->state=state; //Update debug status lldb::SBStream stream; event.GetDescription(stream); std::string event_desc=stream.GetData(); event_desc.pop_back(); auto pos=event_desc.rfind(" = "); if(status_callback && pos!=std::string::npos) status_callback(event_desc.substr(pos+3)); if(state==lldb::StateType::eStateStopped) { auto line_entry=process->GetSelectedThread().GetSelectedFrame().GetLineEntry(); if(stop_callback) { if(line_entry.IsValid()) { lldb::SBStream stream; line_entry.GetFileSpec().GetDescription(stream); auto column=line_entry.GetColumn(); if(column==0) column=1; stop_callback(stream.GetData(), line_entry.GetLine(), column); } else stop_callback("", 0, 0); } } else if(state==lldb::StateType::eStateRunning) { stop_callback("", 0, 0); } else if(state==lldb::StateType::eStateExited) { auto exit_status=process->GetExitStatus(); if(callback) callback(exit_status); if(status_callback) status_callback(""); if(stop_callback) stop_callback("", 0, 0); process.reset(); this->state=lldb::StateType::eStateInvalid; event_mutex.unlock(); return; } else if(state==lldb::StateType::eStateCrashed) { if(callback) callback(-1); if(status_callback) status_callback(""); if(stop_callback) stop_callback("", 0, 0); process.reset(); this->state=lldb::StateType::eStateInvalid; event_mutex.unlock(); return; } } if((event.GetType() & lldb::SBProcess::eBroadcastBitSTDOUT)>0) { char buffer[buffer_size]; size_t n; while((n=process->GetSTDOUT(buffer, buffer_size))!=0) Terminal::get().async_print(std::string(buffer, n)); } //TODO: for some reason stderr is redirected to stdout if((event.GetType() & lldb::SBProcess::eBroadcastBitSTDERR)>0) { char buffer[buffer_size]; size_t n; while((n=process->GetSTDERR(buffer, buffer_size))!=0) Terminal::get().async_print(std::string(buffer, n), true); } } event_mutex.unlock(); this_thread::sleep_for(std::chrono::milliseconds(200)); } }); } void Debug::continue_debug() { event_mutex.lock(); if(state==lldb::StateType::eStateStopped) process->Continue(); event_mutex.unlock(); } void Debug::stop() { event_mutex.lock(); if(state==lldb::StateType::eStateRunning) { auto error=process->Stop(); if(error.Fail()) Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); } event_mutex.unlock(); } void Debug::kill() { event_mutex.lock(); if(process) { auto error=process->Kill(); if(error.Fail()) Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); } event_mutex.unlock(); } std::pair<std::string, std::string> Debug::run_command(const std::string &command) { std::pair<std::string, std::string> command_return; event_mutex.lock(); if(state==lldb::StateType::eStateStopped) { lldb::SBCommandReturnObject command_return_object; debugger.GetCommandInterpreter().HandleCommand(command.c_str(), command_return_object, true); command_return.first=command_return_object.GetOutput(); command_return.second=command_return_object.GetError(); } event_mutex.unlock(); return command_return; } void Debug::delete_debug() { kill(); if(debug_thread.joinable()) debug_thread.join(); lldb::SBDebugger::Terminate(); } std::string Debug::get_value(const std::string &variable, const boost::filesystem::path &file_path, unsigned int line_nr) { std::string variable_value; event_mutex.lock(); if(state==lldb::StateType::eStateStopped) { auto frame=process->GetSelectedThread().GetSelectedFrame(); auto values=frame.GetVariables(true, true, true, false); //First try to find variable based on name, file and line number for(uint32_t value_index=0;value_index<values.GetSize();value_index++) { lldb::SBStream stream; auto value=values.GetValueAtIndex(value_index); if(value.GetName()==variable) { auto declaration=value.GetDeclaration(); if(declaration.IsValid()) { if(declaration.GetLine()==line_nr) { auto file_spec=declaration.GetFileSpec(); boost::filesystem::path value_decl_path=file_spec.GetDirectory(); value_decl_path/=file_spec.GetFilename(); if(value_decl_path==file_path) { value.GetDescription(stream); variable_value=stream.GetData(); break; } } } } } if(variable_value.empty()) { //In case a variable is missing file and line number, only do check on name auto value=frame.FindVariable(variable.c_str()); if(value.IsValid()) { lldb::SBStream stream; value.GetDescription(stream); variable_value=stream.GetData(); } } } event_mutex.unlock(); return variable_value; } bool Debug::is_invalid() { bool invalid; event_mutex.lock(); invalid=state==lldb::StateType::eStateInvalid; event_mutex.unlock(); return invalid; } bool Debug::is_stopped() { bool stopped; event_mutex.lock(); stopped=state==lldb::StateType::eStateStopped; event_mutex.unlock(); return stopped; } bool Debug::is_running() { bool running; event_mutex.lock(); running=state==lldb::StateType::eStateRunning; event_mutex.unlock(); return running; } void Debug::add_breakpoint(const boost::filesystem::path &file_path, int line_nr) { event_mutex.lock(); if(state==lldb::eStateStopped || state==lldb::eStateRunning) { if(!(process->GetTarget().BreakpointCreateByLocation(file_path.string().c_str(), line_nr)).IsValid()) Terminal::get().async_print("Error (debug): Could not create breakpoint at: "+file_path.string()+":"+std::to_string(line_nr)+'\n', true); } event_mutex.unlock(); } void Debug::remove_breakpoint(const boost::filesystem::path &file_path, int line_nr, int line_count) { event_mutex.lock(); if(state==lldb::eStateStopped || state==lldb::eStateRunning) { auto target=process->GetTarget(); for(int line_nr_try=line_nr;line_nr_try<line_count;line_nr_try++) { for(uint32_t b_index=0;b_index<target.GetNumBreakpoints();b_index++) { auto breakpoint=target.GetBreakpointAtIndex(b_index); for(uint32_t l_index=0;l_index<breakpoint.GetNumLocations();l_index++) { auto line_entry=breakpoint.GetLocationAtIndex(l_index).GetAddress().GetLineEntry(); if(line_entry.GetLine()==static_cast<uint32_t>(line_nr_try)) { auto file_spec=line_entry.GetFileSpec(); boost::filesystem::path breakpoint_path=file_spec.GetDirectory(); breakpoint_path/=file_spec.GetFilename(); if(breakpoint_path==file_path) { if(!target.BreakpointDelete(breakpoint.GetID())) Terminal::get().async_print("Error (debug): Could not delete breakpoint at: "+file_path.string()+":"+std::to_string(line_nr)+'\n', true); event_mutex.unlock(); return; } } } } } } event_mutex.unlock(); } void Debug::write(const std::string &buffer) { event_mutex.lock(); if(state==lldb::StateType::eStateRunning) { process->PutSTDIN(buffer.c_str(), buffer.size()); } event_mutex.unlock(); } <commit_msg>Now sets LLDB_DEBUGSERVER_PATH in debug.cc on OS X<commit_after>#include "debug.h" #include <stdio.h> #include <stdlib.h> #include <iostream> #include "terminal.h" #include <lldb/API/SBTarget.h> #include <lldb/API/SBProcess.h> #include <lldb/API/SBEvent.h> #include <lldb/API/SBBreakpoint.h> #include <lldb/API/SBThread.h> #include <lldb/API/SBStream.h> #include <lldb/API/SBDeclaration.h> #include <lldb/API/SBCommandInterpreter.h> #include <lldb/API/SBCommandReturnObject.h> #include <lldb/API/SBBreakpointLocation.h> using namespace std; //TODO: remove extern char **environ; void log(const char *msg, void *) { cout << "debugger log: " << msg << endl; } Debug::Debug(): listener("juCi++ lldb listener"), state(lldb::StateType::eStateInvalid), buffer_size(131072) { #ifdef __APPLE__ setenv("LLDB_DEBUGSERVER_PATH", "/usr/local/opt/llvm/bin/debugserver", 0); #endif } void Debug::start(std::shared_ptr<std::vector<std::pair<boost::filesystem::path, int> > > breakpoints, const boost::filesystem::path &executable, const boost::filesystem::path &path, std::function<void(int exit_status)> callback, std::function<void(const std::string &status)> status_callback, std::function<void(const boost::filesystem::path &file_path, int line_nr, int line_index)> stop_callback) { if(!debugger.IsValid()) { lldb::SBDebugger::Initialize(); debugger=lldb::SBDebugger::Create(true, log, nullptr); } auto target=debugger.CreateTarget(executable.string().c_str()); if(!target.IsValid()) { Terminal::get().async_print("Error (debug): Could not create debug target to: "+executable.string()+'\n', true); return; } for(auto &breakpoint: *breakpoints) { if(!(target.BreakpointCreateByLocation(breakpoint.first.string().c_str(), breakpoint.second)).IsValid()) { Terminal::get().async_print("Error (debug): Could not create breakpoint at: "+breakpoint.first.string()+":"+std::to_string(breakpoint.second)+'\n', true); return; } } lldb::SBError error; process = std::unique_ptr<lldb::SBProcess>(new lldb::SBProcess(target.Launch(listener, nullptr, (const char**)environ, nullptr, nullptr, nullptr, path.string().c_str(), lldb::eLaunchFlagNone, false, error))); if(error.Fail()) { Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); return; } if(debug_thread.joinable()) debug_thread.join(); debug_thread=std::thread([this, callback, status_callback, stop_callback]() { lldb::SBEvent event; while(true) { event_mutex.lock(); if(listener.GetNextEvent(event)) { if((event.GetType() & lldb::SBProcess::eBroadcastBitStateChanged)>0) { auto state=process->GetStateFromEvent(event); this->state=state; //Update debug status lldb::SBStream stream; event.GetDescription(stream); std::string event_desc=stream.GetData(); event_desc.pop_back(); auto pos=event_desc.rfind(" = "); if(status_callback && pos!=std::string::npos) status_callback(event_desc.substr(pos+3)); if(state==lldb::StateType::eStateStopped) { auto line_entry=process->GetSelectedThread().GetSelectedFrame().GetLineEntry(); if(stop_callback) { if(line_entry.IsValid()) { lldb::SBStream stream; line_entry.GetFileSpec().GetDescription(stream); auto column=line_entry.GetColumn(); if(column==0) column=1; stop_callback(stream.GetData(), line_entry.GetLine(), column); } else stop_callback("", 0, 0); } } else if(state==lldb::StateType::eStateRunning) { stop_callback("", 0, 0); } else if(state==lldb::StateType::eStateExited) { auto exit_status=process->GetExitStatus(); if(callback) callback(exit_status); if(status_callback) status_callback(""); if(stop_callback) stop_callback("", 0, 0); process.reset(); this->state=lldb::StateType::eStateInvalid; event_mutex.unlock(); return; } else if(state==lldb::StateType::eStateCrashed) { if(callback) callback(-1); if(status_callback) status_callback(""); if(stop_callback) stop_callback("", 0, 0); process.reset(); this->state=lldb::StateType::eStateInvalid; event_mutex.unlock(); return; } } if((event.GetType() & lldb::SBProcess::eBroadcastBitSTDOUT)>0) { char buffer[buffer_size]; size_t n; while((n=process->GetSTDOUT(buffer, buffer_size))!=0) Terminal::get().async_print(std::string(buffer, n)); } //TODO: for some reason stderr is redirected to stdout if((event.GetType() & lldb::SBProcess::eBroadcastBitSTDERR)>0) { char buffer[buffer_size]; size_t n; while((n=process->GetSTDERR(buffer, buffer_size))!=0) Terminal::get().async_print(std::string(buffer, n), true); } } event_mutex.unlock(); this_thread::sleep_for(std::chrono::milliseconds(200)); } }); } void Debug::continue_debug() { event_mutex.lock(); if(state==lldb::StateType::eStateStopped) process->Continue(); event_mutex.unlock(); } void Debug::stop() { event_mutex.lock(); if(state==lldb::StateType::eStateRunning) { auto error=process->Stop(); if(error.Fail()) Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); } event_mutex.unlock(); } void Debug::kill() { event_mutex.lock(); if(process) { auto error=process->Kill(); if(error.Fail()) Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); } event_mutex.unlock(); } std::pair<std::string, std::string> Debug::run_command(const std::string &command) { std::pair<std::string, std::string> command_return; event_mutex.lock(); if(state==lldb::StateType::eStateStopped) { lldb::SBCommandReturnObject command_return_object; debugger.GetCommandInterpreter().HandleCommand(command.c_str(), command_return_object, true); command_return.first=command_return_object.GetOutput(); command_return.second=command_return_object.GetError(); } event_mutex.unlock(); return command_return; } void Debug::delete_debug() { kill(); if(debug_thread.joinable()) debug_thread.join(); lldb::SBDebugger::Terminate(); } std::string Debug::get_value(const std::string &variable, const boost::filesystem::path &file_path, unsigned int line_nr) { std::string variable_value; event_mutex.lock(); if(state==lldb::StateType::eStateStopped) { auto frame=process->GetSelectedThread().GetSelectedFrame(); auto values=frame.GetVariables(true, true, true, false); //First try to find variable based on name, file and line number for(uint32_t value_index=0;value_index<values.GetSize();value_index++) { lldb::SBStream stream; auto value=values.GetValueAtIndex(value_index); if(value.GetName()==variable) { auto declaration=value.GetDeclaration(); if(declaration.IsValid()) { if(declaration.GetLine()==line_nr) { auto file_spec=declaration.GetFileSpec(); boost::filesystem::path value_decl_path=file_spec.GetDirectory(); value_decl_path/=file_spec.GetFilename(); if(value_decl_path==file_path) { value.GetDescription(stream); variable_value=stream.GetData(); break; } } } } } if(variable_value.empty()) { //In case a variable is missing file and line number, only do check on name auto value=frame.FindVariable(variable.c_str()); if(value.IsValid()) { lldb::SBStream stream; value.GetDescription(stream); variable_value=stream.GetData(); } } } event_mutex.unlock(); return variable_value; } bool Debug::is_invalid() { bool invalid; event_mutex.lock(); invalid=state==lldb::StateType::eStateInvalid; event_mutex.unlock(); return invalid; } bool Debug::is_stopped() { bool stopped; event_mutex.lock(); stopped=state==lldb::StateType::eStateStopped; event_mutex.unlock(); return stopped; } bool Debug::is_running() { bool running; event_mutex.lock(); running=state==lldb::StateType::eStateRunning; event_mutex.unlock(); return running; } void Debug::add_breakpoint(const boost::filesystem::path &file_path, int line_nr) { event_mutex.lock(); if(state==lldb::eStateStopped || state==lldb::eStateRunning) { if(!(process->GetTarget().BreakpointCreateByLocation(file_path.string().c_str(), line_nr)).IsValid()) Terminal::get().async_print("Error (debug): Could not create breakpoint at: "+file_path.string()+":"+std::to_string(line_nr)+'\n', true); } event_mutex.unlock(); } void Debug::remove_breakpoint(const boost::filesystem::path &file_path, int line_nr, int line_count) { event_mutex.lock(); if(state==lldb::eStateStopped || state==lldb::eStateRunning) { auto target=process->GetTarget(); for(int line_nr_try=line_nr;line_nr_try<line_count;line_nr_try++) { for(uint32_t b_index=0;b_index<target.GetNumBreakpoints();b_index++) { auto breakpoint=target.GetBreakpointAtIndex(b_index); for(uint32_t l_index=0;l_index<breakpoint.GetNumLocations();l_index++) { auto line_entry=breakpoint.GetLocationAtIndex(l_index).GetAddress().GetLineEntry(); if(line_entry.GetLine()==static_cast<uint32_t>(line_nr_try)) { auto file_spec=line_entry.GetFileSpec(); boost::filesystem::path breakpoint_path=file_spec.GetDirectory(); breakpoint_path/=file_spec.GetFilename(); if(breakpoint_path==file_path) { if(!target.BreakpointDelete(breakpoint.GetID())) Terminal::get().async_print("Error (debug): Could not delete breakpoint at: "+file_path.string()+":"+std::to_string(line_nr)+'\n', true); event_mutex.unlock(); return; } } } } } } event_mutex.unlock(); } void Debug::write(const std::string &buffer) { event_mutex.lock(); if(state==lldb::StateType::eStateRunning) { process->PutSTDIN(buffer.c_str(), buffer.size()); } event_mutex.unlock(); } <|endoftext|>
<commit_before>#pragma once class device final { public: device(const nlohmann::json& json) : json_(json), identifiers_(json.find("identifiers") != json.end() ? json["identifiers"] : nlohmann::json()), ignore_(false), disable_built_in_keyboard_if_exists_(false), simple_modifications_(json.find("simple_modifications") != json.end() ? json["simple_modifications"] : nlohmann::json::array()), fn_function_keys_(nlohmann::json::array()) { { const std::string key = "ignore"; if (json.find(key) != json.end() && json[key].is_boolean()) { ignore_ = json[key]; } } { const std::string key = "disable_built_in_keyboard_if_exists"; if (json.find(key) != json.end() && json[key].is_boolean()) { disable_built_in_keyboard_if_exists_ = json[key]; } } { const std::string key = "fn_function_keys"; if (json.find(key) != json.end()) { fn_function_keys_.update(json[key]); } } } nlohmann::json to_json(void) const { auto j = json_; j["identifiers"] = identifiers_; j["ignore"] = ignore_; j["disable_built_in_keyboard_if_exists"] = disable_built_in_keyboard_if_exists_; j["simple_modifications"] = simple_modifications_; j["fn_function_keys"] = fn_function_keys_; return j; } const device_identifiers& get_identifiers(void) const { return identifiers_; } bool get_ignore(void) const { return ignore_; } void set_ignore(bool value) { ignore_ = value; } bool get_disable_built_in_keyboard_if_exists(void) const { return disable_built_in_keyboard_if_exists_; } void set_disable_built_in_keyboard_if_exists(bool value) { disable_built_in_keyboard_if_exists_ = value; } const simple_modifications& get_simple_modifications(void) const { return simple_modifications_; } simple_modifications& get_simple_modifications(void) { return simple_modifications_; } const simple_modifications& get_fn_function_keys(void) const { return fn_function_keys_; } simple_modifications& get_fn_function_keys(void) { return fn_function_keys_; } private: nlohmann::json json_; device_identifiers identifiers_; bool ignore_; bool disable_built_in_keyboard_if_exists_; simple_modifications simple_modifications_; simple_modifications fn_function_keys_; }; <commit_msg>add device::make_default_fn_function_keys_json<commit_after>#pragma once class device final { public: device(const nlohmann::json& json) : json_(json), identifiers_(json.find("identifiers") != json.end() ? json["identifiers"] : nlohmann::json()), ignore_(false), disable_built_in_keyboard_if_exists_(false), simple_modifications_(json.find("simple_modifications") != json.end() ? json["simple_modifications"] : nlohmann::json::array()), fn_function_keys_(make_default_fn_function_keys_json()) { { const std::string key = "ignore"; if (json.find(key) != json.end() && json[key].is_boolean()) { ignore_ = json[key]; } } { const std::string key = "disable_built_in_keyboard_if_exists"; if (json.find(key) != json.end() && json[key].is_boolean()) { disable_built_in_keyboard_if_exists_ = json[key]; } } { const std::string key = "fn_function_keys"; if (json.find(key) != json.end()) { fn_function_keys_.update(json[key]); } } } static nlohmann::json make_default_fn_function_keys_json(void) { auto json = nlohmann::json::array(); json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f1"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f2"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f3"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f4"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f5"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f6"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f7"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f8"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f9"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f10"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f11"; json.back()["to"][""] = ""; json.push_back(nlohmann::json::object()); json.back()["from"]["key_code"] = "f12"; json.back()["to"][""] = ""; return json; } nlohmann::json to_json(void) const { auto j = json_; j["identifiers"] = identifiers_; j["ignore"] = ignore_; j["disable_built_in_keyboard_if_exists"] = disable_built_in_keyboard_if_exists_; j["simple_modifications"] = simple_modifications_; j["fn_function_keys"] = fn_function_keys_; return j; } const device_identifiers& get_identifiers(void) const { return identifiers_; } bool get_ignore(void) const { return ignore_; } void set_ignore(bool value) { ignore_ = value; } bool get_disable_built_in_keyboard_if_exists(void) const { return disable_built_in_keyboard_if_exists_; } void set_disable_built_in_keyboard_if_exists(bool value) { disable_built_in_keyboard_if_exists_ = value; } const simple_modifications& get_simple_modifications(void) const { return simple_modifications_; } simple_modifications& get_simple_modifications(void) { return simple_modifications_; } const simple_modifications& get_fn_function_keys(void) const { return fn_function_keys_; } simple_modifications& get_fn_function_keys(void) { return fn_function_keys_; } private: nlohmann::json json_; device_identifiers identifiers_; bool ignore_; bool disable_built_in_keyboard_if_exists_; simple_modifications simple_modifications_; simple_modifications fn_function_keys_; }; <|endoftext|>
<commit_before>#include <string.h> #include <node.h> #include <node_buffer.h> #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/ecdh.h> #include "eckey.h" using namespace v8; using namespace node; static Handle<Value> V8Exception(const char* msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } // Not sure where this came from. but looks like a function that should be part of openssl int static inline EC_KEY_regenerate_key(EC_KEY *eckey, const BIGNUM *priv_key) { if (!eckey) return 0; int ok = 0; BN_CTX *ctx = NULL; EC_POINT *pub_key = NULL; const EC_GROUP *group = EC_KEY_get0_group(eckey); if ((ctx = BN_CTX_new()) == NULL) goto err; pub_key = EC_POINT_new(group); if (pub_key == NULL) goto err; if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) goto err; EC_KEY_set_private_key(eckey, priv_key); EC_KEY_set_public_key(eckey, pub_key); ok = 1; err: if (pub_key) EC_POINT_free(pub_key); if (ctx != NULL) BN_CTX_free(ctx); return ok; } ECKey::ECKey(int curve) { mHasPrivateKey = false; mCurve = curve; mKey = EC_KEY_new_by_curve_name(mCurve); if (!mKey) { V8Exception("EC_KEY_new_by_curve_name Invalid curve?"); return; } } ECKey::~ECKey() { if (mKey) { EC_KEY_free(mKey); } } // Node module init void ECKey::Init(Handle<Object> exports) { Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("ECKey")); tpl->InstanceTemplate()->SetInternalFieldCount(1); //Accessors tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("HasPrivateKey"), GetHasPrivateKey); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PublicKey"), GetPublicKey); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PrivateKey"), GetPrivateKey); //Methods (Prototype) tpl->PrototypeTemplate()->Set(String::NewSymbol("sign"), FunctionTemplate::New(Sign)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("verifySignature"), FunctionTemplate::New(VerifySignature)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("deriveSharedSecret"), FunctionTemplate::New(DeriveSharedSecret)->GetFunction()); Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction()); exports->Set(String::NewSymbol("ECKey"), constructor); } // Node constructor function // new ECKey(curve, buffer, isPublic) Handle<Value> ECKey::New(const Arguments &args) { if (!args.IsConstructCall()) { return V8Exception("Must use new keyword"); } if (args[0]->IsUndefined()) { return V8Exception("First argument must be an ECCurve"); } HandleScope scope; ECKey *eckey = new ECKey(args[0]->NumberValue()); if (!args[1]->IsUndefined()) { if (!Buffer::HasInstance(args[1])) { return V8Exception("Second parameter must be a buffer"); } //we have a second parameter, check the third to see if it is public or private. Handle<Object> buffer = args[1]->ToObject(); const unsigned char *bufferData = (unsigned char *) Buffer::Data(buffer); if ((args[2]->IsUndefined()) || (args[2]->BooleanValue() == false)) { // it's a private key BIGNUM *bn = BN_bin2bn(bufferData, Buffer::Length(buffer), BN_new()); if (EC_KEY_regenerate_key(eckey->mKey, bn) == 0) { BN_clear_free(bn); return V8Exception("Invalid private key"); } BN_clear_free(bn); eckey->mHasPrivateKey = true; } else { // it's a public key if (!o2i_ECPublicKey(&(eckey->mKey), &bufferData, Buffer::Length(buffer))) { return V8Exception("o2i_ECPublicKey failed"); } } } else { if (!EC_KEY_generate_key(eckey->mKey)) { return V8Exception("EC_KEY_generate_key failed"); } eckey->mHasPrivateKey = true; } eckey->Wrap(args.Holder()); return args.Holder(); } // Node properity functions Handle<Value> ECKey::GetHasPrivateKey(Local<String> property, const AccessorInfo &info) { HandleScope scope; ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); return scope.Close(Boolean::New(eckey->mHasPrivateKey)); } Handle<Value> ECKey::GetPublicKey(Local<String> property, const AccessorInfo &info) { ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); const EC_GROUP *group = EC_KEY_get0_group(eckey->mKey); const EC_POINT *point = EC_KEY_get0_public_key(eckey->mKey); unsigned int nReq = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, NULL); if (!nReq) { return V8Exception("EC_POINT_point2oct error"); } unsigned char *buf, *buf2; buf = buf2 = (unsigned char *)malloc(nReq); if (EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, buf, nReq, NULL) != nReq) { return V8Exception("EC_POINT_point2oct didn't return correct size"); } HandleScope scope; Buffer *buffer = Buffer::New(nReq); memcpy(Buffer::Data(buffer), buf2, nReq); free(buf2); return scope.Close(buffer->handle_); } Handle<Value> ECKey::GetPrivateKey(Local<String> property, const AccessorInfo &info) { ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); const BIGNUM *bn = EC_KEY_get0_private_key(eckey->mKey); if (bn == NULL) { return V8Exception("EC_KEY_get0_private_key failed"); } int priv_size = BN_num_bytes(bn); unsigned char *priv_buf = (unsigned char *)malloc(priv_size); int n = BN_bn2bin(bn, priv_buf); if (n != priv_size) { return V8Exception("BN_bn2bin didn't return priv_size"); } HandleScope scope; Buffer *buffer = Buffer::New(priv_size); memcpy(Buffer::Data(buffer), priv_buf, priv_size); free(priv_buf); return scope.Close(buffer->handle_); } // Node method functions Handle<Value> ECKey::Sign(const Arguments &args) { HandleScope scope; ECKey * eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); if (!Buffer::HasInstance(args[0])) { return V8Exception("digest must be a buffer"); } if (!eckey->mHasPrivateKey) { return V8Exception("cannot sign without private key"); } Handle<Object> digest = args[0]->ToObject(); const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest); unsigned int digest_len = Buffer::Length(digest); ECDSA_SIG *sig = ECDSA_do_sign(digest_data, digest_len, eckey->mKey); if (!sig) { return V8Exception("ECDSA_do_sign"); } int sig_len = i2d_ECDSA_SIG(sig, NULL); if (!sig_len) { return V8Exception("i2d_ECDSA_SIG"); } unsigned char *sig_data, *sig_data2; sig_data = sig_data2 = (unsigned char *)malloc(sig_len); if (i2d_ECDSA_SIG(sig, &sig_data) != sig_len) { ECDSA_SIG_free(sig); free(sig_data2); return V8Exception("i2d_ECDSA_SIG didnot return correct length"); } ECDSA_SIG_free(sig); Buffer *result = Buffer::New(sig_len); memcpy(Buffer::Data(result), sig_data2, sig_len); free(sig_data2); return scope.Close(result->handle_); } Handle<Value> ECKey::VerifySignature(const Arguments &args) { HandleScope scope; ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); if (!Buffer::HasInstance(args[0])) { return V8Exception("digest must be a buffer"); } if (!Buffer::HasInstance(args[1])) { return V8Exception("signature must be a buffer"); } Handle<Object> digest = args[0]->ToObject(); Handle<Object> signature = args[1]->ToObject(); const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest); const unsigned char *signature_data = (unsigned char *)Buffer::Data(signature); unsigned int digest_len = Buffer::Length(digest); unsigned int signature_len = Buffer::Length(signature); int result = ECDSA_verify(0, digest_data, digest_len, signature_data, signature_len, eckey->mKey); if (result == -1) { return V8Exception("ECDSA_verify"); } else if (result == 0) { return scope.Close(Boolean::New(false)); } else if (result == 1) { return scope.Close(Boolean::New(true)); } else { return V8Exception("ECDSA_verify gave an unexpected return value"); } } Handle<Value> ECKey::DeriveSharedSecret(const Arguments &args) { HandleScope scope; if (args[0]->IsUndefined()) { return V8Exception("other is required"); } ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); ECKey *other = ObjectWrap::Unwrap<ECKey>(args[0]->ToObject()); if (!other) { return V8Exception("other must be an ECKey"); } unsigned char *secret = (unsigned char*)malloc(512); int len = ECDH_compute_key(secret, 512, EC_KEY_get0_public_key(other->mKey), eckey->mKey, NULL); Buffer *result = Buffer::New(len); memcpy(Buffer::Data(result), secret, len); free(secret); return scope.Close(result->handle_); } <commit_msg>added a more detailed exception for Invalid public keys<commit_after>#include <string.h> #include <node.h> #include <node_buffer.h> #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <openssl/ecdh.h> #include "eckey.h" using namespace v8; using namespace node; static Handle<Value> V8Exception(const char* msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } // Not sure where this came from. but looks like a function that should be part of openssl int static inline EC_KEY_regenerate_key(EC_KEY *eckey, const BIGNUM *priv_key) { if (!eckey) return 0; int ok = 0; BN_CTX *ctx = NULL; EC_POINT *pub_key = NULL; const EC_GROUP *group = EC_KEY_get0_group(eckey); if ((ctx = BN_CTX_new()) == NULL) goto err; pub_key = EC_POINT_new(group); if (pub_key == NULL) goto err; if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) goto err; EC_KEY_set_private_key(eckey, priv_key); EC_KEY_set_public_key(eckey, pub_key); ok = 1; err: if (pub_key) EC_POINT_free(pub_key); if (ctx != NULL) BN_CTX_free(ctx); return ok; } ECKey::ECKey(int curve) { mHasPrivateKey = false; mCurve = curve; mKey = EC_KEY_new_by_curve_name(mCurve); if (!mKey) { V8Exception("EC_KEY_new_by_curve_name Invalid curve?"); return; } } ECKey::~ECKey() { if (mKey) { EC_KEY_free(mKey); } } // Node module init void ECKey::Init(Handle<Object> exports) { Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("ECKey")); tpl->InstanceTemplate()->SetInternalFieldCount(1); //Accessors tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("HasPrivateKey"), GetHasPrivateKey); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PublicKey"), GetPublicKey); tpl->InstanceTemplate()->SetAccessor(String::NewSymbol("PrivateKey"), GetPrivateKey); //Methods (Prototype) tpl->PrototypeTemplate()->Set(String::NewSymbol("sign"), FunctionTemplate::New(Sign)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("verifySignature"), FunctionTemplate::New(VerifySignature)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("deriveSharedSecret"), FunctionTemplate::New(DeriveSharedSecret)->GetFunction()); Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction()); exports->Set(String::NewSymbol("ECKey"), constructor); } // Node constructor function // new ECKey(curve, buffer, isPublic) Handle<Value> ECKey::New(const Arguments &args) { if (!args.IsConstructCall()) { return V8Exception("Must use new keyword"); } if (args[0]->IsUndefined()) { return V8Exception("First argument must be an ECCurve"); } HandleScope scope; ECKey *eckey = new ECKey(args[0]->NumberValue()); if (!args[1]->IsUndefined()) { if (!Buffer::HasInstance(args[1])) { return V8Exception("Second parameter must be a buffer"); } //we have a second parameter, check the third to see if it is public or private. Handle<Object> buffer = args[1]->ToObject(); const unsigned char *bufferData = (unsigned char *) Buffer::Data(buffer); if ((args[2]->IsUndefined()) || (args[2]->BooleanValue() == false)) { // it's a private key BIGNUM *bn = BN_bin2bn(bufferData, Buffer::Length(buffer), BN_new()); if (EC_KEY_regenerate_key(eckey->mKey, bn) == 0) { BN_clear_free(bn); return V8Exception("Invalid private key"); } BN_clear_free(bn); eckey->mHasPrivateKey = true; } else { // it's a public key if (!o2i_ECPublicKey(&(eckey->mKey), &bufferData, Buffer::Length(buffer))) { return V8Exception("o2i_ECPublicKey failed, Invalid public key"); } } } else { if (!EC_KEY_generate_key(eckey->mKey)) { return V8Exception("EC_KEY_generate_key failed"); } eckey->mHasPrivateKey = true; } eckey->Wrap(args.Holder()); return args.Holder(); } // Node properity functions Handle<Value> ECKey::GetHasPrivateKey(Local<String> property, const AccessorInfo &info) { HandleScope scope; ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); return scope.Close(Boolean::New(eckey->mHasPrivateKey)); } Handle<Value> ECKey::GetPublicKey(Local<String> property, const AccessorInfo &info) { ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); const EC_GROUP *group = EC_KEY_get0_group(eckey->mKey); const EC_POINT *point = EC_KEY_get0_public_key(eckey->mKey); unsigned int nReq = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, NULL); if (!nReq) { return V8Exception("EC_POINT_point2oct error"); } unsigned char *buf, *buf2; buf = buf2 = (unsigned char *)malloc(nReq); if (EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, buf, nReq, NULL) != nReq) { return V8Exception("EC_POINT_point2oct didn't return correct size"); } HandleScope scope; Buffer *buffer = Buffer::New(nReq); memcpy(Buffer::Data(buffer), buf2, nReq); free(buf2); return scope.Close(buffer->handle_); } Handle<Value> ECKey::GetPrivateKey(Local<String> property, const AccessorInfo &info) { ECKey *eckey = ObjectWrap::Unwrap<ECKey>(info.Holder()); const BIGNUM *bn = EC_KEY_get0_private_key(eckey->mKey); if (bn == NULL) { return V8Exception("EC_KEY_get0_private_key failed"); } int priv_size = BN_num_bytes(bn); unsigned char *priv_buf = (unsigned char *)malloc(priv_size); int n = BN_bn2bin(bn, priv_buf); if (n != priv_size) { return V8Exception("BN_bn2bin didn't return priv_size"); } HandleScope scope; Buffer *buffer = Buffer::New(priv_size); memcpy(Buffer::Data(buffer), priv_buf, priv_size); free(priv_buf); return scope.Close(buffer->handle_); } // Node method functions Handle<Value> ECKey::Sign(const Arguments &args) { HandleScope scope; ECKey * eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); if (!Buffer::HasInstance(args[0])) { return V8Exception("digest must be a buffer"); } if (!eckey->mHasPrivateKey) { return V8Exception("cannot sign without private key"); } Handle<Object> digest = args[0]->ToObject(); const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest); unsigned int digest_len = Buffer::Length(digest); ECDSA_SIG *sig = ECDSA_do_sign(digest_data, digest_len, eckey->mKey); if (!sig) { return V8Exception("ECDSA_do_sign"); } int sig_len = i2d_ECDSA_SIG(sig, NULL); if (!sig_len) { return V8Exception("i2d_ECDSA_SIG"); } unsigned char *sig_data, *sig_data2; sig_data = sig_data2 = (unsigned char *)malloc(sig_len); if (i2d_ECDSA_SIG(sig, &sig_data) != sig_len) { ECDSA_SIG_free(sig); free(sig_data2); return V8Exception("i2d_ECDSA_SIG didnot return correct length"); } ECDSA_SIG_free(sig); Buffer *result = Buffer::New(sig_len); memcpy(Buffer::Data(result), sig_data2, sig_len); free(sig_data2); return scope.Close(result->handle_); } Handle<Value> ECKey::VerifySignature(const Arguments &args) { HandleScope scope; ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); if (!Buffer::HasInstance(args[0])) { return V8Exception("digest must be a buffer"); } if (!Buffer::HasInstance(args[1])) { return V8Exception("signature must be a buffer"); } Handle<Object> digest = args[0]->ToObject(); Handle<Object> signature = args[1]->ToObject(); const unsigned char *digest_data = (unsigned char *)Buffer::Data(digest); const unsigned char *signature_data = (unsigned char *)Buffer::Data(signature); unsigned int digest_len = Buffer::Length(digest); unsigned int signature_len = Buffer::Length(signature); int result = ECDSA_verify(0, digest_data, digest_len, signature_data, signature_len, eckey->mKey); if (result == -1) { return V8Exception("ECDSA_verify"); } else if (result == 0) { return scope.Close(Boolean::New(false)); } else if (result == 1) { return scope.Close(Boolean::New(true)); } else { return V8Exception("ECDSA_verify gave an unexpected return value"); } } Handle<Value> ECKey::DeriveSharedSecret(const Arguments &args) { HandleScope scope; if (args[0]->IsUndefined()) { return V8Exception("other is required"); } ECKey *eckey = ObjectWrap::Unwrap<ECKey>(args.Holder()); ECKey *other = ObjectWrap::Unwrap<ECKey>(args[0]->ToObject()); if (!other) { return V8Exception("other must be an ECKey"); } unsigned char *secret = (unsigned char*)malloc(512); int len = ECDH_compute_key(secret, 512, EC_KEY_get0_public_key(other->mKey), eckey->mKey, NULL); Buffer *result = Buffer::New(len); memcpy(Buffer::Data(result), secret, len); free(secret); return scope.Close(result->handle_); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_CORE_RECOVER_MEMORY_NESTED_HPP #define STAN_MATH_REV_CORE_RECOVER_MEMORY_NESTED_HPP #include <stan/math/rev/core/chainable.hpp> #include <stan/math/rev/core/chainable_alloc.hpp> #include <stan/math/rev/core/chainablestack.hpp> #include <stan/math/rev/core/empty_nested.hpp> #include <stdexcept> namespace stan { namespace math { /** * Recover only the memory used for the top nested call. If there * is nothing on the nested stack, then a * <code>std::logic_error</code> exception is thrown. * * @throw std::logic_error if <code>empty_nested()</code> returns * <code>true</code> */ static inline void recover_memory_nested() { if (empty_nested()) throw std::logic_error("empty_nested() must be false" " before calling recover_memory_nested()"); ChainableStack::var_stack_ .resize(ChainableStack::nested_var_stack_sizes_.back()); ChainableStack::nested_var_stack_sizes_.pop_back(); ChainableStack::var_nochain_stack_ .resize(ChainableStack::nested_var_nochain_stack_sizes_.back()); ChainableStack::nested_var_nochain_stack_sizes_.pop_back(); for (size_t i = ChainableStack::nested_var_alloc_stack_starts_.back(); i < ChainableStack::var_alloc_stack_.size(); ++i) { delete ChainableStack::var_alloc_stack_[i]; } ChainableStack::var_alloc_stack_.resize (ChainableStack::nested_var_alloc_stack_starts_.back()); ChainableStack::nested_var_alloc_stack_starts_.pop_back(); ChainableStack::memalloc_.recover_nested(); } } } #endif <commit_msg>removing last include for chainable.hpp<commit_after>#ifndef STAN_MATH_REV_CORE_RECOVER_MEMORY_NESTED_HPP #define STAN_MATH_REV_CORE_RECOVER_MEMORY_NESTED_HPP #include <stan/math/rev/core/chainable_alloc.hpp> #include <stan/math/rev/core/chainablestack.hpp> #include <stan/math/rev/core/empty_nested.hpp> #include <stdexcept> namespace stan { namespace math { /** * Recover only the memory used for the top nested call. If there * is nothing on the nested stack, then a * <code>std::logic_error</code> exception is thrown. * * @throw std::logic_error if <code>empty_nested()</code> returns * <code>true</code> */ static inline void recover_memory_nested() { if (empty_nested()) throw std::logic_error("empty_nested() must be false" " before calling recover_memory_nested()"); ChainableStack::var_stack_ .resize(ChainableStack::nested_var_stack_sizes_.back()); ChainableStack::nested_var_stack_sizes_.pop_back(); ChainableStack::var_nochain_stack_ .resize(ChainableStack::nested_var_nochain_stack_sizes_.back()); ChainableStack::nested_var_nochain_stack_sizes_.pop_back(); for (size_t i = ChainableStack::nested_var_alloc_stack_starts_.back(); i < ChainableStack::var_alloc_stack_.size(); ++i) { delete ChainableStack::var_alloc_stack_[i]; } ChainableStack::var_alloc_stack_.resize (ChainableStack::nested_var_alloc_stack_starts_.back()); ChainableStack::nested_var_alloc_stack_starts_.pop_back(); ChainableStack::memalloc_.recover_nested(); } } } #endif <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "jsonwrite.h" #include <assert.h> #include <fstream> #include <iostream> #include <iterator> #include <log.h> #include <map> #include <string> #include "nextpnr.h" #include "version.h" NEXTPNR_NAMESPACE_BEGIN namespace JsonWriter { std::string get_string(std::string str) { std::string newstr = "\""; for (char c : str) { if (c == '\\') newstr += c; newstr += c; } return newstr + "\""; } std::string get_name(IdString name, Context *ctx) { return get_string(name.c_str(ctx)); } void write_parameter_value(std::ostream &f, const Property &value) { if (value.size() == 32 && value.is_fully_def()) { f << stringf("%d", value.as_int64()); } else { f << get_string(value.to_string()); } } void write_parameters(std::ostream &f, Context *ctx, const std::unordered_map<IdString, Property> &parameters, bool for_module = false) { bool first = true; for (auto &param : parameters) { f << stringf("%s\n", first ? "" : ","); f << stringf(" %s%s: ", for_module ? "" : " ", get_name(param.first, ctx).c_str()); write_parameter_value(f, param.second); first = false; } } struct PortGroup { std::string name; std::vector<int> bits; PortType dir; }; std::vector<PortGroup> group_ports(Context *ctx) { std::vector<PortGroup> groups; std::unordered_map<std::string, size_t> base_to_group; for (auto &pair : ctx->ports) { std::string name = pair.second.name.str(ctx); if ((name.back() != ']') || (name.find('[') == std::string::npos)) { groups.push_back({name, {pair.first.index}, pair.second.type}); } else { int off1 = int(name.find_last_of('[')); std::string basename = name.substr(0, off1); int index = std::stoi(name.substr(off1 + 1, name.size() - (off1 + 2))); if (!base_to_group.count(basename)) { base_to_group[basename] = groups.size(); groups.push_back({basename, std::vector<int>(index + 1, -1), pair.second.type}); } auto &grp = groups.at(base_to_group[basename]); if (int(grp.bits.size()) <= index) grp.bits.resize(index + 1, -1); NPNR_ASSERT(grp.bits.at(index) == -1); grp.bits.at(index) = pair.second.net ? pair.second.net->name.index : pair.first.index; } } return groups; }; std::string format_port_bits(const PortGroup &port) { std::stringstream s; s << "[ "; bool first = true; for (auto bit : port.bits) { if (!first) s << ", "; if (bit == -1) s << "\"x\""; else s << bit; first = false; } s << " ]"; return s.str(); } void write_module(std::ostream &f, Context *ctx) { auto val = ctx->attrs.find(ctx->id("module")); if (val != ctx->attrs.end()) f << stringf(" %s: {\n", get_string(val->second.as_string()).c_str()); else f << stringf(" %s: {\n", get_string("top").c_str()); f << stringf(" \"settings\": {"); write_parameters(f, ctx, ctx->settings, true); f << stringf("\n },\n"); f << stringf(" \"attributes\": {"); write_parameters(f, ctx, ctx->attrs, true); f << stringf("\n },\n"); f << stringf(" \"ports\": {"); auto ports = group_ports(ctx); bool first = true; for (auto &port : ports) { f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_string(port.name).c_str()); f << stringf(" \"direction\": \"%s\",\n", port.dir == PORT_IN ? "input" : port.dir == PORT_INOUT ? "inout" : "output"); f << stringf(" \"bits\": %s\n", format_port_bits(port).c_str()); f << stringf(" }"); first = false; } f << stringf("\n },\n"); f << stringf(" \"cells\": {"); first = true; for (auto &pair : ctx->cells) { auto &c = pair.second; f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_name(c->name, ctx).c_str()); f << stringf(" \"hide_name\": %s,\n", c->name.c_str(ctx)[0] == '$' ? "1" : "0"); f << stringf(" \"type\": %s,\n", get_name(c->type, ctx).c_str()); f << stringf(" \"parameters\": {"); write_parameters(f, ctx, c->params); f << stringf("\n },\n"); f << stringf(" \"attributes\": {"); write_parameters(f, ctx, c->attrs); f << stringf("\n },\n"); f << stringf(" \"port_directions\": {"); bool first2 = true; for (auto &conn : c->ports) { auto &p = conn.second; std::string direction = (p.type == PORT_IN) ? "input" : (p.type == PORT_OUT) ? "output" : "inout"; f << stringf("%s\n", first2 ? "" : ","); f << stringf(" %s: \"%s\"", get_name(conn.first, ctx).c_str(), direction.c_str()); first2 = false; } f << stringf("\n },\n"); f << stringf(" \"connections\": {"); first2 = true; for (auto &conn : c->ports) { auto &p = conn.second; f << stringf("%s\n", first2 ? "" : ","); if (p.net) f << stringf(" %s: [ %d ]", get_name(conn.first, ctx).c_str(), p.net->name.index); else f << stringf(" %s: [ ]", get_name(conn.first, ctx).c_str()); first2 = false; } f << stringf("\n }\n"); f << stringf(" }"); first = false; } f << stringf("\n },\n"); f << stringf(" \"netnames\": {"); first = true; for (auto &pair : ctx->nets) { auto &w = pair.second; f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_name(w->name, ctx).c_str()); f << stringf(" \"hide_name\": %s,\n", w->name.c_str(ctx)[0] == '$' ? "1" : "0"); f << stringf(" \"bits\": [ %d ] ,\n", pair.first.index); f << stringf(" \"attributes\": {"); write_parameters(f, ctx, w->attrs); f << stringf("\n }\n"); f << stringf(" }"); first = false; } f << stringf("\n }\n"); f << stringf(" }"); } void write_context(std::ostream &f, Context *ctx) { f << stringf("{\n"); f << stringf(" \"creator\": %s,\n", get_string("Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")").c_str()); f << stringf(" \"modules\": {\n"); write_module(f, ctx); f << stringf("\n }"); f << stringf("\n}\n"); } }; // End Namespace JsonWriter bool write_json_file(std::ostream &f, std::string &filename, Context *ctx) { try { using namespace JsonWriter; if (!f) log_error("failed to open JSON file.\n"); write_context(f, ctx); log_break(); return true; } catch (log_execution_error_exception) { return false; } } NEXTPNR_NAMESPACE_END <commit_msg>jsonwrite: Fix bus cell ports<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "jsonwrite.h" #include <assert.h> #include <fstream> #include <iostream> #include <iterator> #include <log.h> #include <map> #include <string> #include "nextpnr.h" #include "version.h" NEXTPNR_NAMESPACE_BEGIN namespace JsonWriter { std::string get_string(std::string str) { std::string newstr = "\""; for (char c : str) { if (c == '\\') newstr += c; newstr += c; } return newstr + "\""; } std::string get_name(IdString name, Context *ctx) { return get_string(name.c_str(ctx)); } void write_parameter_value(std::ostream &f, const Property &value) { if (value.size() == 32 && value.is_fully_def()) { f << stringf("%d", value.as_int64()); } else { f << get_string(value.to_string()); } } void write_parameters(std::ostream &f, Context *ctx, const std::unordered_map<IdString, Property> &parameters, bool for_module = false) { bool first = true; for (auto &param : parameters) { f << stringf("%s\n", first ? "" : ","); f << stringf(" %s%s: ", for_module ? "" : " ", get_name(param.first, ctx).c_str()); write_parameter_value(f, param.second); first = false; } } struct PortGroup { std::string name; std::vector<int> bits; PortType dir; }; std::vector<PortGroup> group_ports(Context *ctx, const std::unordered_map<IdString, PortInfo> &ports, bool is_cell = false) { std::vector<PortGroup> groups; std::unordered_map<std::string, size_t> base_to_group; for (auto &pair : ports) { std::string name = pair.second.name.str(ctx); if ((name.back() != ']') || (name.find('[') == std::string::npos)) { groups.push_back({name, {is_cell ? (pair.second.net ? pair.second.net->name.index : -1) : pair.first.index}, pair.second.type}); } else { int off1 = int(name.find_last_of('[')); std::string basename = name.substr(0, off1); int index = std::stoi(name.substr(off1 + 1, name.size() - (off1 + 2))); if (!base_to_group.count(basename)) { base_to_group[basename] = groups.size(); groups.push_back({basename, std::vector<int>(index + 1, -1), pair.second.type}); } auto &grp = groups.at(base_to_group[basename]); if (int(grp.bits.size()) <= index) grp.bits.resize(index + 1, -1); NPNR_ASSERT(grp.bits.at(index) == -1); grp.bits.at(index) = pair.second.net ? pair.second.net->name.index : (is_cell ? -1 : pair.first.index); } } return groups; } std::string format_port_bits(const PortGroup &port, int &dummy_idx) { std::stringstream s; s << "[ "; bool first = true; if (port.bits.size() != 1 || port.bits.at(0) != -1) // skip single disconnected ports for (auto bit : port.bits) { if (!first) s << ", "; if (bit == -1) s << (++dummy_idx); else s << bit; first = false; } s << " ]"; return s.str(); } void write_module(std::ostream &f, Context *ctx) { auto val = ctx->attrs.find(ctx->id("module")); int dummy_idx = int(ctx->idstring_idx_to_str->size()) + 1000; if (val != ctx->attrs.end()) f << stringf(" %s: {\n", get_string(val->second.as_string()).c_str()); else f << stringf(" %s: {\n", get_string("top").c_str()); f << stringf(" \"settings\": {"); write_parameters(f, ctx, ctx->settings, true); f << stringf("\n },\n"); f << stringf(" \"attributes\": {"); write_parameters(f, ctx, ctx->attrs, true); f << stringf("\n },\n"); f << stringf(" \"ports\": {"); auto ports = group_ports(ctx, ctx->ports); bool first = true; for (auto &port : ports) { f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_string(port.name).c_str()); f << stringf(" \"direction\": \"%s\",\n", port.dir == PORT_IN ? "input" : port.dir == PORT_INOUT ? "inout" : "output"); f << stringf(" \"bits\": %s\n", format_port_bits(port, dummy_idx).c_str()); f << stringf(" }"); first = false; } f << stringf("\n },\n"); f << stringf(" \"cells\": {"); first = true; for (auto &pair : ctx->cells) { auto &c = pair.second; auto cell_ports = group_ports(ctx, c->ports, true); f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_name(c->name, ctx).c_str()); f << stringf(" \"hide_name\": %s,\n", c->name.c_str(ctx)[0] == '$' ? "1" : "0"); f << stringf(" \"type\": %s,\n", get_name(c->type, ctx).c_str()); f << stringf(" \"parameters\": {"); write_parameters(f, ctx, c->params); f << stringf("\n },\n"); f << stringf(" \"attributes\": {"); write_parameters(f, ctx, c->attrs); f << stringf("\n },\n"); f << stringf(" \"port_directions\": {"); bool first2 = true; for (auto &pg : cell_ports) { std::string direction = (pg.dir == PORT_IN) ? "input" : (pg.dir == PORT_OUT) ? "output" : "inout"; f << stringf("%s\n", first2 ? "" : ","); f << stringf(" %s: \"%s\"", get_string(pg.name).c_str(), direction.c_str()); first2 = false; } f << stringf("\n },\n"); f << stringf(" \"connections\": {"); first2 = true; for (auto &pg : cell_ports) { f << stringf("%s\n", first2 ? "" : ","); f << stringf(" %s: %s", get_string(pg.name).c_str(), format_port_bits(pg, dummy_idx).c_str()); first2 = false; } f << stringf("\n }\n"); f << stringf(" }"); first = false; } f << stringf("\n },\n"); f << stringf(" \"netnames\": {"); first = true; for (auto &pair : ctx->nets) { auto &w = pair.second; f << stringf("%s\n", first ? "" : ","); f << stringf(" %s: {\n", get_name(w->name, ctx).c_str()); f << stringf(" \"hide_name\": %s,\n", w->name.c_str(ctx)[0] == '$' ? "1" : "0"); f << stringf(" \"bits\": [ %d ] ,\n", pair.first.index); f << stringf(" \"attributes\": {"); write_parameters(f, ctx, w->attrs); f << stringf("\n }\n"); f << stringf(" }"); first = false; } f << stringf("\n }\n"); f << stringf(" }"); } void write_context(std::ostream &f, Context *ctx) { f << stringf("{\n"); f << stringf(" \"creator\": %s,\n", get_string("Next Generation Place and Route (git sha1 " GIT_COMMIT_HASH_STR ")").c_str()); f << stringf(" \"modules\": {\n"); write_module(f, ctx); f << stringf("\n }"); f << stringf("\n}\n"); } }; // End Namespace JsonWriter bool write_json_file(std::ostream &f, std::string &filename, Context *ctx) { try { using namespace JsonWriter; if (!f) log_error("failed to open JSON file.\n"); write_context(f, ctx); log_break(); return true; } catch (log_execution_error_exception) { return false; } } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>#ifndef __EVAL_HPP__ #define __EVAL_HPP__ #include <iostream> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <boost/unordered_map.hpp> #include <iomanip> #include <boost/format.hpp> #include "util.hpp" typedef struct { std::string id; std::string gold; std::string sys; double score; } s_res; class evaluator { public: std::vector< s_res > results; unsigned int tp; unsigned int tn; unsigned int fp; unsigned int fn; unsigned int correct_num; unsigned int false_num; std::vector< std::string > labels; public: evaluator() { correct_num = 0; false_num = 0; } ~evaluator() { } private: unsigned int count_utf8( const std::string str ) { unsigned int size = 0; bool first = true; std::string tmp; for (size_t i=0 ; i<=str.size() ; ++i) { if (first || (i != str.size() && (str.at(i) & 0xc0) == 0x80)) { tmp += str.at(i); first = false; continue; } if (tmp.size() > 1) { size += 2; } else { size += 1; } } return size; } unsigned int max_width(std::vector<std::string> labels) { unsigned int width = 0; BOOST_FOREACH (std::string label, labels) { unsigned int size = count_utf8(label); if (size > width) { width = size; } } return width; } public: void add( std::string id, std::string gold, std::string sys ) { s_res res; res.id = id; res.gold = gold; res.sys = sys; results.push_back(res); } void add( std::string id, std::string gold, std::string sys, double score ) { s_res res; res.id = id; res.gold = gold; res.sys = sys; res.score = score; results.push_back(res); } void eval() { correct_num = 0; false_num = 0; labels.clear(); BOOST_FOREACH (s_res res, results) { if (res.gold == res.sys) { correct_num++; } else { false_num++; } if (find(labels.begin(), labels.end(), res.gold) == labels.end()) { labels.push_back(res.gold); } if (find(labels.begin(), labels.end(), res.sys) == labels.end()) { labels.push_back(res.sys); } } } void print_prec_rec() { unsigned int width = max_width(labels); width += 2; double prec_sum = 0.0, rec_sum = 0.0; BOOST_FOREACH (std::string label, labels) { for (unsigned int i=0 ; i<(width-count_utf8(label)) ; ++i) { std::cout << " "; } std::cout << label << ", "; unsigned int tp = 0; unsigned int tn = 0; unsigned int fp = 0; unsigned int fn = 0; BOOST_FOREACH (s_res res, results) { if (res.sys == label && res.gold == label) { tp++; } else if (res.sys == label && res.gold != label) { fp++; } else if (res.sys != label && res.gold == label) { fn++; } else { tn++; } } double prec = -1.0, rec = -1.0; if (tp+fp == 0) { std::cout << std::setw(4) << "-"; } else { prec = (double)tp / (double)(tp+fp); prec_sum += prec; std::cout << boost::format("%4.2lf") % (prec); } std::cout << ", "; std::cout << "(" << boost::format("%6d") % (tp) << "/" << boost::format("%6d") % (tp+fp) << "), "; if (tp+fn == 0) { std::cout << std::setw(4) << "-"; } else { rec = (double)tp / (double)(tp+fn); rec_sum += rec; std::cout << boost::format("%4.2lf") % (rec); } std::cout << ", "; std::cout << "(" << boost::format("%6d") % (tp) << "/" << boost::format("%6d") % (tp+fn) << ")"; if (prec != -1.0 && rec != -1.0) { std::cout << ", " << boost::format("%4.2lf") % (2 * prec * rec / (prec + rec)); } std::cout << std::endl; } double macro_prec = prec_sum / labels.size(); double macro_rec = rec_sum / labels.size(); std::cout << "Macro Precision: " << boost::format("%4.2lf") % (macro_prec) << std::endl; std::cout << "Macro Recall: " << boost::format("%4.2lf") % (macro_rec) << std::endl; std::cout << "Macro F1: " << boost::format("%4.2lf") % (2 * macro_prec * macro_rec / (macro_prec + macro_rec)) << std::endl; } void print_confusion_matrix() { unsigned int width = max_width(labels); width += 2; boost::unordered_map<std::string, int> label_w; std::string sg = "sys\\gold"; for (unsigned int i=0 ; i<(width-count_utf8(sg)) ; i++) { std::cout << " "; } std::cout << "sys\\gold"; BOOST_FOREACH (std::string label, labels) { unsigned int w = count_utf8(label); if (w<7) { label_w[label] = 6; } else { label_w[label] = w; } std::cout << ", "; for (unsigned int i=0 ; i<(label_w[label]-w) ; i++) { std::cout << " "; } std::cout << label; } std::cout << std::endl; BOOST_FOREACH (std::string label_sys, labels) { for (unsigned int i=0 ; i<(width-count_utf8(label_sys)) ; i++) { std::cout << " "; } std::cout << label_sys; unsigned int cnt_sys = 0; BOOST_FOREACH (std::string label_gold, labels) { unsigned int cnt=0; BOOST_FOREACH (s_res res, results) { if (res.gold == label_gold && res.sys == label_sys) { cnt++; cnt_sys++; } } std::cout << "," << std::setw(label_w[label_gold]+1) << cnt; } std::cout << ", " << cnt_sys << std::endl; } } double accuracy() { return (double)correct_num / (double)(correct_num + false_num); } }; #endif <commit_msg>Fixed a bug in output confusion matrix<commit_after>#ifndef __EVAL_HPP__ #define __EVAL_HPP__ #include <iostream> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <boost/unordered_map.hpp> #include <iomanip> #include <boost/format.hpp> #include "util.hpp" typedef struct { std::string id; std::string gold; std::string sys; double score; } s_res; class evaluator { public: std::vector< s_res > results; unsigned int tp; unsigned int tn; unsigned int fp; unsigned int fn; unsigned int correct_num; unsigned int false_num; std::vector< std::string > labels; public: evaluator() { correct_num = 0; false_num = 0; } ~evaluator() { } private: unsigned int count_utf8( const std::string str ) { unsigned int size = 0; bool first = true; std::string tmp; for (size_t i=0 ; i<=str.size() ; ++i) { if (first || (i != str.size() && (str.at(i) & 0xc0) == 0x80)) { tmp += str.at(i); first = false; continue; } if (tmp.size() > 1) { size += 2; } else { size += 1; } } return size; } unsigned int max_width(std::vector<std::string> labels) { unsigned int width = 0; BOOST_FOREACH (std::string label, labels) { unsigned int size = count_utf8(label); if (size > width) { width = size; } } return width; } public: void add( std::string id, std::string gold, std::string sys ) { s_res res; res.id = id; res.gold = gold; res.sys = sys; results.push_back(res); } void add( std::string id, std::string gold, std::string sys, double score ) { s_res res; res.id = id; res.gold = gold; res.sys = sys; res.score = score; results.push_back(res); } void eval() { correct_num = 0; false_num = 0; labels.clear(); BOOST_FOREACH (s_res res, results) { if (res.gold == res.sys) { correct_num++; } else { false_num++; } if (find(labels.begin(), labels.end(), res.gold) == labels.end()) { labels.push_back(res.gold); } if (find(labels.begin(), labels.end(), res.sys) == labels.end()) { labels.push_back(res.sys); } } } void print_prec_rec() { unsigned int width = max_width(labels); width += 2; double prec_sum = 0.0, rec_sum = 0.0; BOOST_FOREACH (std::string label, labels) { for (unsigned int i=0 ; i<(width-count_utf8(label)) ; ++i) { std::cout << " "; } std::cout << label << ", "; unsigned int tp = 0; unsigned int tn = 0; unsigned int fp = 0; unsigned int fn = 0; BOOST_FOREACH (s_res res, results) { if (res.sys == label && res.gold == label) { tp++; } else if (res.sys == label && res.gold != label) { fp++; } else if (res.sys != label && res.gold == label) { fn++; } else { tn++; } } double prec = -1.0, rec = -1.0; if (tp+fp == 0) { std::cout << std::setw(4) << "-"; } else { prec = (double)tp / (double)(tp+fp); prec_sum += prec; std::cout << boost::format("%4.2lf") % (prec); } std::cout << ", "; std::cout << "(" << boost::format("%6d") % (tp) << "/" << boost::format("%6d") % (tp+fp) << "), "; if (tp+fn == 0) { std::cout << std::setw(4) << "-"; } else { rec = (double)tp / (double)(tp+fn); rec_sum += rec; std::cout << boost::format("%4.2lf") % (rec); } std::cout << ", "; std::cout << "(" << boost::format("%6d") % (tp) << "/" << boost::format("%6d") % (tp+fn) << ")"; if (prec != -1.0 && rec != -1.0) { std::cout << ", " << boost::format("%4.2lf") % (2 * prec * rec / (prec + rec)); } std::cout << std::endl; } double macro_prec = prec_sum / labels.size(); double macro_rec = rec_sum / labels.size(); std::cout << "Macro Precision: " << boost::format("%4.2lf") % (macro_prec) << std::endl; std::cout << "Macro Recall: " << boost::format("%4.2lf") % (macro_rec) << std::endl; std::cout << "Macro F1: " << boost::format("%4.2lf") % (2 * macro_prec * macro_rec / (macro_prec + macro_rec)) << std::endl; } void print_confusion_matrix() { unsigned int width = max_width(labels); width += 2; boost::unordered_map<std::string, int> label_w; std::string sg = "sys\\gold"; unsigned int sg_size = count_utf8(sg); if (width < sg_size) { width = sg_size; } for (unsigned int i=0 ; i<(width-count_utf8(sg)) ; i++) { std::cout << " "; } std::cout << "sys\\gold"; BOOST_FOREACH (std::string label, labels) { unsigned int w = count_utf8(label); if (w<7) { label_w[label] = 6; } else { label_w[label] = w; } std::cout << ", "; for (unsigned int i=0 ; i<(label_w[label]-w) ; i++) { std::cout << " "; } std::cout << label; } std::cout << std::endl; BOOST_FOREACH (std::string label_sys, labels) { for (unsigned int i=0 ; i<(width-count_utf8(label_sys)) ; i++) { std::cout << " "; } std::cout << label_sys; unsigned int cnt_sys = 0; BOOST_FOREACH (std::string label_gold, labels) { unsigned int cnt=0; BOOST_FOREACH (s_res res, results) { if (res.gold == label_gold && res.sys == label_sys) { cnt++; cnt_sys++; } } std::cout << "," << std::setw(label_w[label_gold]+1) << cnt; } std::cout << ", " << cnt_sys << std::endl; } } double accuracy() { return (double)correct_num / (double)(correct_num + false_num); } }; #endif <|endoftext|>
<commit_before>///===--- GlobalExecutor.cpp - Global concurrent executor ------------------===/// /// /// This source file is part of the Swift.org open source project /// /// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors /// Licensed under Apache License v2.0 with Runtime Library Exception /// /// See https:///swift.org/LICENSE.txt for license information /// See https:///swift.org/CONTRIBUTORS.txt for the list of Swift project authors /// ///===----------------------------------------------------------------------===/// /// /// Routines related to the global concurrent execution service. /// /// The execution side of Swift's concurrency model centers around /// scheduling work onto various execution services ("executors"). /// Executors vary in several different dimensions: /// /// First, executors may be exclusive or concurrent. An exclusive /// executor can only execute one job at once; a concurrent executor /// can execute many. Exclusive executors are usually used to achieve /// some higher-level requirement, like exclusive access to some /// resource or memory. Concurrent executors are usually used to /// manage a pool of threads and prevent the number of allocated /// threads from growing without limit. /// /// Second, executors may own dedicated threads, or they may schedule /// work onto some some underlying executor. Dedicated threads can /// improve the responsiveness of a subsystem *locally*, but they impose /// substantial costs which can drive down performance *globally* /// if not used carefully. When an executor relies on running work /// on its own dedicated threads, jobs that need to run briefly on /// that executor may need to suspend and restart. Dedicating threads /// to an executor is a decision that should be made carefully /// and holistically. /// /// If most executors should not have dedicated threads, they must /// be backed by some underlying executor, typically a concurrent /// executor. The purpose of most concurrent executors is to /// manage threads and prevent excessive growth in the number /// of threads. Having multiple independent concurrent executors /// with their own dedicated threads would undermine that. /// Therefore, it is sensible to have a single, global executor /// that will ultimately schedule most of the work in the system. /// With that as a baseline, special needs can be recognized and /// carved out from the global executor with its cooperation. /// /// This file defines Swift's interface to that global executor. /// /// The default implementation is backed by libdispatch, but there /// may be good reasons to provide alternatives (e.g. when building /// a single-threaded runtime). /// ///===----------------------------------------------------------------------===/// #include "swift/Runtime/Concurrency.h" #include "TaskPrivate.h" #include <dispatch/dispatch.h> using namespace swift; SWIFT_CC(swift) void (*swift::swift_task_enqueueGlobal_hook)(Job *job) = nullptr; SWIFT_CC(swift) void (*swift::swift_task_enqueueGlobalWithDelay_hook)(unsigned long long delay, Job *job) = nullptr; #if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR #include <chrono> #include <thread> static Job *JobQueue = nullptr; class DelayedJob { public: Job *job; unsigned long long when; DelayedJob *next; DelayedJob(Job *job, unsigned long long when) : job(job), when(when), next(nullptr) {} }; static DelayedJob *DelayedJobQueue = nullptr; /// Get the next-in-queue storage slot. static Job *&nextInQueue(Job *cur) { return reinterpret_cast<Job*&>(cur->SchedulerPrivate); } /// Insert a job into the cooperative global queue. static void insertIntoJobQueue(Job *newJob) { Job **position = &JobQueue; while (auto cur = *position) { // If we find a job with lower priority, insert here. if (cur->getPriority() < newJob->getPriority()) { nextInQueue(newJob) = cur; *position = newJob; return; } // Otherwise, keep advancing through the queue. position = &nextInQueue(cur); } nextInQueue(newJob) = nullptr; *position = newJob; } static unsigned long long currentNanos() { auto now = std::chrono::steady_clock::now(); auto nowNanos = std::chrono::time_point_cast<std::chrono::nanoseconds>(now); auto value = std::chrono::duration_cast<std::chrono::nanoseconds>(nowNanos.time_since_epoch()); return value.count(); } /// Insert a job into the cooperative global queue. static void insertIntoDelayedJobQueue(unsigned long long delay, Job *job) { DelayedJob **position = &DelayedJobQueue; DelayedJob *newJob = new DelayedJob(job, currentNanos() + delay); while (auto cur = *position) { // If we find a job with lower priority, insert here. if (cur->when > newJob->when) { newJob->next = cur; *position = newJob; return; } // Otherwise, keep advancing through the queue. position = &cur->next; } *position = newJob; } /// Claim the next job from the cooperative global queue. static Job *claimNextFromJobQueue() { // Check delayed jobs first while (true) { if (auto delayedJob = DelayedJobQueue) { if (delayedJob->when < currentNanos()) { DelayedJobQueue = delayedJob->next; auto job = delayedJob->job; delete delayedJob; return job; } } if (auto job = JobQueue) { JobQueue = nextInQueue(job); return job; } // there are only delayed jobs left, but they are not ready, // so we sleep until the first one is if (auto delayedJob = DelayedJobQueue) { std::this_thread::sleep_for(std::chrono::nanoseconds(delayedJob->when - currentNanos())); continue; } return nullptr; } } void swift::donateThreadToGlobalExecutorUntil(bool (*condition)(void *), void *conditionContext) { while (!condition(conditionContext)) { auto job = claimNextFromJobQueue(); if (!job) return; job->run(ExecutorRef::generic()); } } #else /// The function passed to dispatch_async_f to execute a job. static void __swift_run_job(void *_job) { Job *job = (Job*) _job; swift_job_run(job, ExecutorRef::generic()); } /// A specialized version of __swift_run_job to execute the job on the main /// executor. /// FIXME: only exists for the quick-and-dirty MainActor implementation. static void __swift_run_job_main_executor(void *_job) { Job *job = (Job*) _job; swift_job_run(job, ExecutorRef::mainExecutor()); } #endif void swift::swift_task_enqueueGlobal(Job *job) { assert(job && "no job provided"); // If the hook is defined, use it. if (swift_task_enqueueGlobal_hook) return swift_task_enqueueGlobal_hook(job); #if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR insertIntoJobQueue(job); #else // We really want four things from the global execution service: // - Enqueuing work should have minimal runtime and memory overhead. // - Adding work should never result in an "explosion" where many // more threads are created than the available cores. // - Jobs should run on threads with an appropriate priority. // - Thread priorities should temporarily elevatable to avoid // priority inversions. // // Of these, the first two are the most important. Many programs // do not rely on high-usage priority scheduling, and many priority // inversions can be avoided at a higher level (albeit with some // performance cost, e.g. by creating higher-priority tasks to run // critical sections that contend with high-priority work). In // contrast, if the async feature adds too much overhead, or if // heavy use of it leads to thread explosions and memory exhaustion, // programmers will have no choice but to stop using it. So if // goals are in conflict, it's best to focus on core properties over // priority-inversion avoidance. // We currently use Dispatch for our thread pool on all platforms. // Dispatch currently backs its serial queues with a global // concurrent queue that is prone to thread explosions when a flood // of jobs are added to it. That problem does not apply equally // to the global concurrent queues returned by dispatch_get_global_queue, // which are not strictly CPU-limited but are at least much more // cautious about adding new threads. We cannot safely elevate // the priorities of work added to this queue using Dispatch's public // API, but as discussed above, that is less important than avoiding // performance problems. dispatch_function_t dispatchFunction = &__swift_run_job; void *dispatchContext = job; JobPriority priority = job->getPriority(); // TODO: cache this to avoid the extra call auto queue = dispatch_get_global_queue((dispatch_qos_class_t) priority, /*flags*/ 0); dispatch_async_f(queue, dispatchContext, dispatchFunction); #endif } void swift::swift_task_enqueueGlobalWithDelay(unsigned long long delay, Job *job) { assert(job && "no job provided"); // If the hook is defined, use it. if (swift_task_enqueueGlobalWithDelay_hook) return swift_task_enqueueGlobalWithDelay_hook(delay, job); #if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR insertIntoDelayedJobQueue(delay, job); #else dispatch_function_t dispatchFunction = &__swift_run_job; void *dispatchContext = job; JobPriority priority = job->getPriority(); // TODO: cache this to avoid the extra call auto queue = dispatch_get_global_queue((dispatch_qos_class_t) priority, /*flags*/ 0); dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, delay); dispatch_after_f(when, queue, dispatchContext, dispatchFunction); #endif } /// Enqueues a task on the main executor. /// FIXME: only exists for the quick-and-dirty MainActor implementation. void swift::swift_task_enqueueMainExecutor(Job *job) { assert(job && "no job provided"); #if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR insertIntoJobQueue(job); #else dispatch_function_t dispatchFunction = &__swift_run_job_main_executor; void *dispatchContext = job; // TODO: cache this to avoid the extra call auto mainQueue = dispatch_get_main_queue(); dispatch_async_f(mainQueue, dispatchContext, dispatchFunction); #endif } <commit_msg>[Concurrency] Cache the queue returned from dispatch_get_global_queue.<commit_after>///===--- GlobalExecutor.cpp - Global concurrent executor ------------------===/// /// /// This source file is part of the Swift.org open source project /// /// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors /// Licensed under Apache License v2.0 with Runtime Library Exception /// /// See https:///swift.org/LICENSE.txt for license information /// See https:///swift.org/CONTRIBUTORS.txt for the list of Swift project authors /// ///===----------------------------------------------------------------------===/// /// /// Routines related to the global concurrent execution service. /// /// The execution side of Swift's concurrency model centers around /// scheduling work onto various execution services ("executors"). /// Executors vary in several different dimensions: /// /// First, executors may be exclusive or concurrent. An exclusive /// executor can only execute one job at once; a concurrent executor /// can execute many. Exclusive executors are usually used to achieve /// some higher-level requirement, like exclusive access to some /// resource or memory. Concurrent executors are usually used to /// manage a pool of threads and prevent the number of allocated /// threads from growing without limit. /// /// Second, executors may own dedicated threads, or they may schedule /// work onto some some underlying executor. Dedicated threads can /// improve the responsiveness of a subsystem *locally*, but they impose /// substantial costs which can drive down performance *globally* /// if not used carefully. When an executor relies on running work /// on its own dedicated threads, jobs that need to run briefly on /// that executor may need to suspend and restart. Dedicating threads /// to an executor is a decision that should be made carefully /// and holistically. /// /// If most executors should not have dedicated threads, they must /// be backed by some underlying executor, typically a concurrent /// executor. The purpose of most concurrent executors is to /// manage threads and prevent excessive growth in the number /// of threads. Having multiple independent concurrent executors /// with their own dedicated threads would undermine that. /// Therefore, it is sensible to have a single, global executor /// that will ultimately schedule most of the work in the system. /// With that as a baseline, special needs can be recognized and /// carved out from the global executor with its cooperation. /// /// This file defines Swift's interface to that global executor. /// /// The default implementation is backed by libdispatch, but there /// may be good reasons to provide alternatives (e.g. when building /// a single-threaded runtime). /// ///===----------------------------------------------------------------------===/// #include "swift/Runtime/Concurrency.h" #include "TaskPrivate.h" #include <dispatch/dispatch.h> using namespace swift; SWIFT_CC(swift) void (*swift::swift_task_enqueueGlobal_hook)(Job *job) = nullptr; SWIFT_CC(swift) void (*swift::swift_task_enqueueGlobalWithDelay_hook)(unsigned long long delay, Job *job) = nullptr; #if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR #include <chrono> #include <thread> static Job *JobQueue = nullptr; class DelayedJob { public: Job *job; unsigned long long when; DelayedJob *next; DelayedJob(Job *job, unsigned long long when) : job(job), when(when), next(nullptr) {} }; static DelayedJob *DelayedJobQueue = nullptr; /// Get the next-in-queue storage slot. static Job *&nextInQueue(Job *cur) { return reinterpret_cast<Job*&>(cur->SchedulerPrivate); } /// Insert a job into the cooperative global queue. static void insertIntoJobQueue(Job *newJob) { Job **position = &JobQueue; while (auto cur = *position) { // If we find a job with lower priority, insert here. if (cur->getPriority() < newJob->getPriority()) { nextInQueue(newJob) = cur; *position = newJob; return; } // Otherwise, keep advancing through the queue. position = &nextInQueue(cur); } nextInQueue(newJob) = nullptr; *position = newJob; } static unsigned long long currentNanos() { auto now = std::chrono::steady_clock::now(); auto nowNanos = std::chrono::time_point_cast<std::chrono::nanoseconds>(now); auto value = std::chrono::duration_cast<std::chrono::nanoseconds>(nowNanos.time_since_epoch()); return value.count(); } /// Insert a job into the cooperative global queue. static void insertIntoDelayedJobQueue(unsigned long long delay, Job *job) { DelayedJob **position = &DelayedJobQueue; DelayedJob *newJob = new DelayedJob(job, currentNanos() + delay); while (auto cur = *position) { // If we find a job with lower priority, insert here. if (cur->when > newJob->when) { newJob->next = cur; *position = newJob; return; } // Otherwise, keep advancing through the queue. position = &cur->next; } *position = newJob; } /// Claim the next job from the cooperative global queue. static Job *claimNextFromJobQueue() { // Check delayed jobs first while (true) { if (auto delayedJob = DelayedJobQueue) { if (delayedJob->when < currentNanos()) { DelayedJobQueue = delayedJob->next; auto job = delayedJob->job; delete delayedJob; return job; } } if (auto job = JobQueue) { JobQueue = nextInQueue(job); return job; } // there are only delayed jobs left, but they are not ready, // so we sleep until the first one is if (auto delayedJob = DelayedJobQueue) { std::this_thread::sleep_for(std::chrono::nanoseconds(delayedJob->when - currentNanos())); continue; } return nullptr; } } void swift::donateThreadToGlobalExecutorUntil(bool (*condition)(void *), void *conditionContext) { while (!condition(conditionContext)) { auto job = claimNextFromJobQueue(); if (!job) return; job->run(ExecutorRef::generic()); } } #else /// The function passed to dispatch_async_f to execute a job. static void __swift_run_job(void *_job) { Job *job = (Job*) _job; swift_job_run(job, ExecutorRef::generic()); } /// A specialized version of __swift_run_job to execute the job on the main /// executor. /// FIXME: only exists for the quick-and-dirty MainActor implementation. static void __swift_run_job_main_executor(void *_job) { Job *job = (Job*) _job; swift_job_run(job, ExecutorRef::mainExecutor()); } static constexpr size_t globalQueueCacheCount = static_cast<size_t>(JobPriority::UserInteractive) + 1; static std::atomic<dispatch_queue_t> globalQueueCache[globalQueueCacheCount]; static dispatch_queue_t getGlobalQueue(JobPriority priority) { size_t numericPriority = static_cast<size_t>(priority); if (numericPriority >= globalQueueCacheCount) fatalError(0, "invalid job priority %#zx"); auto *ptr = &globalQueueCache[numericPriority]; auto queue = ptr->load(std::memory_order_relaxed); if (SWIFT_LIKELY(queue)) return queue; // If we don't have a queue cached for this priority, cache it now. This may // race with other threads doing this at the same time for this priority, but // that's OK, they'll all end up writing the same value. queue = dispatch_get_global_queue((dispatch_qos_class_t)priority, /*flags*/ 0); // Unconditionally store it back in the cache. If we raced with another // thread, we'll just overwrite the entry with the same value. ptr->store(queue, std::memory_order_relaxed); return queue; } #endif void swift::swift_task_enqueueGlobal(Job *job) { assert(job && "no job provided"); // If the hook is defined, use it. if (swift_task_enqueueGlobal_hook) return swift_task_enqueueGlobal_hook(job); #if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR insertIntoJobQueue(job); #else // We really want four things from the global execution service: // - Enqueuing work should have minimal runtime and memory overhead. // - Adding work should never result in an "explosion" where many // more threads are created than the available cores. // - Jobs should run on threads with an appropriate priority. // - Thread priorities should temporarily elevatable to avoid // priority inversions. // // Of these, the first two are the most important. Many programs // do not rely on high-usage priority scheduling, and many priority // inversions can be avoided at a higher level (albeit with some // performance cost, e.g. by creating higher-priority tasks to run // critical sections that contend with high-priority work). In // contrast, if the async feature adds too much overhead, or if // heavy use of it leads to thread explosions and memory exhaustion, // programmers will have no choice but to stop using it. So if // goals are in conflict, it's best to focus on core properties over // priority-inversion avoidance. // We currently use Dispatch for our thread pool on all platforms. // Dispatch currently backs its serial queues with a global // concurrent queue that is prone to thread explosions when a flood // of jobs are added to it. That problem does not apply equally // to the global concurrent queues returned by dispatch_get_global_queue, // which are not strictly CPU-limited but are at least much more // cautious about adding new threads. We cannot safely elevate // the priorities of work added to this queue using Dispatch's public // API, but as discussed above, that is less important than avoiding // performance problems. dispatch_function_t dispatchFunction = &__swift_run_job; void *dispatchContext = job; JobPriority priority = job->getPriority(); auto queue = getGlobalQueue(priority); dispatch_async_f(queue, dispatchContext, dispatchFunction); #endif } void swift::swift_task_enqueueGlobalWithDelay(unsigned long long delay, Job *job) { assert(job && "no job provided"); // If the hook is defined, use it. if (swift_task_enqueueGlobalWithDelay_hook) return swift_task_enqueueGlobalWithDelay_hook(delay, job); #if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR insertIntoDelayedJobQueue(delay, job); #else dispatch_function_t dispatchFunction = &__swift_run_job; void *dispatchContext = job; JobPriority priority = job->getPriority(); auto queue = getGlobalQueue(priority); dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, delay); dispatch_after_f(when, queue, dispatchContext, dispatchFunction); #endif } /// Enqueues a task on the main executor. /// FIXME: only exists for the quick-and-dirty MainActor implementation. void swift::swift_task_enqueueMainExecutor(Job *job) { assert(job && "no job provided"); #if SWIFT_CONCURRENCY_COOPERATIVE_GLOBAL_EXECUTOR insertIntoJobQueue(job); #else dispatch_function_t dispatchFunction = &__swift_run_job_main_executor; void *dispatchContext = job; // This is an inline function that compiles down to a pointer to a global. auto mainQueue = dispatch_get_main_queue(); dispatch_async_f(mainQueue, dispatchContext, dispatchFunction); #endif } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2006 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // interface headers #include "HUDuiFrame.h" // system headers #include <iostream> // common headers #include "bzfgl.h" #include "OpenGLGState.h" #include "FontManager.h" // // HUDuiFrame // HUDuiFrame::HUDuiFrame() : lineWidth(1.0f), style(RectangleStyle) { color[0] = 1.0f; color[1] = 1.0f; color[2] = 1.0f; color[3] = 1.0f; skipRenderLabel = true; } HUDuiFrame::~HUDuiFrame() { } void HUDuiFrame::drawArc(float x, float y, float r, int sides, float atAngle, float arcAngle) { // sanity if (sides <= 0) sides = 1; float i = arcAngle / sides; glPushMatrix(); // center glTranslatef(x, y, 0); // draw glBegin(GL_LINE_STRIP); for (float a = atAngle; a - (atAngle + arcAngle) < 0.001f; a += i) { glVertex2f(r * cos(a), r * sin(a)); } glEnd(); glPopMatrix(); } void HUDuiFrame::doRender() { const float height = getHeight(); const float width = getWidth(); const int fontFace = getFontFace(); const float fontSize = getFontSize(); const float x = getX(); const float y = getY(); FontManager &fm = FontManager::instance(); const float labelWidth = std::max(getLabelWidth(), fm.getStrLength(fontFace, fontSize, getLabel())); const float labelGap = fm.getStrLength(fontFace, fontSize, "9"); const float frameY = y + fontSize / 2; const float frameX = x - labelGap; const float frameWidth = labelGap * 2 + width; // set up appearance OpenGLGState::resetState(); // fixme: shouldn't be needed glLineWidth(lineWidth); glColor4fv(color); // render frame switch (style) { case RectangleStyle: { glBegin(GL_LINES); glVertex2f(frameX, frameY); glVertex2f(frameX, frameY - height); glVertex2f(frameX, frameY - height); glVertex2f(frameX + frameWidth, frameY - height); glVertex2f(frameX + frameWidth, frameY - height); glVertex2f(frameX + frameWidth, frameY); if (width > labelWidth + labelGap) { glVertex2f(frameX + frameWidth, frameY); glVertex2f(frameX + labelWidth + labelGap, frameY); glVertex2f(frameX, frameY); glVertex2f(frameX + labelGap, frameY); } glEnd(); } break; case RoundedRectStyle: { glBegin(GL_LINES); glVertex2f(frameX, frameY - labelGap); glVertex2f(frameX, frameY - height + labelGap); glVertex2f(frameX + labelGap, frameY - height); glVertex2f(frameX + frameWidth - labelGap, frameY - height); glVertex2f(frameX + frameWidth, frameY - height + labelGap); glVertex2f(frameX + frameWidth, frameY - labelGap); if (width > labelWidth + labelGap) { glVertex2f(frameX + frameWidth - labelGap, frameY); glVertex2f(frameX + labelWidth + labelGap, frameY); } glEnd(); const float ninety = (float) M_PI / 2.0f; drawArc(frameX + frameWidth - labelGap, frameY - labelGap, labelGap, 20, 0, ninety); drawArc(frameX + labelGap, frameY - labelGap, labelGap, 20, ninety, ninety); drawArc(frameX + labelGap, frameY - height + labelGap, labelGap, 20, 2*ninety, ninety); drawArc(frameX + frameWidth - labelGap, frameY - height + labelGap, labelGap, 20, 3*ninety, ninety); } break; } // render label fm.drawString(x, y, 0, fontFace, fontSize, getLabel()); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>smooth dem lines<commit_after>/* bzflag * Copyright (c) 1993 - 2006 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // interface headers #include "HUDuiFrame.h" // system headers #include <iostream> // common headers #include "bzfgl.h" #include "OpenGLGState.h" #include "FontManager.h" #include "BZDBCache.h" // // HUDuiFrame // HUDuiFrame::HUDuiFrame() : lineWidth(1.0f), style(RectangleStyle) { color[0] = 1.0f; color[1] = 1.0f; color[2] = 1.0f; color[3] = 1.0f; skipRenderLabel = true; } HUDuiFrame::~HUDuiFrame() { } void HUDuiFrame::drawArc(float x, float y, float r, int sides, float atAngle, float arcAngle) { // sanity if (sides <= 0) sides = 1; float i = arcAngle / sides; glPushMatrix(); // center glTranslatef(x, y, 0); // draw glBegin(GL_LINE_STRIP); for (float a = atAngle; a - (atAngle + arcAngle) < 0.001f; a += i) { glVertex2f(r * cos(a), r * sin(a)); } glEnd(); glPopMatrix(); } void HUDuiFrame::doRender() { const float height = getHeight(); const float width = getWidth(); const int fontFace = getFontFace(); const float fontSize = getFontSize(); const float x = getX(); const float y = getY(); FontManager &fm = FontManager::instance(); const float labelWidth = std::max(getLabelWidth(), fm.getStrLength(fontFace, fontSize, getLabel())); const float labelGap = fm.getStrLength(fontFace, fontSize, "9"); const float frameY = y + fontSize / 2; const float frameX = x - labelGap; const float frameWidth = labelGap * 2 + width; // set up appearance OpenGLGState::resetState(); // fixme: shouldn't be needed glLineWidth(lineWidth); glColor4fv(color); const bool antialias = BZDBCache::blend && BZDBCache::smooth; if (antialias) { glEnable(GL_BLEND); glEnable(GL_LINE_SMOOTH); } // render frame switch (style) { case RectangleStyle: { glBegin(GL_LINES); glVertex2f(frameX, frameY); glVertex2f(frameX, frameY - height); glVertex2f(frameX, frameY - height); glVertex2f(frameX + frameWidth, frameY - height); glVertex2f(frameX + frameWidth, frameY - height); glVertex2f(frameX + frameWidth, frameY); if (width > labelWidth + labelGap) { glVertex2f(frameX + frameWidth, frameY); glVertex2f(frameX + labelWidth + labelGap, frameY); glVertex2f(frameX, frameY); glVertex2f(frameX + labelGap, frameY); } glEnd(); } break; case RoundedRectStyle: { glBegin(GL_LINES); glVertex2f(frameX, frameY - labelGap); glVertex2f(frameX, frameY - height + labelGap); glVertex2f(frameX + labelGap, frameY - height); glVertex2f(frameX + frameWidth - labelGap, frameY - height); glVertex2f(frameX + frameWidth, frameY - height + labelGap); glVertex2f(frameX + frameWidth, frameY - labelGap); if (width > labelWidth + labelGap) { glVertex2f(frameX + frameWidth - labelGap, frameY); glVertex2f(frameX + labelWidth + labelGap, frameY); } glEnd(); const float ninety = (float) M_PI / 2.0f; drawArc(frameX + frameWidth - labelGap, frameY - labelGap, labelGap, 20, 0, ninety); drawArc(frameX + labelGap, frameY - labelGap, labelGap, 20, ninety, ninety); drawArc(frameX + labelGap, frameY - height + labelGap, labelGap, 20, 2*ninety, ninety); drawArc(frameX + frameWidth - labelGap, frameY - height + labelGap, labelGap, 20, 3*ninety, ninety); } break; } if (antialias) { glDisable(GL_BLEND); glDisable(GL_LINE_SMOOTH); } // render label fm.drawString(x, y, 0, fontFace, fontSize, getLabel()); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/** * @file ToStringTest.cpp * @author Ryan Birmingham * * Test of the AugmentedLagrangian class using the test functions defined in * aug_lagrangian_test_functions.hpp. **/ #include <mlpack/core.hpp> #include <mlpack/core.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" #include <mlpack/core/metrics/ip_metric.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <mlpack/core/metrics/mahalanobis_distance.hpp> #include <mlpack/core/kernels/pspectrum_string_kernel.hpp> #include <mlpack/core/kernels/pspectrum_string_kernel.hpp> #include <mlpack/core/kernels/example_kernel.hpp> #include <mlpack/core/optimizers/aug_lagrangian/aug_lagrangian.hpp> #include <mlpack/core/optimizers/lbfgs/lbfgs.hpp> //#include <mlpack/core/optimizers/lrsdp/lrsdp.hpp> #include <mlpack/core/optimizers/sgd/sgd.hpp> #include <mlpack/methods/nca/nca_softmax_error_function.hpp> #include <mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_test_functions.hpp> #include <mlpack/core/tree/ballbound.hpp> #include <mlpack/core/tree/binary_space_tree.hpp> #include <mlpack/core/tree/bounds.hpp> #include <mlpack/core/tree/mrkd_statistic.hpp> #include <mlpack/core/tree/hrectbound.hpp> #include <mlpack/core/tree/periodichrectbound.hpp> #include <mlpack/core/tree/statistic.hpp> #include <mlpack/methods/cf/cf.hpp> #include <mlpack/methods/det/dtree.hpp> #include <mlpack/methods/emst/dtb.hpp> #include <mlpack/methods/fastmks/fastmks.hpp> #include <mlpack/methods/gmm/gmm.hpp> #include <mlpack/methods/hmm/hmm.hpp> #include <mlpack/methods/kernel_pca/kernel_pca.hpp> #include <mlpack/methods/kmeans/kmeans.hpp> #include <mlpack/methods/lars/lars.hpp> #include <mlpack/methods/linear_regression/linear_regression.hpp> #include <mlpack/methods/local_coordinate_coding/lcc.hpp> #include <mlpack/methods/logistic_regression/logistic_regression.hpp> using namespace mlpack; using namespace mlpack::kernel; using namespace mlpack::distribution; using namespace mlpack::metric; using namespace mlpack::nca; using namespace mlpack::bound; using namespace mlpack::tree; //using namespace mlpack::optimization; BOOST_AUTO_TEST_SUITE(ToStringTest); BOOST_AUTO_TEST_CASE(DiscreteDistributionString) { DiscreteDistribution d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(GaussianDistributionString) { GaussianDistribution d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(CosineDistanceString) { CosineDistance d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(EpanechnikovKernelString) { EpanechnikovKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(ExampleKernelString) { ExampleKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(GaussianKernelString) { GaussianKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(HyperbolicTangentKernelString) { HyperbolicTangentKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LaplacianKernelString) { LaplacianKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LinearKernelString) { LinearKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(PolynomialKernelString) { PolynomialKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(PSpectrumStringKernelString) { const std::vector<std::vector<std::string> > s; const size_t t=1; PSpectrumStringKernel d(s,t); Log::Debug << d; std::string sttm = d.ToString(); BOOST_REQUIRE_NE(sttm, ""); } BOOST_AUTO_TEST_CASE(SphericalKernelString) { SphericalKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(TriangularKernelString) { TriangularKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(IPMetricString) { IPMetric<TriangularKernel> d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LMetricString) { LMetric<1> d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(MahalanobisDistanceString) { MahalanobisDistance<> d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(SGDString) { const arma::mat g(2,2); const arma::Col<size_t> v(2); SoftmaxErrorFunction<> a(g,v); mlpack::optimization::SGD<SoftmaxErrorFunction<> > d(a); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(L_BFGSString) { const arma::mat g(2,2); const arma::Col<size_t> v(2); SoftmaxErrorFunction<> a(g,v); mlpack::optimization::L_BFGS<SoftmaxErrorFunction<> > d(a); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(AugLagString) { mlpack::optimization::AugLagrangianTestFunction a; mlpack::optimization::AugLagrangianFunction <mlpack::optimization::AugLagrangianTestFunction> q(a); mlpack::optimization::AugLagrangian <mlpack::optimization::AugLagrangianTestFunction> d(a); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(BallBoundString) { BallBound<> d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(BinSpaceString) { arma::mat q(2,2); q.randu(); BinarySpaceTree<HRectBound<1> > d(q); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } /** BOOST_AUTO_TEST_CASE(CFString) { size_t a = 1 ; arma::mat c(3,3); c(0, 0) = 0; c(0, 1) = 1; c(0, 2) = 1.5; c(1, 0) = 1; c(1, 1) = 2; c(1, 2) = 2.0; c(2, 0) = 0; c(2, 1) = 2; c(2, 2) = 0.7; mlpack::cf::CF d(a,a,c); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } **/ BOOST_AUTO_TEST_CASE(DetString) { arma::mat c(4,4); c.randn(); mlpack::det::DTree d(c); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(EmstString) { arma::mat c(4,4); c.randu(); mlpack::emst::DualTreeBoruvka<> d(c); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(FastMKSString) { arma::mat c(4,4); c.randn(); mlpack::fastmks::FastMKS<LinearKernel> d(c); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(GMMString) { arma::mat c(400,40); c.randn(); mlpack::gmm::GMM<> d(5, 4); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(HMMString) { mlpack::hmm::HMM<> d(5,4); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(KPCAString) { LinearKernel k; mlpack::kpca::KernelPCA<LinearKernel> d(k,false); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(KMeansString) { mlpack::kmeans::KMeans<metric::ManhattanDistance> d(100, 4.0); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LarsString) { mlpack::regression::LARS::LARS d(false); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LinRegString) { arma::mat c(40,40); arma::mat b(40,1); c.randn(); b.randn(); mlpack::regression::LinearRegression::LinearRegression d(c,b); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LCCString) { arma::mat c(40,40); const size_t b=3; const double a=1; c.randn(); mlpack::lcc::LocalCoordinateCoding<> d(c,b,a); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LogRegString) { arma::mat c(40,40); arma::mat b(40,1); c.randn(); b.randn(); mlpack::regression::LogisticRegression<> d(c,b); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Fix collaborative filtering test (#323).<commit_after>/** * @file ToStringTest.cpp * @author Ryan Birmingham * * Test of the AugmentedLagrangian class using the test functions defined in * aug_lagrangian_test_functions.hpp. **/ #include <mlpack/core.hpp> #include <mlpack/core.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" #include <mlpack/core/metrics/ip_metric.hpp> #include <mlpack/core/metrics/lmetric.hpp> #include <mlpack/core/metrics/mahalanobis_distance.hpp> #include <mlpack/core/kernels/pspectrum_string_kernel.hpp> #include <mlpack/core/kernels/pspectrum_string_kernel.hpp> #include <mlpack/core/kernels/example_kernel.hpp> #include <mlpack/core/optimizers/aug_lagrangian/aug_lagrangian.hpp> #include <mlpack/core/optimizers/lbfgs/lbfgs.hpp> //#include <mlpack/core/optimizers/lrsdp/lrsdp.hpp> #include <mlpack/core/optimizers/sgd/sgd.hpp> #include <mlpack/methods/nca/nca_softmax_error_function.hpp> #include <mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_test_functions.hpp> #include <mlpack/core/tree/ballbound.hpp> #include <mlpack/core/tree/binary_space_tree.hpp> #include <mlpack/core/tree/bounds.hpp> #include <mlpack/core/tree/mrkd_statistic.hpp> #include <mlpack/core/tree/hrectbound.hpp> #include <mlpack/core/tree/periodichrectbound.hpp> #include <mlpack/core/tree/statistic.hpp> #include <mlpack/methods/cf/cf.hpp> #include <mlpack/methods/det/dtree.hpp> #include <mlpack/methods/emst/dtb.hpp> #include <mlpack/methods/fastmks/fastmks.hpp> #include <mlpack/methods/gmm/gmm.hpp> #include <mlpack/methods/hmm/hmm.hpp> #include <mlpack/methods/kernel_pca/kernel_pca.hpp> #include <mlpack/methods/kmeans/kmeans.hpp> #include <mlpack/methods/lars/lars.hpp> #include <mlpack/methods/linear_regression/linear_regression.hpp> #include <mlpack/methods/local_coordinate_coding/lcc.hpp> #include <mlpack/methods/logistic_regression/logistic_regression.hpp> using namespace mlpack; using namespace mlpack::kernel; using namespace mlpack::distribution; using namespace mlpack::metric; using namespace mlpack::nca; using namespace mlpack::bound; using namespace mlpack::tree; //using namespace mlpack::optimization; BOOST_AUTO_TEST_SUITE(ToStringTest); BOOST_AUTO_TEST_CASE(DiscreteDistributionString) { DiscreteDistribution d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(GaussianDistributionString) { GaussianDistribution d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(CosineDistanceString) { CosineDistance d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(EpanechnikovKernelString) { EpanechnikovKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(ExampleKernelString) { ExampleKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(GaussianKernelString) { GaussianKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(HyperbolicTangentKernelString) { HyperbolicTangentKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LaplacianKernelString) { LaplacianKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LinearKernelString) { LinearKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(PolynomialKernelString) { PolynomialKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(PSpectrumStringKernelString) { const std::vector<std::vector<std::string> > s; const size_t t=1; PSpectrumStringKernel d(s,t); Log::Debug << d; std::string sttm = d.ToString(); BOOST_REQUIRE_NE(sttm, ""); } BOOST_AUTO_TEST_CASE(SphericalKernelString) { SphericalKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(TriangularKernelString) { TriangularKernel d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(IPMetricString) { IPMetric<TriangularKernel> d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LMetricString) { LMetric<1> d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(MahalanobisDistanceString) { MahalanobisDistance<> d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(SGDString) { const arma::mat g(2,2); const arma::Col<size_t> v(2); SoftmaxErrorFunction<> a(g,v); mlpack::optimization::SGD<SoftmaxErrorFunction<> > d(a); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(L_BFGSString) { const arma::mat g(2,2); const arma::Col<size_t> v(2); SoftmaxErrorFunction<> a(g,v); mlpack::optimization::L_BFGS<SoftmaxErrorFunction<> > d(a); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(AugLagString) { mlpack::optimization::AugLagrangianTestFunction a; mlpack::optimization::AugLagrangianFunction <mlpack::optimization::AugLagrangianTestFunction> q(a); mlpack::optimization::AugLagrangian <mlpack::optimization::AugLagrangianTestFunction> d(a); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(BallBoundString) { BallBound<> d; Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(BinSpaceString) { arma::mat q(2,2); q.randu(); BinarySpaceTree<HRectBound<1> > d(q); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(CFString) { size_t a = 1 ; arma::mat c(3,3); c(0, 0) = 1; c(0, 1) = 2; c(0, 2) = 1.5; c(1, 0) = 2; c(1, 1) = 3; c(1, 2) = 2.0; c(2, 0) = 1; c(2, 1) = 3; c(2, 2) = 0.7; mlpack::cf::CF d(a,a,c); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(DetString) { arma::mat c(4,4); c.randn(); mlpack::det::DTree d(c); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(EmstString) { arma::mat c(4,4); c.randu(); mlpack::emst::DualTreeBoruvka<> d(c); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(FastMKSString) { arma::mat c(4,4); c.randn(); mlpack::fastmks::FastMKS<LinearKernel> d(c); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(GMMString) { arma::mat c(400,40); c.randn(); mlpack::gmm::GMM<> d(5, 4); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(HMMString) { mlpack::hmm::HMM<> d(5,4); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(KPCAString) { LinearKernel k; mlpack::kpca::KernelPCA<LinearKernel> d(k,false); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(KMeansString) { mlpack::kmeans::KMeans<metric::ManhattanDistance> d(100, 4.0); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LarsString) { mlpack::regression::LARS d(false); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LinRegString) { arma::mat c(40,40); arma::mat b(40,1); c.randn(); b.randn(); mlpack::regression::LinearRegression d(c,b); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LCCString) { arma::mat c(40,40); const size_t b=3; const double a=1; c.randn(); mlpack::lcc::LocalCoordinateCoding<> d(c,b,a); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_CASE(LogRegString) { arma::mat c(40,40); arma::mat b(40,1); c.randn(); b.randn(); mlpack::regression::LogisticRegression<> d(c,b); Log::Debug << d; std::string s = d.ToString(); BOOST_REQUIRE_NE(s, ""); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // 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., // 51 Franklin Street, Fifth Floor, // Boston, MA // 02110-1301 // USA // //////////////////////////////////////////////////////////////////////////////// #include <fstream> #include <sstream> #include <Context.h> #include <Uri.h> #include <Transport.h> #include <text.h> #include <util.h> #include <CmdMerge.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdMerge::CmdMerge () { _keyword = "merge"; _usage = "task merge URL"; _description = "Merges the specified undo.data file with the local data files."; _read_only = false; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdMerge::execute (std::string& output) { // invoke gc before merging in order to update data files context.tdb.gc (); context.tdb2.gc (); std::vector <std::string> words = context.a3.extract_words (); std::string file; if (words.size ()) file = words[0]; std::string pushfile = ""; std::string tmpfile = ""; std::string sAutopush = lowerCase (context.config.get ("merge.autopush")); bool bAutopush = context.config.getBoolean ("merge.autopush"); Uri uri (file, "merge"); uri.parse(); if (uri._data.length ()) { Directory location (context.config.get ("data.location")); // be sure that uri points to a file uri.append ("undo.data"); Transport* transport; if ((transport = Transport::getTransport (uri)) != NULL ) { tmpfile = location._data + "/undo_remote.data"; transport->recv (tmpfile); delete transport; file = tmpfile; } else file = uri._path; context.tdb2.merge (file); output += "Merge complete.\n"; if (tmpfile != "") remove (tmpfile.c_str ()); if ( ((sAutopush == "ask") && (confirm ("Would you like to push the merged changes to \'" + uri._data + "\'?")) ) || (bAutopush) ) { // TODO derive autopush uri from merge.default.uri? otherwise: change prompt above // context.task.set ("description", uri._data); std::string out; context.commands["push"]->execute (out); } } else throw std::string ("No uri was specified for the merge. Either specify " "the uri of a remote .task directory, or create a " "'merge.default.uri' entry in your .taskrc file."); return 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>TDB2<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // 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., // 51 Franklin Street, Fifth Floor, // Boston, MA // 02110-1301 // USA // //////////////////////////////////////////////////////////////////////////////// #include <fstream> #include <sstream> #include <Context.h> #include <Uri.h> #include <Transport.h> #include <text.h> #include <util.h> #include <CmdMerge.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdMerge::CmdMerge () { _keyword = "merge"; _usage = "task merge URL"; _description = "Merges the specified undo.data file with the local data files."; _read_only = false; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdMerge::execute (std::string& output) { // invoke gc and commit before merging in order to update data files context.tdb2.gc (); context.tdb2.commit (); std::vector <std::string> words = context.a3.extract_words (); std::string file; if (words.size ()) file = words[0]; std::string pushfile = ""; std::string tmpfile = ""; std::string sAutopush = lowerCase (context.config.get ("merge.autopush")); bool bAutopush = context.config.getBoolean ("merge.autopush"); Uri uri (file, "merge"); uri.parse(); if (uri._data.length ()) { Directory location (context.config.get ("data.location")); // be sure that uri points to a file uri.append ("undo.data"); Transport* transport; if ((transport = Transport::getTransport (uri)) != NULL ) { tmpfile = location._data + "/undo_remote.data"; transport->recv (tmpfile); delete transport; file = tmpfile; } else file = uri._path; context.tdb2.merge (file); output += "Merge complete.\n"; if (tmpfile != "") remove (tmpfile.c_str ()); if ( ((sAutopush == "ask") && (confirm ("Would you like to push the merged changes to \'" + uri._data + "\'?")) ) || (bAutopush) ) { // TODO derive autopush uri from merge.default.uri? otherwise: change prompt above // context.task.set ("description", uri._data); std::string out; context.commands["push"]->execute (out); } } else throw std::string ("No uri was specified for the merge. Either specify " "the uri of a remote .task directory, or create a " "'merge.default.uri' entry in your .taskrc file."); return 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * game.cpp * * Created on: Mar 26, 2016 * Author: Tumblr */ #include <string> #include <iostream> #include <sstream> #include "game.h" #include "utils.h" using namespace std; /* * Default Game constructor */ Game::Game(string type) { players = type; if(players != "single" || players != "mutli") // Throw custruction error here cont = true; myTurn = false; } /* * Default Game Destructor */ Game::~Game() { // TODO } /* * Load needed game content here * This should always load before the game begins */ void Game::load_content(const Deck selected) { // loads in the selected deck for the player player.select_deck(selected); // sets the players starting mana and shuffles the deck player.set_mana(opponent.get_life()); player.get_deck()->shuffle(); // draws the players starting hand while(player.get_hand()->size() < START_HAND) player.draw_card(); // gets the images of the cards in the players hand for(Card* card : player.get_hand()->get_vector()) { display.add_image(card->get_image()); } // Game mode specific content loading if(players == "single") { /* * TODO loads AI's deck here * For now it will just be * a copy of the players deck. */ opponent.select_deck(selected); while(opponent.get_hand()->size() < START_HAND) opponent.draw_card(); opponent.set_mana(player.get_life()); opponent.get_deck()->shuffle(); } else if(players == "mutli") { // TODO loads opponenets deck here } else { /* TODO Something went wrong??? */ } update(); } /* * Unload game data here * this should be called at the end of the game * to prep us for deconstruction */ void Game::unload_content() { // TODO } void Game::update() { /* * TODO This is the running function of the game. * This will be where the player takes their turn. */ // Multiplayer should not play yet if(players == "multi") return; // prints the game to the console draw(); myTurn = true; // takes in the players input string in; cin >> in; size_t choice = 0; if(in == "exit") { unload_content(); return; } else istringstream(in) >> choice; // parses out the players input if(player.get_mana() > 0 && choice != 0) { player.cast(choice - 1); update(); } else { /* "Combat phase" */ // TODO /* "Draw phase" */ // if at starting hand only draw one card if(player.get_hand()->size() > START_HAND) player.draw_card(); // draw cards until you are back to starting limit while(player.get_hand()->size() < START_HAND) player.draw_card(); for(Card* card : player.get_hand()->get_vector()) { // TODO Only adds to the display console if it is not already if(!display.contains(card->get_image())) display.add_image(card->get_image()); } /* "End Turn" */ opponent.set_mana(player.get_life()); // start AI's turn if(players == "single") sp_update(); // start opponenets turn else if(players == "multi") mp_update(); } } /* * TODO Single player logic here * This will be where the AI takes their turn */ void Game::sp_update() { myTurn = false; draw(); // This is where the AI takes their turn if(opponent.get_mana() > 0 && opponent.get_hand()->size() > 0) { opponent.cast(/* TODO Opponent casts card here */ 0); sp_update(); } else { /* "Combat phase" */ // TODO /* "Draw phase" */ // if at starting hand only draw one card if(opponent.get_hand()->size() > START_HAND) opponent.draw_card(); // draw cards until you are back to starting limit while(opponent.get_hand()->size() < START_HAND) opponent.draw_card(); } /* "End Turn" */ player.set_mana(opponent.get_life()); // start the players turn update(); } /* * Multiplayer game works here * This will be where the opponent takes their turn */ void Game::mp_update() { myTurn = false; draw(); /* "Start Turn" */ // TODO /* "Combat phase" */ // TODO /* "Draw phase" */ // TODO /* "End Turn" */ player.set_mana(opponent.get_life()); // start the players turn update(); } /* * TODO Draw the board state and players hand here. * any animations should happen here, as this method * is called at the start of every update call. */ void Game::draw() { display.print(); } <commit_msg>Possible fix of getting stuck in game<commit_after>/* * game.cpp * * Created on: Mar 26, 2016 * Author: Tumblr */ #include <string> #include <iostream> #include <sstream> #include "game.h" #include "utils.h" using namespace std; /* * Default Game constructor */ Game::Game(string type) { players = type; if(players != "single" || players != "mutli") // Throw custruction error here cont = true; myTurn = false; } /* * Default Game Destructor */ Game::~Game() { // TODO } /* * Load needed game content here * This should always load before the game begins */ void Game::load_content(const Deck selected) { // loads in the selected deck for the player player.select_deck(selected); // sets the players starting mana and shuffles the deck player.set_mana(opponent.get_life()); player.get_deck()->shuffle(); // draws the players starting hand while(player.get_hand()->size() < START_HAND) player.draw_card(); // gets the images of the cards in the players hand for(Card* card : player.get_hand()->get_vector()) { display.add_image(card->get_image()); } // Game mode specific content loading if(players == "single") { /* * TODO loads AI's deck here * For now it will just be * a copy of the players deck. */ opponent.select_deck(selected); while(opponent.get_hand()->size() < START_HAND) opponent.draw_card(); opponent.set_mana(player.get_life()); opponent.get_deck()->shuffle(); } else if(players == "mutli") { // TODO loads opponenets deck here } else { /* TODO Something went wrong??? */ } update(); } /* * Unload game data here * this should be called at the end of the game * to prep us for deconstruction */ void Game::unload_content() { // TODO } void Game::update() { /* * TODO This is the running function of the game. * This will be where the player takes their turn. */ // Multiplayer should not play yet if(players == "multi") return; // prints the game to the console draw(); myTurn = true; // takes in the players input string in; cin >> in; size_t choice = 0; if(in == "exit") { unload_content(); return; } else istringstream(in) >> choice; // parses out the players input if(player.get_mana() > 0 && choice != 0) { player.cast(choice - 1); update(); return; } else { /* "Combat phase" */ // TODO /* "Draw phase" */ // if at starting hand only draw one card if(player.get_hand()->size() > START_HAND) player.draw_card(); // draw cards until you are back to starting limit while(player.get_hand()->size() < START_HAND) player.draw_card(); for(Card* card : player.get_hand()->get_vector()) { // TODO Only adds to the display console if it is not already if(!display.contains(card->get_image())) display.add_image(card->get_image()); } /* "End Turn" */ opponent.set_mana(player.get_life()); // start AI's turn if(players == "single") sp_update(); // start opponenets turn else if(players == "multi") mp_update(); } } /* * TODO Single player logic here * This will be where the AI takes their turn */ void Game::sp_update() { myTurn = false; draw(); // This is where the AI takes their turn if(opponent.get_mana() > 0 && opponent.get_hand()->size() > 0) { opponent.cast(/* TODO Opponent casts card here */ 0); sp_update(); } else { /* "Combat phase" */ // TODO /* "Draw phase" */ // if at starting hand only draw one card if(opponent.get_hand()->size() > START_HAND) opponent.draw_card(); // draw cards until you are back to starting limit while(opponent.get_hand()->size() < START_HAND) opponent.draw_card(); } /* "End Turn" */ player.set_mana(opponent.get_life()); // start the players turn update(); } /* * Multiplayer game works here * This will be where the opponent takes their turn */ void Game::mp_update() { myTurn = false; draw(); /* "Start Turn" */ // TODO /* "Combat phase" */ // TODO /* "Draw phase" */ // TODO /* "End Turn" */ player.set_mana(opponent.get_life()); // start the players turn update(); } /* * TODO Draw the board state and players hand here. * any animations should happen here, as this method * is called at the start of every update call. */ void Game::draw() { display.print(); } <|endoftext|>
<commit_before>/* * ProjAction.cpp * OpenLieroX * * Created by Albert Zeyer on 02.04.09. * code under LGPL * */ #include "ProjAction.h" #include "CGameScript.h" #include "CWorm.h" #include "CProjectile.h" #include "CClient.h" #include "ProjectileDesc.h" #include "Physics.h" #include "ConfigHandler.h" #include "EndianSwap.h" int Proj_SpawnParent::ownerWorm() const { switch(type) { case PSPT_NOTHING: return -1; case PSPT_SHOT: return shot->nWormID; case PSPT_PROJ: return proj->GetOwner(); } return -1; } int Proj_SpawnParent::fixedRandomIndex() const { switch(type) { case PSPT_NOTHING: return -1; case PSPT_SHOT: return shot->nRandom; case PSPT_PROJ: return proj->getRandomIndex() + 1; } return -1; } float Proj_SpawnParent::fixedRandomFloat() const { switch(type) { case PSPT_NOTHING: return -1; case PSPT_SHOT: return GetFixedRandomNum(shot->nRandom); case PSPT_PROJ: return proj->getRandomFloat(); } return -1; } CVec Proj_SpawnParent::position() const { switch(type) { case PSPT_NOTHING: return CVec(0,0); case PSPT_SHOT: { CVec dir; GetVecsFromAngle(shot->nAngle, &dir, NULL); CVec pos = shot->cPos + dir*8; return pos; } case PSPT_PROJ: return proj->GetPosition(); } return CVec(0,0); } CVec Proj_SpawnParent::velocity() const { switch(type) { case PSPT_NOTHING: return CVec(0,0); case PSPT_SHOT: return shot->cWormVel; case PSPT_PROJ: return proj->GetVelocity(); } return CVec(0,0); } float Proj_SpawnParent::angle() const { switch(type) { case PSPT_NOTHING: return 0; case PSPT_SHOT: return (float)shot->nAngle; case PSPT_PROJ: { CVec v = velocity(); NormalizeVector(&v); float heading = (float)( -atan2(v.x,v.y) * (180.0f/PI) ); heading+=90; FMOD(heading, 360.0f); return heading; } } return 0; } void Proj_SpawnInfo::apply(Proj_SpawnParent parent, AbsTime spawnTime) const { // Calculate the angle of the direction the projectile is heading float heading = 0; if(Useangle) heading = parent.angle(); for(int i=0; i < Amount; i++) { CVec sprd; if(UseParentVelocityForSpread) sprd = parent.velocity() * ParentVelSpreadFactor; else { int a = (int)( (float)Angle + heading + parent.fixedRandomFloat() * (float)Spread ); GetVecsFromAngle(a, &sprd, NULL); } int rot = 0; if(UseRandomRot) { // Calculate a random starting angle for the projectile rotation (if used) if(Proj->Rotating) { // Prevent div by zero if(Proj->RotIncrement == 0) Proj->RotIncrement = 1; rot = GetRandomInt( 360 / Proj->RotIncrement ) * Proj->RotIncrement; } } if(parent.type == Proj_SpawnParent::PSPT_SHOT) { parent.shot->nRandom++; parent.shot->nRandom %= 255; } CVec v = sprd * (float)Speed; CVec speedVarVec = sprd; if(UseSpecial11VecForSpeedVar) speedVarVec = CVec(1,1); v += speedVarVec * (float)SpeedVar * parent.fixedRandomFloat(); if(AddParentVel) v += parent.velocity(); if(parent.type == Proj_SpawnParent::PSPT_SHOT) { parent.shot->nRandom *= 5; parent.shot->nRandom %= 255; } AbsTime ignoreWormCollBeforeTime = spawnTime; if(parent.type == Proj_SpawnParent::PSPT_PROJ) ignoreWormCollBeforeTime = parent.proj->getIgnoreWormCollBeforeTime(); else // we set the ignoreWormCollBeforeTime to the current time to let the physics engine // first emulate the projectiles to the curtime and ignore earlier colls as the worm-pos // is probably outdated at this time ignoreWormCollBeforeTime = GetPhysicsTime() + 0.1f; // HINT: we add 100ms (it was dt before) because the projectile is spawned -> worms are simulated (pos change) -> projectiles are simulated int random = parent.fixedRandomIndex(); cClient->SpawnProjectile(parent.position(), v, rot, parent.ownerWorm(), Proj, random, spawnTime, ignoreWormCollBeforeTime); if(parent.type == Proj_SpawnParent::PSPT_SHOT) { parent.shot->nRandom++; parent.shot->nRandom %= 255; } } } std::string Proj_SpawnInfo::readFromIni(const std::string& file, const std::string& section) { ReadKeyword(file, section, "Useangle", &Useangle, Useangle); ReadInteger(file, section, "Angle", &Angle, Angle); ReadKeyword(file, section, "UseProjVelocity", &UseParentVelocityForSpread, UseParentVelocityForSpread); ReadInteger(file, section, "Amount", &Amount, Amount); ReadInteger(file, section, "Speed", &Speed, Speed); ReadFloat(file, section, "SpeedVar", &SpeedVar, SpeedVar); ReadFloat(file, section, "Spread", &Spread, Spread); std::string prjfile; ReadString(file, section, "Projectile", prjfile, ""); return prjfile; } bool Proj_SpawnInfo::read(CGameScript* gs, FILE* fp) { fread_endian<char>(fp, Useangle); fread_endian<int>(fp, Angle); fread_endian<int>(fp, Amount); fread_endian<int>(fp, Speed); fread_endian<float>(fp, SpeedVar); fread_endian<float>(fp, Spread); Proj = gs->LoadProjectile(fp); return Proj != NULL; } bool Proj_SpawnInfo::write(CGameScript* gs, FILE* fp) { fwrite_endian<char>(fp, Useangle); fwrite_endian<int>(fp, Angle); fwrite_endian<int>(fp, Amount); fwrite_endian<int>(fp, Speed); fwrite_endian<float>(fp, SpeedVar); fwrite_endian<float>(fp, Spread); return gs->SaveProjectile(Proj, fp); } <commit_msg>make AddParentVel configurable<commit_after>/* * ProjAction.cpp * OpenLieroX * * Created by Albert Zeyer on 02.04.09. * code under LGPL * */ #include "ProjAction.h" #include "CGameScript.h" #include "CWorm.h" #include "CProjectile.h" #include "CClient.h" #include "ProjectileDesc.h" #include "Physics.h" #include "ConfigHandler.h" #include "EndianSwap.h" int Proj_SpawnParent::ownerWorm() const { switch(type) { case PSPT_NOTHING: return -1; case PSPT_SHOT: return shot->nWormID; case PSPT_PROJ: return proj->GetOwner(); } return -1; } int Proj_SpawnParent::fixedRandomIndex() const { switch(type) { case PSPT_NOTHING: return -1; case PSPT_SHOT: return shot->nRandom; case PSPT_PROJ: return proj->getRandomIndex() + 1; } return -1; } float Proj_SpawnParent::fixedRandomFloat() const { switch(type) { case PSPT_NOTHING: return -1; case PSPT_SHOT: return GetFixedRandomNum(shot->nRandom); case PSPT_PROJ: return proj->getRandomFloat(); } return -1; } CVec Proj_SpawnParent::position() const { switch(type) { case PSPT_NOTHING: return CVec(0,0); case PSPT_SHOT: { CVec dir; GetVecsFromAngle(shot->nAngle, &dir, NULL); CVec pos = shot->cPos + dir*8; return pos; } case PSPT_PROJ: return proj->GetPosition(); } return CVec(0,0); } CVec Proj_SpawnParent::velocity() const { switch(type) { case PSPT_NOTHING: return CVec(0,0); case PSPT_SHOT: return shot->cWormVel; case PSPT_PROJ: return proj->GetVelocity(); } return CVec(0,0); } float Proj_SpawnParent::angle() const { switch(type) { case PSPT_NOTHING: return 0; case PSPT_SHOT: return (float)shot->nAngle; case PSPT_PROJ: { CVec v = velocity(); NormalizeVector(&v); float heading = (float)( -atan2(v.x,v.y) * (180.0f/PI) ); heading+=90; FMOD(heading, 360.0f); return heading; } } return 0; } void Proj_SpawnInfo::apply(Proj_SpawnParent parent, AbsTime spawnTime) const { // Calculate the angle of the direction the projectile is heading float heading = 0; if(Useangle) heading = parent.angle(); for(int i=0; i < Amount; i++) { CVec sprd; if(UseParentVelocityForSpread) sprd = parent.velocity() * ParentVelSpreadFactor; else { int a = (int)( (float)Angle + heading + parent.fixedRandomFloat() * (float)Spread ); GetVecsFromAngle(a, &sprd, NULL); } int rot = 0; if(UseRandomRot) { // Calculate a random starting angle for the projectile rotation (if used) if(Proj->Rotating) { // Prevent div by zero if(Proj->RotIncrement == 0) Proj->RotIncrement = 1; rot = GetRandomInt( 360 / Proj->RotIncrement ) * Proj->RotIncrement; } } if(parent.type == Proj_SpawnParent::PSPT_SHOT) { parent.shot->nRandom++; parent.shot->nRandom %= 255; } CVec v = sprd * (float)Speed; CVec speedVarVec = sprd; if(UseSpecial11VecForSpeedVar) speedVarVec = CVec(1,1); v += speedVarVec * (float)SpeedVar * parent.fixedRandomFloat(); if(AddParentVel) v += parent.velocity(); if(parent.type == Proj_SpawnParent::PSPT_SHOT) { parent.shot->nRandom *= 5; parent.shot->nRandom %= 255; } AbsTime ignoreWormCollBeforeTime = spawnTime; if(parent.type == Proj_SpawnParent::PSPT_PROJ) ignoreWormCollBeforeTime = parent.proj->getIgnoreWormCollBeforeTime(); else // we set the ignoreWormCollBeforeTime to the current time to let the physics engine // first emulate the projectiles to the curtime and ignore earlier colls as the worm-pos // is probably outdated at this time ignoreWormCollBeforeTime = GetPhysicsTime() + 0.1f; // HINT: we add 100ms (it was dt before) because the projectile is spawned -> worms are simulated (pos change) -> projectiles are simulated int random = parent.fixedRandomIndex(); cClient->SpawnProjectile(parent.position(), v, rot, parent.ownerWorm(), Proj, random, spawnTime, ignoreWormCollBeforeTime); if(parent.type == Proj_SpawnParent::PSPT_SHOT) { parent.shot->nRandom++; parent.shot->nRandom %= 255; } } } std::string Proj_SpawnInfo::readFromIni(const std::string& file, const std::string& section) { ReadKeyword(file, section, "AddParentVel", &AddParentVel, AddParentVel); // new in OLX beta9 ReadKeyword(file, section, "Useangle", &Useangle, Useangle); ReadInteger(file, section, "Angle", &Angle, Angle); ReadKeyword(file, section, "UseProjVelocity", &UseParentVelocityForSpread, UseParentVelocityForSpread); ReadInteger(file, section, "Amount", &Amount, Amount); ReadInteger(file, section, "Speed", &Speed, Speed); ReadFloat(file, section, "SpeedVar", &SpeedVar, SpeedVar); ReadFloat(file, section, "Spread", &Spread, Spread); std::string prjfile; ReadString(file, section, "Projectile", prjfile, ""); return prjfile; } bool Proj_SpawnInfo::read(CGameScript* gs, FILE* fp) { fread_endian<char>(fp, AddParentVel); fread_endian<char>(fp, Useangle); fread_endian<int>(fp, Angle); fread_endian<int>(fp, Amount); fread_endian<int>(fp, Speed); fread_endian<float>(fp, SpeedVar); fread_endian<float>(fp, Spread); Proj = gs->LoadProjectile(fp); return Proj != NULL; } bool Proj_SpawnInfo::write(CGameScript* gs, FILE* fp) { fwrite_endian<char>(fp, AddParentVel); fwrite_endian<char>(fp, Useangle); fwrite_endian<int>(fp, Angle); fwrite_endian<int>(fp, Amount); fwrite_endian<int>(fp, Speed); fwrite_endian<float>(fp, SpeedVar); fwrite_endian<float>(fp, Spread); return gs->SaveProjectile(Proj, fp); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: accselectionhelper.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-04-24 16:13:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ACCSELECTIONHELPER_HXX_ #define _ACCSELECTIONHELPER_HXX_ class SwAccessibleContext; class SwRootFrm; class SwFEShell; class SwFlyFrm; #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_ #include <com/sun/star/accessibility/XAccessibleSelection.hpp> #endif class SwAccessibleSelectionHelper { /// the context on which this helper works SwAccessibleContext& rContext; /// get FE-Shell SwFEShell* GetFEShell(); void throwIndexOutOfBoundsException() throw ( ::com::sun::star::lang::IndexOutOfBoundsException ); public: SwAccessibleSelectionHelper( SwAccessibleContext& rContext ); ~SwAccessibleSelectionHelper(); //===== XAccessibleSelection ============================================ void selectAccessibleChild( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); sal_Bool isAccessibleChildSelected( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); void clearAccessibleSelection( ) throw ( ::com::sun::star::uno::RuntimeException ); void selectAllAccessible( ) throw ( ::com::sun::star::uno::RuntimeException ); sal_Int32 getSelectedAccessibleChildCount( ) throw ( ::com::sun::star::uno::RuntimeException ); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); void deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); }; #endif <commit_msg>INTEGRATION: CWS uaa03 (1.4.30); FILE MERGED 2003/05/21 15:48:57 mt 1.4.30.1: #i14623# UAA finalization<commit_after>/************************************************************************* * * $RCSfile: accselectionhelper.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2003-05-22 12:51:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ACCSELECTIONHELPER_HXX_ #define _ACCSELECTIONHELPER_HXX_ class SwAccessibleContext; class SwRootFrm; class SwFEShell; class SwFlyFrm; #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_ #include <com/sun/star/accessibility/XAccessibleSelection.hpp> #endif class SwAccessibleSelectionHelper { /// the context on which this helper works SwAccessibleContext& rContext; /// get FE-Shell SwFEShell* GetFEShell(); void throwIndexOutOfBoundsException() throw ( ::com::sun::star::lang::IndexOutOfBoundsException ); public: SwAccessibleSelectionHelper( SwAccessibleContext& rContext ); ~SwAccessibleSelectionHelper(); //===== XAccessibleSelection ============================================ void selectAccessibleChild( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); sal_Bool isAccessibleChildSelected( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); void clearAccessibleSelection( ) throw ( ::com::sun::star::uno::RuntimeException ); void selectAllAccessibleChildren( ) throw ( ::com::sun::star::uno::RuntimeException ); sal_Int32 getSelectedAccessibleChildCount( ) throw ( ::com::sun::star::uno::RuntimeException ); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); void deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); }; #endif <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2010-2011 Dreamhost * * This 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. See file COPYING. * */ #include "auth/AuthSupported.h" #include "auth/KeyRing.h" #include "common/ceph_argparse.h" #include "common/code_environment.h" #include "common/DoutStreambuf.h" #include "common/safe_io.h" #include "common/signal.h" #include "common/version.h" #include "common/config.h" #include "common/common_init.h" #include "common/errno.h" #include "common/ceph_crypto.h" #include "include/color.h" #include <errno.h> #include <deque> #include <syslog.h> #define _STR(x) #x #define STRINGIFY(x) _STR(x) int keyring_init(md_config_t *conf) { if (!is_supported_auth(CEPH_AUTH_CEPHX)) return 0; int ret = 0; string filename; if (ceph_resolve_file_search(conf->keyring, filename)) { ret = g_keyring.load(filename); } if (!conf->key.empty()) { EntityAuth ea; ea.key.decode_base64(conf->key); g_keyring.add(conf->name, ea); ret = 0; } else if (!conf->keyfile.empty()) { char buf[100]; int fd = ::open(conf->keyfile.c_str(), O_RDONLY); if (fd < 0) { int err = errno; derr << "unable to open " << conf->keyfile << ": " << cpp_strerror(err) << dendl; ceph_abort(); } memset(buf, 0, sizeof(buf)); int len = safe_read(fd, buf, sizeof(buf) - 1); if (len < 0) { derr << "unable to read key from " << conf->keyfile << ": " << cpp_strerror(len) << dendl; TEMP_FAILURE_RETRY(::close(fd)); ceph_abort(); } TEMP_FAILURE_RETRY(::close(fd)); buf[len] = 0; string k = buf; EntityAuth ea; ea.key.decode_base64(k); g_keyring.add(conf->name, ea); ret = 0; } if (ret) derr << "keyring_init: failed to load " << filename << dendl; return ret; } md_config_t *common_preinit(const CephInitParameters &iparams, enum code_environment_t code_env, int flags) { // set code environment g_code_env = code_env; // Create a configuration object // TODO: de-globalize md_config_t *conf = &g_conf; //new md_config_t(); // add config observers here // Set up our entity name. conf->name = iparams.name; // Set some defaults based on code type switch (code_env) { case CODE_ENVIRONMENT_DAEMON: conf->daemonize = true; if (!(flags & CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS)) { conf->set_val_or_die("log_dir", "/var/log/ceph"); conf->set_val_or_die("pid_file", "/var/run/ceph/$type.$id.pid"); } conf->set_val_or_die("log_to_stderr", STRINGIFY(LOG_TO_STDERR_SOME)); break; default: conf->set_val_or_die("daemonize", "false"); break; } return conf; } void complain_about_parse_errors(std::deque<std::string> *parse_errors) { if (parse_errors->empty()) return; derr << "Errors while parsing config file!" << dendl; int cur_err = 0; static const int MAX_PARSE_ERRORS = 20; for (std::deque<std::string>::const_iterator p = parse_errors->begin(); p != parse_errors->end(); ++p) { derr << *p << dendl; if (cur_err == MAX_PARSE_ERRORS) { derr << "Suppressed " << (parse_errors->size() - MAX_PARSE_ERRORS) << " more errors." << dendl; break; } ++cur_err; } } void common_init(std::vector < const char* >& args, uint32_t module_type, code_environment_t code_env, int flags) { CephInitParameters iparams = ceph_argparse_early_args(args, module_type, flags); md_config_t *conf = common_preinit(iparams, code_env, flags); std::deque<std::string> parse_errors; int ret = conf->parse_config_files(iparams.get_conf_files(), &parse_errors); if (ret == -EDOM) { dout_emergency("common_init: error parsing config file.\n"); _exit(1); } else if (ret == -EINVAL) { if (!(flags & CINIT_FLAG_NO_DEFAULT_CONFIG_FILE)) { dout_emergency("common_init: unable to open config file.\n"); _exit(1); } } else if (ret) { dout_emergency("common_init: error reading config file.\n"); _exit(1); } conf->parse_env(); // environment variables override conf->parse_argv(args); // argv override // Expand metavariables. Invoke configuration observers. conf->apply_changes(); // Now we're ready to complain about config file parse errors complain_about_parse_errors(&parse_errors); // signal stuff int siglist[] = { SIGPIPE, 0 }; block_signals(NULL, siglist); install_standard_sighandlers(); if (code_env == CODE_ENVIRONMENT_DAEMON) { cout << TEXT_YELLOW << " ** WARNING: Ceph is still under heavy development, " << "and is only suitable for **" << TEXT_NORMAL << std::endl; cout << TEXT_YELLOW << " ** testing and review. Do not trust it " << "with important data. **" << TEXT_NORMAL << std::endl; output_ceph_version(); } ceph::crypto::init(); } <commit_msg>common_init: set log_file, not log_dir, by default<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2010-2011 Dreamhost * * This 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. See file COPYING. * */ #include "auth/AuthSupported.h" #include "auth/KeyRing.h" #include "common/ceph_argparse.h" #include "common/code_environment.h" #include "common/DoutStreambuf.h" #include "common/safe_io.h" #include "common/signal.h" #include "common/version.h" #include "common/config.h" #include "common/common_init.h" #include "common/errno.h" #include "common/ceph_crypto.h" #include "include/color.h" #include <errno.h> #include <deque> #include <syslog.h> #define _STR(x) #x #define STRINGIFY(x) _STR(x) int keyring_init(md_config_t *conf) { if (!is_supported_auth(CEPH_AUTH_CEPHX)) return 0; int ret = 0; string filename; if (ceph_resolve_file_search(conf->keyring, filename)) { ret = g_keyring.load(filename); } if (!conf->key.empty()) { EntityAuth ea; ea.key.decode_base64(conf->key); g_keyring.add(conf->name, ea); ret = 0; } else if (!conf->keyfile.empty()) { char buf[100]; int fd = ::open(conf->keyfile.c_str(), O_RDONLY); if (fd < 0) { int err = errno; derr << "unable to open " << conf->keyfile << ": " << cpp_strerror(err) << dendl; ceph_abort(); } memset(buf, 0, sizeof(buf)); int len = safe_read(fd, buf, sizeof(buf) - 1); if (len < 0) { derr << "unable to read key from " << conf->keyfile << ": " << cpp_strerror(len) << dendl; TEMP_FAILURE_RETRY(::close(fd)); ceph_abort(); } TEMP_FAILURE_RETRY(::close(fd)); buf[len] = 0; string k = buf; EntityAuth ea; ea.key.decode_base64(k); g_keyring.add(conf->name, ea); ret = 0; } if (ret) derr << "keyring_init: failed to load " << filename << dendl; return ret; } md_config_t *common_preinit(const CephInitParameters &iparams, enum code_environment_t code_env, int flags) { // set code environment g_code_env = code_env; // Create a configuration object // TODO: de-globalize md_config_t *conf = &g_conf; //new md_config_t(); // add config observers here // Set up our entity name. conf->name = iparams.name; // Set some defaults based on code type switch (code_env) { case CODE_ENVIRONMENT_DAEMON: conf->daemonize = true; if (!(flags & CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS)) { conf->set_val_or_die("pid_file", "/var/run/ceph/$type.$id.pid"); } conf->set_val_or_die("log_to_stderr", STRINGIFY(LOG_TO_STDERR_SOME)); break; default: conf->set_val_or_die("daemonize", "false"); break; } return conf; } void complain_about_parse_errors(std::deque<std::string> *parse_errors) { if (parse_errors->empty()) return; derr << "Errors while parsing config file!" << dendl; int cur_err = 0; static const int MAX_PARSE_ERRORS = 20; for (std::deque<std::string>::const_iterator p = parse_errors->begin(); p != parse_errors->end(); ++p) { derr << *p << dendl; if (cur_err == MAX_PARSE_ERRORS) { derr << "Suppressed " << (parse_errors->size() - MAX_PARSE_ERRORS) << " more errors." << dendl; break; } ++cur_err; } } void common_init(std::vector < const char* >& args, uint32_t module_type, code_environment_t code_env, int flags) { CephInitParameters iparams = ceph_argparse_early_args(args, module_type, flags); md_config_t *conf = common_preinit(iparams, code_env, flags); std::deque<std::string> parse_errors; int ret = conf->parse_config_files(iparams.get_conf_files(), &parse_errors); if (ret == -EDOM) { dout_emergency("common_init: error parsing config file.\n"); _exit(1); } else if (ret == -EINVAL) { if (!(flags & CINIT_FLAG_NO_DEFAULT_CONFIG_FILE)) { dout_emergency("common_init: unable to open config file.\n"); _exit(1); } } else if (ret) { dout_emergency("common_init: error reading config file.\n"); _exit(1); } conf->parse_env(); // environment variables override conf->parse_argv(args); // argv override if (code_env == CODE_ENVIRONMENT_DAEMON) { if (conf->log_dir.empty() && conf->log_file.empty()) { conf->set_val_or_die("log_file", "/var/log/ceph/$name.log"); } } // Expand metavariables. Invoke configuration observers. conf->apply_changes(); // Now we're ready to complain about config file parse errors complain_about_parse_errors(&parse_errors); // signal stuff int siglist[] = { SIGPIPE, 0 }; block_signals(NULL, siglist); install_standard_sighandlers(); if (code_env == CODE_ENVIRONMENT_DAEMON) { cout << TEXT_YELLOW << " ** WARNING: Ceph is still under heavy development, " << "and is only suitable for **" << TEXT_NORMAL << std::endl; cout << TEXT_YELLOW << " ** testing and review. Do not trust it " << "with important data. **" << TEXT_NORMAL << std::endl; output_ceph_version(); } ceph::crypto::init(); } <|endoftext|>
<commit_before> // Copyright (c) 2012, 2013 Pierre MOULON. // 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/. #ifndef OPENMVG_FEATURES_DESCRIPTOR_HPP #define OPENMVG_FEATURES_DESCRIPTOR_HPP #include "openMVG/numeric/numeric.h" #include <iostream> #include <iterator> #include <fstream> #include <string> #include <vector> namespace openMVG { namespace features { /** * Class that handle descriptor (a data container of N values of type T). * SiftDescriptor => <uchar,128> or <float,128> * Surf 64 => <float,64> */ template <typename T, std::size_t N> class Descriptor { public: typedef Descriptor<T, N> This; typedef T value_type; typedef T bin_type; typedef std::size_t size_type; /// Compile-time length of the descriptor static const size_type static_size = N; /// Constructor inline Descriptor() {} inline Descriptor(T defaultValue) { for(size_type i = 0; i < N; ++i) data[i] = defaultValue; } /// capacity inline size_type size() const { return N; } /// Mutable and non-mutable bin getters inline bin_type& operator[](std::size_t i) { return data[i]; } inline bin_type operator[](std::size_t i) const { return data[i]; } // Atomic addition between two descriptors inline This& operator+=(const This other) { for(size_type i = 0; i < size(); ++i) data[i] += other[i]; return *this; } // Division between two descriptors inline This operator/(const This other) const { This res; for(size_type i = 0; i < size(); ++i) res[i] = data[i] / other[i]; return res; } inline bin_type* getData() const {return (bin_type* ) (&data[0]);} /// Ostream interface std::ostream& print(std::ostream& os) const; /// Istream interface std::istream& read(std::istream& in); template<class Archive> void save(Archive & archive) const { std::vector<T> array(data,data+N); archive( array ); } template<class Archive> void load(Archive & archive) { std::vector<T> array(N); archive( array ); std::memcpy(data, array.data(), sizeof(T)*N); } private: bin_type data[N]; }; // Output stream definition template <typename T, std::size_t N> inline std::ostream& operator<<(std::ostream& out, const Descriptor<T, N>& obj) { return obj.print(out); //simply call the print method. } // Input stream definition template <typename T, std::size_t N> inline std::istream& operator>>(std::istream& in, Descriptor<T, N>& obj) { return obj.read(in); //simply call the read method. } //-- Use specialization to handle unsigned char case. //-- We do not want confuse unsigned char value with the spaces written in the file template<typename T> inline std::ostream& printT(std::ostream& os, T *tab, size_t N) { std::copy( tab, &tab[N], std::ostream_iterator<T>(os," ")); return os; } template<> inline std::ostream& printT<unsigned char>(std::ostream& os, unsigned char *tab, size_t N) { for(size_t i=0; i < N; ++i) os << (int)tab[i] << " "; return os; } template<typename T> inline std::istream& readT(std::istream& is, T *tab, size_t N) { for(size_t i=0; i<N; ++i) is >> tab[i]; return is; } template<> inline std::istream& readT<unsigned char>(std::istream& is, unsigned char *tab, size_t N) { int temp = -1; for(size_t i=0; i < N; ++i){ is >> temp; tab[i] = (unsigned char)temp; } return is; } template<typename T, std::size_t N> std::ostream& Descriptor<T,N>::print(std::ostream& os) const { return printT<T>(os, (T*) &data[0], N); } template<typename T, std::size_t N> std::istream& Descriptor<T,N>::read(std::istream& in) { return readT<T>(in, (T*) &data[0], N); } /// Read descriptors from file template<typename DescriptorsT > static bool loadDescsFromFile( const std::string & sfileNameDescs, DescriptorsT & vec_desc) { vec_desc.clear(); std::ifstream fileIn(sfileNameDescs.c_str()); std::copy( std::istream_iterator<typename DescriptorsT::value_type >(fileIn), std::istream_iterator<typename DescriptorsT::value_type >(), std::back_inserter(vec_desc)); bool bOk = !fileIn.bad(); fileIn.close(); return bOk; } /// Write descriptors to file template<typename DescriptorsT > static bool saveDescsToFile( const std::string & sfileNameDescs, DescriptorsT & vec_desc) { std::ofstream file(sfileNameDescs.c_str()); std::copy(vec_desc.begin(), vec_desc.end(), std::ostream_iterator<typename DescriptorsT::value_type >(file,"\n")); bool bOk = file.good(); file.close(); return bOk; } /// Read descriptors from file (in binary mode) template<typename DescriptorsT > static bool loadDescsFromBinFile( const std::string & sfileNameDescs, DescriptorsT & vec_desc) { typedef typename DescriptorsT::value_type VALUE; vec_desc.clear(); std::ifstream fileIn(sfileNameDescs.c_str(), std::ios::in | std::ios::binary); //Read the number of descriptor in the file std::size_t cardDesc = 0; fileIn.read((char*) &cardDesc, sizeof(std::size_t)); vec_desc.resize(cardDesc); for (typename DescriptorsT::const_iterator iter = vec_desc.begin(); iter != vec_desc.end(); ++iter) { fileIn.read((char*) (*iter).getData(), VALUE::static_size*sizeof(typename VALUE::bin_type)); } bool bOk = !fileIn.bad(); fileIn.close(); return bOk; } /// Write descriptors to file (in binary mode) template<typename DescriptorsT > static bool saveDescsToBinFile( const std::string & sfileNameDescs, DescriptorsT & vec_desc) { typedef typename DescriptorsT::value_type VALUE; std::ofstream file(sfileNameDescs.c_str(), std::ios::out | std::ios::binary); //Write the number of descriptor const std::size_t cardDesc = vec_desc.size(); file.write((const char*) &cardDesc, sizeof(std::size_t)); for (typename DescriptorsT::const_iterator iter = vec_desc.begin(); iter != vec_desc.end(); ++iter) { file.write((const char*) (*iter).getData(), VALUE::static_size*sizeof(typename VALUE::bin_type)); } bool bOk = file.good(); file.close(); return bOk; } } // namespace features } // namespace openMVG #endif // OPENMVG_FEATURES_DESCRIPTOR_HPP <commit_msg>[features] possibility to append descriptors during loading<commit_after> // Copyright (c) 2012, 2013 Pierre MOULON. // 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/. #ifndef OPENMVG_FEATURES_DESCRIPTOR_HPP #define OPENMVG_FEATURES_DESCRIPTOR_HPP #include "openMVG/numeric/numeric.h" #include <iostream> #include <iterator> #include <fstream> #include <string> #include <vector> namespace openMVG { namespace features { /** * Class that handle descriptor (a data container of N values of type T). * SiftDescriptor => <uchar,128> or <float,128> * Surf 64 => <float,64> */ template <typename T, std::size_t N> class Descriptor { public: typedef Descriptor<T, N> This; typedef T value_type; typedef T bin_type; typedef std::size_t size_type; /// Compile-time length of the descriptor static const size_type static_size = N; /// Constructor inline Descriptor() {} inline Descriptor(T defaultValue) { for(size_type i = 0; i < N; ++i) data[i] = defaultValue; } /// capacity inline size_type size() const { return N; } /// Mutable and non-mutable bin getters inline bin_type& operator[](std::size_t i) { return data[i]; } inline bin_type operator[](std::size_t i) const { return data[i]; } // Atomic addition between two descriptors inline This& operator+=(const This other) { for(size_type i = 0; i < size(); ++i) data[i] += other[i]; return *this; } // Division between two descriptors inline This operator/(const This other) const { This res; for(size_type i = 0; i < size(); ++i) res[i] = data[i] / other[i]; return res; } inline bin_type* getData() const {return (bin_type* ) (&data[0]);} /// Ostream interface std::ostream& print(std::ostream& os) const; /// Istream interface std::istream& read(std::istream& in); template<class Archive> void save(Archive & archive) const { std::vector<T> array(data,data+N); archive( array ); } template<class Archive> void load(Archive & archive) { std::vector<T> array(N); archive( array ); std::memcpy(data, array.data(), sizeof(T)*N); } private: bin_type data[N]; }; // Output stream definition template <typename T, std::size_t N> inline std::ostream& operator<<(std::ostream& out, const Descriptor<T, N>& obj) { return obj.print(out); //simply call the print method. } // Input stream definition template <typename T, std::size_t N> inline std::istream& operator>>(std::istream& in, Descriptor<T, N>& obj) { return obj.read(in); //simply call the read method. } //-- Use specialization to handle unsigned char case. //-- We do not want confuse unsigned char value with the spaces written in the file template<typename T> inline std::ostream& printT(std::ostream& os, T *tab, size_t N) { std::copy( tab, &tab[N], std::ostream_iterator<T>(os," ")); return os; } template<> inline std::ostream& printT<unsigned char>(std::ostream& os, unsigned char *tab, size_t N) { for(size_t i=0; i < N; ++i) os << (int)tab[i] << " "; return os; } template<typename T> inline std::istream& readT(std::istream& is, T *tab, size_t N) { for(size_t i=0; i<N; ++i) is >> tab[i]; return is; } template<> inline std::istream& readT<unsigned char>(std::istream& is, unsigned char *tab, size_t N) { int temp = -1; for(size_t i=0; i < N; ++i){ is >> temp; tab[i] = (unsigned char)temp; } return is; } template<typename T, std::size_t N> std::ostream& Descriptor<T,N>::print(std::ostream& os) const { return printT<T>(os, (T*) &data[0], N); } template<typename T, std::size_t N> std::istream& Descriptor<T,N>::read(std::istream& in) { return readT<T>(in, (T*) &data[0], N); } /// Read descriptors from file template<typename DescriptorsT > static bool loadDescsFromFile( const std::string & sfileNameDescs, DescriptorsT & vec_desc) { vec_desc.clear(); std::ifstream fileIn(sfileNameDescs.c_str()); std::copy( std::istream_iterator<typename DescriptorsT::value_type >(fileIn), std::istream_iterator<typename DescriptorsT::value_type >(), std::back_inserter(vec_desc)); bool bOk = !fileIn.bad(); fileIn.close(); return bOk; } /// Write descriptors to file template<typename DescriptorsT > static bool saveDescsToFile( const std::string & sfileNameDescs, DescriptorsT & vec_desc) { std::ofstream file(sfileNameDescs.c_str()); std::copy(vec_desc.begin(), vec_desc.end(), std::ostream_iterator<typename DescriptorsT::value_type >(file,"\n")); bool bOk = file.good(); file.close(); return bOk; } /// Read descriptors from file (in binary mode) template<typename DescriptorsT > static bool loadDescsFromBinFile( const std::string & sfileNameDescs, DescriptorsT & vec_desc, bool append = false) { typedef typename DescriptorsT::value_type VALUE; if( !append ) // for compatibility vec_desc.clear(); std::ifstream fileIn(sfileNameDescs.c_str(), std::ios::in | std::ios::binary); //Read the number of descriptor in the file std::size_t cardDesc = 0; fileIn.read((char*) &cardDesc, sizeof(std::size_t)); // Reserve is necessary to avoid iterator problems in case of cleared vector vec_desc.reserve(vec_desc.size() + cardDesc); typename DescriptorsT::const_iterator begin = vec_desc.end(); vec_desc.resize(vec_desc.size() + cardDesc); for (typename DescriptorsT::const_iterator iter = begin; iter != vec_desc.end(); ++iter) { fileIn.read((char*) (*iter).getData(), VALUE::static_size*sizeof(typename VALUE::bin_type)); } bool bOk = !fileIn.bad(); fileIn.close(); return bOk; } /// Write descriptors to file (in binary mode) template<typename DescriptorsT > static bool saveDescsToBinFile( const std::string & sfileNameDescs, DescriptorsT & vec_desc) { typedef typename DescriptorsT::value_type VALUE; std::ofstream file(sfileNameDescs.c_str(), std::ios::out | std::ios::binary); //Write the number of descriptor const std::size_t cardDesc = vec_desc.size(); file.write((const char*) &cardDesc, sizeof(std::size_t)); for (typename DescriptorsT::const_iterator iter = vec_desc.begin(); iter != vec_desc.end(); ++iter) { file.write((const char*) (*iter).getData(), VALUE::static_size*sizeof(typename VALUE::bin_type)); } bool bOk = file.good(); file.close(); return bOk; } } // namespace features } // namespace openMVG #endif // OPENMVG_FEATURES_DESCRIPTOR_HPP <|endoftext|>
<commit_before>#include "iges.h" bool siren_iges_install(mrb_state* mrb, struct RClass* rclass) { rclass = mrb_define_module(mrb, "IGES"); mrb_define_class_method(mrb, rclass, "save", siren_iges_save, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, rclass, "load", siren_iges_load, MRB_ARGS_REQ(1)); return true; } mrb_value siren_iges_save(mrb_state* mrb, mrb_value self) { mrb_value shapes; mrb_value path; int argc = mrb_get_args(mrb, "AS", &shapes, &path); IGESControl_Controller::Init(); IGESControl_Writer writer(Interface_Static::CVal("XSTEP.iges.unit"), Interface_Static::IVal("XSTEP.iges.writebrep.mode")); for (int i=0; i < mrb_ary_len(mrb, shapes); i++) { mrb_value target = mrb_ary_ref(mrb, shapes, i); TopoDS_Shape* shape = siren_shape_get(mrb, target); writer.AddShape(*shape); } writer.ComputeModel(); if (writer.Write((Standard_CString)RSTRING_PTR(path)) == Standard_False) { mrb_raisef(mrb, E_ARGUMENT_ERROR, "Failed to save IGES to %S.", path); } return mrb_nil_value(); } mrb_value siren_iges_load(mrb_state* mrb, mrb_value self) { mrb_value path; mrb_bool oneshape; int argc = mrb_get_args(mrb, "S|b", &path, &oneshape); if (argc == 1) oneshape = 0; IGESControl_Reader iges_reader; int stat = iges_reader.ReadFile((Standard_CString)RSTRING_PTR(path)); mrb_value result; if (stat == IFSelect_RetDone) { try { iges_reader.TransferRoots(); } catch (...) { mrb_raise(mrb, E_RUNTIME_ERROR, "Failed to TransferRoots() with an IGES."); } if (oneshape) { // As one shape result = siren_shape_new(mrb, iges_reader.OneShape()); } else { // Some shapes result = mrb_ary_new(mrb); for (int i=1; i <= iges_reader.NbShapes(); i++) { try { mrb_value mrshape = siren_shape_new(mrb, iges_reader.Shape(i)); mrb_ary_push(mrb, result, mrshape); } catch(...) { // Add nil value at raise exception. mrb_ary_push(mrb, result, mrb_nil_value()); } } if (mrb_ary_len(mrb, result) < 1) result = mrb_nil_value(); } } else { mrb_raisef(mrb, E_ARGUMENT_ERROR, "Failed to load IGES from %S.", path); } return result; } <commit_msg>Fix use to multibyte path in IGES::load.<commit_after>#include "iges.h" bool siren_iges_install(mrb_state* mrb, struct RClass* rclass) { rclass = mrb_define_module(mrb, "IGES"); mrb_define_class_method(mrb, rclass, "save", siren_iges_save, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, rclass, "load", siren_iges_load, MRB_ARGS_REQ(1)); return true; } mrb_value siren_iges_save(mrb_state* mrb, mrb_value self) { mrb_value shapes; mrb_value path; int argc = mrb_get_args(mrb, "AS", &shapes, &path); IGESControl_Controller::Init(); IGESControl_Writer writer(Interface_Static::CVal("XSTEP.iges.unit"), Interface_Static::IVal("XSTEP.iges.writebrep.mode")); for (int i=0; i < mrb_ary_len(mrb, shapes); i++) { mrb_value target = mrb_ary_ref(mrb, shapes, i); TopoDS_Shape* shape = siren_shape_get(mrb, target); writer.AddShape(*shape); } writer.ComputeModel(); std::ofstream fst(RSTRING_PTR(path), std::ios_base::out); if (writer.Write(fst) == Standard_False) { mrb_raisef(mrb, E_ARGUMENT_ERROR, "Failed to save IGES to %S.", path); } return mrb_nil_value(); } mrb_value siren_iges_load(mrb_state* mrb, mrb_value self) { mrb_value path; mrb_bool oneshape; int argc = mrb_get_args(mrb, "S|b", &path, &oneshape); if (argc == 1) oneshape = 0; IGESControl_Reader iges_reader; int stat = iges_reader.ReadFile((Standard_CString)RSTRING_PTR(path)); mrb_value result; if (stat == IFSelect_RetDone) { try { iges_reader.TransferRoots(); } catch (...) { mrb_raise(mrb, E_RUNTIME_ERROR, "Failed to TransferRoots() with an IGES."); } if (oneshape) { // As one shape result = siren_shape_new(mrb, iges_reader.OneShape()); } else { // Some shapes result = mrb_ary_new(mrb); for (int i=1; i <= iges_reader.NbShapes(); i++) { try { mrb_value mrshape = siren_shape_new(mrb, iges_reader.Shape(i)); mrb_ary_push(mrb, result, mrshape); } catch(...) { // Add nil value at raise exception. mrb_ary_push(mrb, result, mrb_nil_value()); } } if (mrb_ary_len(mrb, result) < 1) result = mrb_nil_value(); } } else { mrb_raisef(mrb, E_ARGUMENT_ERROR, "Failed to load IGES from %S.", path); } return result; } <|endoftext|>
<commit_before>/******************************************************************************* * Reverse Polish Notation calculator. * * Copyright (c) 2007-2008, Samuel Fredrickson <kinghajj@gmail.com> * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 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. * ******************************************************************************/ /******************************************************************************* * Argument.cpp - argument handling for the console port. * ******************************************************************************/ #include "../rpn.h" using namespace RPN; using namespace std; static void argumentEvaluate(vector<string>& args) { Calculator calculator; calculator.Eval(args[0]); calculator.Display(); cout << endl; } static void argumentVersion(vector<string>& args) { Print("RPN "); Print(VERSION_MAJOR); Print('.'); Print(VERSION_MINOR); Print('.'); Print(VERSION_REVIS); Print('.'); Print(VERSION_BUILD); Print(' '); Print(VERSION_EXTRA); Print('\n'); } //! Converts command-line arguments into a vector of strings. vector<string> RPN::vectorize(char **argv, int argc) { vector<string> ret; for(int i = 0; i < argc; ++i) ret.push_back(argv[i]); return ret; } bool RPN::processArguments(const vector<string>& args, const Arguments& arguments) { bool continueProgram = true; bool performed = false; // iterate through the arguments for(vector<string>::const_iterator it = args.begin(); it != args.end() && continueProgram; it++) { Arguments::const_iterator found = arguments.find(*it); // if an argument was found in the map, if(found != arguments.end()) { // if the argument requires arguments and there are enough, if(found->second.NumArgs() && it + found->second.NumArgs() != args.end()) { // create a sub-vector of the arguments, vector<string> argument_args( it + 1, it + found->second.NumArgs() + 1); // and perform the argument. found->second.Perform(argument_args); performed = true; // then skip the argument's arguments. it += found->second.NumArgs(); } // if the argument requires no arguments, else if(found->second.NumArgs() == 0) { // perform it with an empty arguments vector. vector<string> argument_args; found->second.Perform(argument_args); performed = true; } // ask the argument whether to continue the program. if(performed) continueProgram = found->second.ContinueProgram(); } // the next argument is not yet performed. performed = false; } return continueProgram; } void RPN::setupArguments(Arguments& arguments) { arguments["-e"] = Argument(1, false, argumentEvaluate); arguments["-v"] = Argument(0, false, argumentVersion); arguments["--version"] = Argument(0, false, argumentVersion); } <commit_msg>Removed use of "cout".<commit_after>/******************************************************************************* * Reverse Polish Notation calculator. * * Copyright (c) 2007-2008, Samuel Fredrickson <kinghajj@gmail.com> * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 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. * ******************************************************************************/ /******************************************************************************* * Argument.cpp - argument handling for the console port. * ******************************************************************************/ #include "../rpn.h" using namespace RPN; using namespace std; static void argumentEvaluate(vector<string>& args) { Calculator calculator; calculator.Eval(args[0]); calculator.Display(); Print('\n'); } static void argumentVersion(vector<string>& args) { Print("RPN "); Print(VERSION_MAJOR); Print('.'); Print(VERSION_MINOR); Print('.'); Print(VERSION_REVIS); Print('.'); Print(VERSION_BUILD); Print(' '); Print(VERSION_EXTRA); Print('\n'); } //! Converts command-line arguments into a vector of strings. vector<string> RPN::vectorize(char **argv, int argc) { vector<string> ret; for(int i = 0; i < argc; ++i) ret.push_back(argv[i]); return ret; } bool RPN::processArguments(const vector<string>& args, const Arguments& arguments) { bool continueProgram = true; bool performed = false; // iterate through the arguments for(vector<string>::const_iterator it = args.begin(); it != args.end() && continueProgram; it++) { Arguments::const_iterator found = arguments.find(*it); // if an argument was found in the map, if(found != arguments.end()) { // if the argument requires arguments and there are enough, if(found->second.NumArgs() && it + found->second.NumArgs() != args.end()) { // create a sub-vector of the arguments, vector<string> argument_args( it + 1, it + found->second.NumArgs() + 1); // and perform the argument. found->second.Perform(argument_args); performed = true; // then skip the argument's arguments. it += found->second.NumArgs(); } // if the argument requires no arguments, else if(found->second.NumArgs() == 0) { // perform it with an empty arguments vector. vector<string> argument_args; found->second.Perform(argument_args); performed = true; } // ask the argument whether to continue the program. if(performed) continueProgram = found->second.ContinueProgram(); } // the next argument is not yet performed. performed = false; } return continueProgram; } void RPN::setupArguments(Arguments& arguments) { arguments["-e"] = Argument(1, false, argumentEvaluate); arguments["-v"] = Argument(0, false, argumentVersion); arguments["--version"] = Argument(0, false, argumentVersion); } <|endoftext|>
<commit_before>#include "FemusInit.hpp" #include "MultiLevelProblem.hpp" #include "VTKWriter.hpp" #include "TransientSystem.hpp" #include "NonLinearImplicitSystem.hpp" #include "NumericVector.hpp" #include "adept.h" #include "petsc.h" #include "petscmat.h" #include "PetscMatrix.hpp" #include "slepceps.h" #include "sparseGrid.hpp" //THIS EXTENDS WHAT IS IN EX10 TO SPARSE GRIDS (so stochastic dimension grater than 3) using namespace femus; //BEGIN stochastic data unsigned alpha = 6; unsigned M = pow ( 10, alpha ); //number of samples unsigned N = 1; //dimension of the parameter space (each of the M samples has N entries) unsigned L = alpha + 3; bool output = false; //for debugging bool matlabView = true; //FOR NORMAL DISTRIBUTION boost::mt19937 rng; // I don't seed it on purpouse (it's not relevant) boost::normal_distribution<> nd ( 0., 1. ); boost::variate_generator < boost::mt19937&, boost::normal_distribution<> > var_nor ( rng, nd ); //FOR UNIFORM DISTRIBUTION boost::mt19937 rng1; // I don't seed it on purpouse (it's not relevant) boost::random::uniform_real_distribution<> un ( - 1., 1. ); boost::variate_generator < boost::mt19937&, boost::random::uniform_real_distribution<> > var_unif ( rng1, un ); //FOR LAPLACE DISTRIBUTION boost::mt19937 rng2; // I don't seed it on purpouse (it's not relevant) boost::random::uniform_real_distribution<> un1 ( - 0.5, 0.49999999999 ); boost::variate_generator < boost::mt19937&, boost::random::uniform_real_distribution<> > var_unif1 ( rng2, un1 ); double b = 2.; //END int main ( int argc, char** argv ) { std::vector < std::vector < double > > samples; samples.resize ( M ); for ( unsigned m = 0; m < M; m++ ) { samples[m].resize ( N ); } for ( unsigned m = 0; m < M; m++ ) { for ( unsigned n = 0; n < N; n++ ) { double var = var_nor(); double varunif = var_unif(); double U = var_unif1(); // samples[m][n] = var * var * var; // samples[m][n] = exp(var); // samples[m][n] = exp (varunif); samples[m][n] = var; //exp of truncated gaussian // if(fabs(var) <= 1.) { // samples[m][n] = var / (0.5 * ((1. + erf((1. / 0.3) / sqrt(2))) - (1. + erf((- 1. / 0.3) / sqrt(2))))) ; //truncated Gaussian // } // else samples[m][n] = 0.; //laplace distribution // double signU = 0.; // if(U < 0) signU = - 1.; // else if(U > 0) signU = 1.; // samples[m][n] = 0. - b * signU * log(1. - 2. * fabs(U)) ; // std::cout << "samples[" << m << "][" << n << "]=" << samples[m][n] << std::endl; } } clock_t total_time = clock(); clock_t grid_time = clock(); sparseGrid spg ( samples, output ); std::cout << std::endl << " Builds sparse grid in: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - grid_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; clock_t nodal_time = clock(); spg.EvaluateNodalValuesPDF ( samples ); spg.PrintNodalValuesPDF(); std::cout << std::endl << " Builds nodal values in: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - nodal_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; //BEGIN these are just tests // double phi; // double x = 0.; // unsigned nn = 0; // unsigned ll = 0; // unsigned ii = 0; // bool scale = false; // spg.EvaluateOneDimensionalPhi(phi, x, nn, ll, ii, scale); // // // std::cout << "phi = " << phi << std::endl; // // std::vector< std::vector < unsigned > > id; // id.resize(N); // for(unsigned n=0; n<N; n++){ // id[n].resize(3); // } // // id[0][0] = 0; // id[0][1] = 0; // id[0][2] = 0; // id[1][0] = 1; // id[1][1] = 0; // id[1][2] = 0; // // double phiTensorProduct; // std::vector<double> coords(N); // for(unsigned n=0; n<N; n++){ // coords[n]=0.; // } // // spg.EvaluatePhi (phiTensorProduct, coords, id, false); // // // std::cout<<"phiTensorProduct = " << phiTensorProduct << std::endl; //END //BEGIN create grid for plot in 2D //sampling from [-1,1] for both variables, testing on uniform PDF on [-1.5,1,5] x [-1.5,1.5] std::vector < unsigned > refinementLevel ( N ); refinementLevel[0] = L; //refinement level in x if ( N > 1 ) refinementLevel[1] = L; //refinement level in y if ( N > 2 ) refinementLevel[2] = L; //refinement level in x std::vector < unsigned > gridPoints ( N ); std::vector < std::vector < double> > gridBounds ( N ); for ( unsigned n = 0; n < N; n++ ) { gridPoints[n] = static_cast<unsigned> ( pow ( 2, refinementLevel[n] ) + 1 ); gridBounds[n].resize ( 2 ); } unsigned gridSize = 1; for ( unsigned n = 0; n < N; n++ ) { gridSize *= gridPoints[n]; } gridBounds[0][0] = -5.45091; //-1.5 for uniform // -5.5 for Gaussian gridBounds[0][1] = 5.41019; //1.5 for uniform // 5.5 for Gaussian if ( N > 1 ) { gridBounds[1][0] = -5.5; gridBounds[1][1] = 5.5; } if ( N > 2 ) { gridBounds[2][0] = -1.5; gridBounds[2][1] = 1.5; } std::vector < double > h ( N ); for ( unsigned n = 0; n < N; n++ ) { h[n] = ( gridBounds[n][1] - gridBounds[n][0] ) / pow ( 2, refinementLevel[n] ); } std::vector < std::vector < double > > grid; unsigned counterGrid = 0; // for ( unsigned j = 0; j < gridPoints[1]; j++ ) { for ( unsigned i = 0; i < gridPoints[0]; i++ ) { grid.resize ( counterGrid + 1 ); grid[counterGrid].resize ( N ); grid[counterGrid][0] = gridBounds[0][0] + i * h[0]; // grid[counterGrid][1] = gridBounds[1][0] + j * h[1]; counterGrid++; } // } //END create grid std::vector< std::vector < unsigned > > idPhi ( N ); for ( unsigned n = 0; n < N; n++ ) { idPhi[n].resize ( 3 ); } //BEGIN these are just tests // phi_000 * phi_100 // idPhi[0][0] = 0; // idPhi[0][1] = 0; // idPhi[0][2] = 0; // idPhi[1][0] = 1; // idPhi[1][1] = 0; // idPhi[1][2] = 0; // phi_010 * phi_100 // idPhi[0][0] = 0; // idPhi[0][1] = 1; // idPhi[0][2] = 0; // idPhi[1][0] = 1; // idPhi[1][1] = 0; // idPhi[1][2] = 0; // phi_012 * phi_100 // idPhi[0][0] = 0; // idPhi[0][1] = 1; // idPhi[0][2] = 2; // idPhi[1][0] = 1; // idPhi[1][1] = 0; // idPhi[1][2] = 0; //END //BEGIN grid plot if ( matlabView ) { std::cout << "x=[" << std::endl; for ( unsigned i = 0; i < grid.size(); i++ ) { std::cout << grid[i][0] << std::endl; } std::cout << "];" << std::endl; // std::cout << "y=[" << std::endl; // // for ( unsigned i = 0; i < grid.size(); i++ ) { // std::cout << grid[i][1] << std::endl; // } // // std::cout << "];" << std::endl; clock_t pdf_time = clock(); std::cout << "PDF=[" << std::endl; for ( unsigned i = 0; i < grid.size(); i++ ) { double pdfValue; spg.EvaluatePDF ( pdfValue, grid[i] ); std::cout << std::setprecision ( 14 ) << pdfValue << std::endl; // double phiTensorProductTest; // spg.EvaluatePhi ( phiTensorProductTest, grid[i], idPhi, false ); // std::cout << grid[i][0] << " , " << grid[i][1] << std::endl; // std::cout << phiTensorProductTest << std::endl; } std::cout << "];" << std::endl; std::cout << std::endl << " Builds PDF in: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - pdf_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; } //END grid plot //BEGIN these are just tests // double phiTensorProductTest; // std::vector< double> trialX ( 2 ); // trialX[0] = -0.75; // trialX[1] = 0.; // spg.EvaluatePhi ( phiTensorProductTest, trialX, idPhi, true ); // std::cout << phiTensorProductTest << std::endl; //END //BEGIN compute error clock_t error_time = clock(); double sumError = 0.; for ( unsigned m = 0; m < samples.size(); m++ ) { double pdfValue; spg.EvaluatePDF ( pdfValue, samples[m] ); // double uniformPDF = ( fabs ( samples[m][0] ) <= 1 && fabs ( samples[m][1] ) <= 1 ) ? 0.25 : 0.; double Gaussian = exp ( -samples[m][0] * samples[m][0] * 0.5 ) / sqrt( 2 * acos ( -1 ) ) /** exp ( -samples[m][1] * samples[m][1] * 0.5 ) / sqrt( 2 * acos ( -1 ) )*/; double errorSquared = ( pdfValue - Gaussian ) * ( pdfValue - Gaussian ); sumError += errorSquared; } double aL2E = sqrt ( sumError ) / M; std::cout << " Averaged L2 error is = " << aL2E << std::endl; //END std::cout << std::endl << " Computes error in: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - error_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; std::cout << std::endl << " Total time: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - total_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; return 0; } //end main <commit_msg>tested 1D uniform PDF<commit_after>#include "FemusInit.hpp" #include "MultiLevelProblem.hpp" #include "VTKWriter.hpp" #include "TransientSystem.hpp" #include "NonLinearImplicitSystem.hpp" #include "NumericVector.hpp" #include "adept.h" #include "petsc.h" #include "petscmat.h" #include "PetscMatrix.hpp" #include "slepceps.h" #include "sparseGrid.hpp" //THIS EXTENDS WHAT IS IN EX10 TO SPARSE GRIDS (so stochastic dimension grater than 3) using namespace femus; //BEGIN stochastic data unsigned alpha = 6; unsigned M = pow ( 10, alpha ); //number of samples unsigned N = 1; //dimension of the parameter space (each of the M samples has N entries) unsigned L = alpha + 3; bool output = false; //for debugging bool matlabView = true; //FOR NORMAL DISTRIBUTION boost::mt19937 rng; // I don't seed it on purpouse (it's not relevant) boost::normal_distribution<> nd ( 0., 1. ); boost::variate_generator < boost::mt19937&, boost::normal_distribution<> > var_nor ( rng, nd ); //FOR UNIFORM DISTRIBUTION boost::mt19937 rng1; // I don't seed it on purpouse (it's not relevant) boost::random::uniform_real_distribution<> un ( - 1., 1. ); boost::variate_generator < boost::mt19937&, boost::random::uniform_real_distribution<> > var_unif ( rng1, un ); //FOR LAPLACE DISTRIBUTION boost::mt19937 rng2; // I don't seed it on purpouse (it's not relevant) boost::random::uniform_real_distribution<> un1 ( - 0.5, 0.49999999999 ); boost::variate_generator < boost::mt19937&, boost::random::uniform_real_distribution<> > var_unif1 ( rng2, un1 ); double b = 2.; //END int main ( int argc, char** argv ) { std::vector < std::vector < double > > samples; samples.resize ( M ); for ( unsigned m = 0; m < M; m++ ) { samples[m].resize ( N ); } for ( unsigned m = 0; m < M; m++ ) { for ( unsigned n = 0; n < N; n++ ) { double var = var_nor(); double varunif = var_unif(); double U = var_unif1(); // samples[m][n] = var * var * var; // samples[m][n] = exp(var); // samples[m][n] = exp (varunif); samples[m][n] = varunif; //exp of truncated gaussian // if(fabs(var) <= 1.) { // samples[m][n] = var / (0.5 * ((1. + erf((1. / 0.3) / sqrt(2))) - (1. + erf((- 1. / 0.3) / sqrt(2))))) ; //truncated Gaussian // } // else samples[m][n] = 0.; //laplace distribution // double signU = 0.; // if(U < 0) signU = - 1.; // else if(U > 0) signU = 1.; // samples[m][n] = 0. - b * signU * log(1. - 2. * fabs(U)) ; // std::cout << "samples[" << m << "][" << n << "]=" << samples[m][n] << std::endl; } } clock_t total_time = clock(); clock_t grid_time = clock(); sparseGrid spg ( samples, output ); std::cout << std::endl << " Builds sparse grid in: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - grid_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; clock_t nodal_time = clock(); spg.EvaluateNodalValuesPDF ( samples ); // spg.PrintNodalValuesPDF(); std::cout << std::endl << " Builds nodal values in: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - nodal_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; //BEGIN these are just tests // double phi; // double x = 0.; // unsigned nn = 0; // unsigned ll = 0; // unsigned ii = 0; // bool scale = false; // spg.EvaluateOneDimensionalPhi(phi, x, nn, ll, ii, scale); // // // std::cout << "phi = " << phi << std::endl; // // std::vector< std::vector < unsigned > > id; // id.resize(N); // for(unsigned n=0; n<N; n++){ // id[n].resize(3); // } // // id[0][0] = 0; // id[0][1] = 0; // id[0][2] = 0; // id[1][0] = 1; // id[1][1] = 0; // id[1][2] = 0; // // double phiTensorProduct; // std::vector<double> coords(N); // for(unsigned n=0; n<N; n++){ // coords[n]=0.; // } // // spg.EvaluatePhi (phiTensorProduct, coords, id, false); // // // std::cout<<"phiTensorProduct = " << phiTensorProduct << std::endl; //END //BEGIN create grid for plot in 2D //sampling from [-1,1] for both variables, testing on uniform PDF on [-1.5,1,5] x [-1.5,1.5] std::vector < unsigned > refinementLevel ( N ); refinementLevel[0] = L; //refinement level in x if ( N > 1 ) refinementLevel[1] = L; //refinement level in y if ( N > 2 ) refinementLevel[2] = L; //refinement level in x std::vector < unsigned > gridPoints ( N ); std::vector < std::vector < double> > gridBounds ( N ); for ( unsigned n = 0; n < N; n++ ) { gridPoints[n] = static_cast<unsigned> ( pow ( 2, refinementLevel[n] ) + 1 ); gridBounds[n].resize ( 2 ); } unsigned gridSize = 1; for ( unsigned n = 0; n < N; n++ ) { gridSize *= gridPoints[n]; } gridBounds[0][0] = -1.5; //-1.5 for uniform // -5.5 for Gaussian gridBounds[0][1] = 1.5; //1.5 for uniform // 5.5 for Gaussian if ( N > 1 ) { gridBounds[1][0] = -5.5; gridBounds[1][1] = 5.5; } if ( N > 2 ) { gridBounds[2][0] = -1.5; gridBounds[2][1] = 1.5; } std::vector < double > h ( N ); for ( unsigned n = 0; n < N; n++ ) { h[n] = ( gridBounds[n][1] - gridBounds[n][0] ) / pow ( 2, refinementLevel[n] ); } std::vector < std::vector < double > > grid; unsigned counterGrid = 0; // for ( unsigned j = 0; j < gridPoints[1]; j++ ) { for ( unsigned i = 0; i < gridPoints[0]; i++ ) { grid.resize ( counterGrid + 1 ); grid[counterGrid].resize ( N ); grid[counterGrid][0] = gridBounds[0][0] + i * h[0]; // grid[counterGrid][1] = gridBounds[1][0] + j * h[1]; counterGrid++; } // } //END create grid std::vector< std::vector < unsigned > > idPhi ( N ); for ( unsigned n = 0; n < N; n++ ) { idPhi[n].resize ( 3 ); } //BEGIN these are just tests // phi_000 * phi_100 // idPhi[0][0] = 0; // idPhi[0][1] = 0; // idPhi[0][2] = 0; // idPhi[1][0] = 1; // idPhi[1][1] = 0; // idPhi[1][2] = 0; // phi_010 * phi_100 // idPhi[0][0] = 0; // idPhi[0][1] = 1; // idPhi[0][2] = 0; // idPhi[1][0] = 1; // idPhi[1][1] = 0; // idPhi[1][2] = 0; // phi_012 * phi_100 // idPhi[0][0] = 0; // idPhi[0][1] = 1; // idPhi[0][2] = 2; // idPhi[1][0] = 1; // idPhi[1][1] = 0; // idPhi[1][2] = 0; //END //BEGIN grid plot if ( matlabView ) { std::cout << "x=[" << std::endl; for ( unsigned i = 0; i < grid.size(); i++ ) { std::cout << grid[i][0] << std::endl; } std::cout << "];" << std::endl; // std::cout << "y=[" << std::endl; // // for ( unsigned i = 0; i < grid.size(); i++ ) { // std::cout << grid[i][1] << std::endl; // } // // std::cout << "];" << std::endl; clock_t pdf_time = clock(); std::cout << "PDF=[" << std::endl; for ( unsigned i = 0; i < grid.size(); i++ ) { double pdfValue; spg.EvaluatePDF ( pdfValue, grid[i] ); std::cout << std::setprecision ( 14 ) << pdfValue << std::endl; // double phiTensorProductTest; // spg.EvaluatePhi ( phiTensorProductTest, grid[i], idPhi, false ); // std::cout << grid[i][0] << " , " << grid[i][1] << std::endl; // std::cout << phiTensorProductTest << std::endl; } std::cout << "];" << std::endl; std::cout << std::endl << " Builds PDF in: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - pdf_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; } //END grid plot //BEGIN these are just tests // double phiTensorProductTest; // std::vector< double> trialX ( 2 ); // trialX[0] = -0.75; // trialX[1] = 0.; // spg.EvaluatePhi ( phiTensorProductTest, trialX, idPhi, true ); // std::cout << phiTensorProductTest << std::endl; //END //BEGIN compute error clock_t error_time = clock(); double sumError = 0.; for ( unsigned m = 0; m < samples.size(); m++ ) { double pdfValue; spg.EvaluatePDF ( pdfValue, samples[m] ); double uniformPDF = ( fabs ( samples[m][0] ) <= 1 /*&& fabs ( samples[m][1]) <= 1*/) ? 0.5 : 0.; // double Gaussian = exp ( -samples[m][0] * samples[m][0] * 0.5 ) / sqrt( 2 * acos ( -1 ) ) /** exp ( -samples[m][1] * samples[m][1] * 0.5 ) / sqrt( 2 * acos ( -1 ) )*/; double errorSquared = ( pdfValue - uniformPDF ) * ( pdfValue - uniformPDF ); sumError += errorSquared; } double aL2E = sqrt ( sumError ) / M; std::cout << " Averaged L2 error is = " << aL2E << std::endl; //END std::cout << std::endl << " Computes error in: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - error_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; std::cout << std::endl << " Total time: " << std::setw ( 11 ) << std::setprecision ( 6 ) << std::fixed << static_cast<double> ( ( clock() - total_time ) ) / CLOCKS_PER_SEC << " s" << std::endl; return 0; } //end main <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // 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 other 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 "pch.hpp" #include <kiss_fftr.h> #include <core/debug.h> #include <core/audio/Player.h> #include <core/audio/Stream.h> #include <core/audio/Visualizer.h> #include <core/plugin/PluginFactory.h> #include <algorithm> #include <math.h> #include <future> #define MAX_PREBUFFER_QUEUE_COUNT 8 #define FFT_N 512 #define PI 3.14159265358979323846 using namespace musik::core::audio; using namespace musik::core::sdk; using std::min; using std::max; static std::string TAG = "Player"; static float* hammingWindow = nullptr; namespace musik { namespace core { namespace audio { static void playerThreadLoop(Player* player); struct FftContext { FftContext() { samples = 0; cfg = nullptr; deinterleaved = nullptr; scratch = nullptr; } ~FftContext() { Reset(); } void Reset() { kiss_fftr_free(cfg); delete[] deinterleaved; delete[] scratch; cfg = nullptr; deinterleaved = nullptr; scratch = nullptr; } void Init(int samples) { if (!cfg || samples != this->samples) { Reset(); cfg = kiss_fftr_alloc(FFT_N, false, 0, 0); deinterleaved = new float[samples]; scratch = new kiss_fft_cpx[(FFT_N / 2) + 1]; this->samples = samples; } } int samples; kiss_fftr_cfg cfg; float* deinterleaved; kiss_fft_cpx* scratch; }; } } } Player* Player::Create(const std::string &url, OutputPtr output) { return new Player(url, output); } OutputPtr Player::CreateDefaultOutput() { /* if no output is specified, find all output plugins, and select the first one. */ typedef std::vector<OutputPtr> OutputVector; OutputVector outputs = musik::core::PluginFactory::Instance().QueryInterface< IOutput, musik::core::PluginFactory::DestroyDeleter<IOutput> >("GetAudioOutput"); if (!outputs.empty()) { musik::debug::info(TAG, "found an IOutput device!"); return outputs.front(); } return OutputPtr(); } Player::Player(const std::string &url, OutputPtr output) : state(Player::Precache) , url(url) , currentPosition(0) , output(output) , notifiedStarted(false) , setPosition(-1) , fftContext(nullptr) { musik::debug::info(TAG, "new instance created"); this->spectrum = new float[FFT_N / 2]; /* we allow callers to specify an output device; but if they don't, we will create and manage our own. */ if (!this->output) { throw std::runtime_error("output cannot be null!"); } /* each player instance is driven by a background thread. start it. */ this->thread.reset(new std::thread(std::bind(&musik::core::audio::playerThreadLoop, this))); } Player::~Player() { delete[] this->spectrum; delete fftContext; } void Player::Play() { std::unique_lock<std::mutex> lock(this->queueMutex); if (this->state != Player::Quit) { this->state = Player::Playing; this->writeToOutputCondition.notify_all(); } } void Player::Destroy() { { std::unique_lock<std::mutex> lock(this->queueMutex); if (this->state == Player::Quit && !this->thread) { return; /* already terminated (or terminating) */ } this->state = Player::Quit; this->writeToOutputCondition.notify_all(); this->thread->detach(); } } double Player::Position() { std::unique_lock<std::mutex> lock(this->positionMutex); return this->currentPosition; } void Player::SetPosition(double seconds) { std::unique_lock<std::mutex> lock(this->positionMutex); this->setPosition = std::max(0.0, seconds); } int Player::State() { std::unique_lock<std::mutex> lock(this->queueMutex); return this->state; } static void musik::core::audio::playerThreadLoop(Player* player) { player->stream = Stream::Create(); BufferPtr buffer; if (player->stream->OpenStream(player->url)) { /* precache until buffers are full */ bool keepPrecaching = true; while (player->State() == Player::Precache && keepPrecaching) { keepPrecaching = player->PreBuffer(); } /* wait until we enter the Playing or Quit state; we may still be in the Precache state. */ { std::unique_lock<std::mutex> lock(player->queueMutex); while (player->state == Player::Precache) { player->writeToOutputCondition.wait(lock); } } /* we're ready to go.... */ bool finished = false; while (!finished && !player->Exited()) { /* see if we've been asked to seek since the last sample was played. if we have, clear our output buffer and seek the stream. */ double position = -1; { std::unique_lock<std::mutex> lock(player->positionMutex); position = player->setPosition; player->setPosition = -1; } if (position != -1) { player->output->Stop(); /* flush all buffers */ player->output->Resume(); /* start it back up */ /* if we've allocated a buffer, but it hasn't been written to the output yet, unlock it. this is an important step, and if not performed, will result in a deadlock just below while waiting for all buffers to complete. */ if (buffer) { player->OnBufferProcessed(buffer.get()); buffer.reset(); } { std::unique_lock<std::mutex> lock(player->queueMutex); while (player->lockedBuffers.size() > 0) { player->writeToOutputCondition.wait(lock); } } player->stream->SetPosition(position); { std::unique_lock<std::mutex> lock(player->queueMutex); player->prebufferQueue.clear(); } } /* let's see if we can find some samples to play */ if (!buffer) { std::unique_lock<std::mutex> lock(player->queueMutex); /* the buffer queue may already have some available if it was prefetched. */ if (!player->prebufferQueue.empty()) { buffer = player->prebufferQueue.front(); player->prebufferQueue.pop_front(); } /* otherwise, we need to grab a buffer from the stream and add it to the queue */ else { buffer = player->stream->GetNextProcessedOutputBuffer(); } /* lock it down until it's processed */ if (buffer) { player->lockedBuffers.push_back(buffer); } } /* if we have a decoded, processed buffer available. let's try to send it to the output device. */ if (buffer) { if (player->output->Play(buffer.get(), player)) { /* success! the buffer was accepted by the output.*/ /* lock it down so it's not destroyed until the output device lets us know it's done with it. */ std::unique_lock<std::mutex> lock(player->queueMutex); if (player->lockedBuffers.size() == 1) { player->currentPosition = buffer->Position(); } buffer.reset(); /* important! we're done with this one locally. */ } else { /* the output device queue is full. we should block and wait until the output lets us know that it needs more data */ std::unique_lock<std::mutex> lock(player->queueMutex); player->writeToOutputCondition.wait(lock); } } /* if we're unable to obtain a buffer, it means we're out of data and the player is finished. terminate the thread. */ else { finished = true; } } /* if the Quit flag isn't set, that means the stream has ended "naturally", i.e. it wasn't stopped by the user. raise the "almost ended" flag. */ if (!player->Exited()) { player->PlaybackAlmostEnded(player); } } /* if the stream failed to open... */ else { player->PlaybackError(player); } player->state = Player::Quit; /* unlock any remaining buffers... see comment above */ if (buffer) { player->OnBufferProcessed(buffer.get()); buffer.reset(); } /* wait until all remaining buffers have been written, set final state... */ { std::unique_lock<std::mutex> lock(player->queueMutex); while (player->lockedBuffers.size() > 0) { player->writeToOutputCondition.wait(lock); } } player->PlaybackFinished(player); delete player; } void Player::ReleaseAllBuffers() { std::unique_lock<std::mutex> lock(this->queueMutex); this->lockedBuffers.empty(); } bool Player::PreBuffer() { /* don't prebuffer if the buffer is already full */ if (this->prebufferQueue.size() < MAX_PREBUFFER_QUEUE_COUNT) { BufferPtr newBuffer = this->stream->GetNextProcessedOutputBuffer(); if (newBuffer) { std::unique_lock<std::mutex> lock(this->queueMutex); this->prebufferQueue.push_back(newBuffer); } return true; } return false; } bool Player::Exited() { std::unique_lock<std::mutex> lock(this->queueMutex); return (this->state == Player::Quit); } static inline void initHammingWindow() { delete hammingWindow; hammingWindow = new float[FFT_N]; for (int i = 0; i < FFT_N; i++) { hammingWindow[i] = 0.54f - 0.46f * (float) cos((2 * PI * i) / (FFT_N - 1)); } } static inline bool performFft(IBuffer* buffer, FftContext* fft, float* output, int outputSize) { long samples = buffer->Samples(); int channels = buffer->Channels(); long samplesPerChannel = samples / channels; if (samplesPerChannel < FFT_N || outputSize != FFT_N / 2) { return false; } if (!hammingWindow) { initHammingWindow(); } memset(output, 0, outputSize * sizeof(float)); float* input = buffer->BufferPointer(); fft->Init(samples); for (int i = 0; i < samples; i++) { const int to = ((i % channels) * samplesPerChannel) + (i / channels); fft->deinterleaved[to] = input[i] * hammingWindow[to % FFT_N]; } int offset = 0; int iterations = samples / FFT_N; for (int i = 0; i < iterations; i++) { kiss_fftr(fft->cfg, fft->deinterleaved + offset, fft->scratch); for (int z = 0; z < outputSize; z++) { /* convert to decibels */ double db = (fft->scratch[z].r * fft->scratch[z].r + fft->scratch[z].i + fft->scratch[z].i); output[z] += (db < 1 ? 0 : 20 * (float) log10(db)) / iterations; /* frequencies over all channels */ } offset += FFT_N; } return true; } void Player::OnBufferProcessed(IBuffer *buffer) { bool started = false; bool found = false; /* process visualizer data, and write to the selected plugin, if applicable */ ISpectrumVisualizer* specVis = vis::SpectrumVisualizer(); IPcmVisualizer* pcmVis = vis::PcmVisualizer(); if (specVis && specVis->Visible()) { if (!fftContext) { fftContext = new FftContext(); } if (performFft(buffer, fftContext, spectrum, FFT_N / 2)) { vis::SpectrumVisualizer()->Write(spectrum, FFT_N / 2); } } else if (pcmVis && pcmVis->Visible()) { vis::PcmVisualizer()->Write(buffer); } /* free the buffer */ { std::unique_lock<std::mutex> lock(this->queueMutex); /* removes the specified buffer from the list of locked buffers, and also lets the stream know it can be recycled. */ BufferList::iterator it = this->lockedBuffers.begin(); while (it != this->lockedBuffers.end() && !found) { if (it->get() == buffer) { found = true; if (this->stream) { this->stream->OnBufferProcessedByPlayer(*it); } bool isFront = this->lockedBuffers.front() == *it; it = this->lockedBuffers.erase(it); /* this sets the current time in the stream. it does this by grabbing the time at the next buffer in the queue */ if (this->lockedBuffers.empty() || isFront) { this->currentPosition = ((Buffer*)buffer)->Position(); } else { /* if the queue is drained, use the position from the buffer that was just processed */ this->currentPosition = this->lockedBuffers.front()->Position(); } /* if the output device's internal buffers are full, it will stop accepting new samples. now that a buffer has been processed, we can try to enqueue another sample. the thread loop blocks on this condition */ this->writeToOutputCondition.notify_all(); } else { ++it; } } if (!this->notifiedStarted) { this->notifiedStarted = true; started = true; } } /* we notify our listeners that we've started playing only after the first buffer has been consumed. this is because sometimes we precache buffers and send them to the output before they are actually processed by the output device */ if (started) { this->PlaybackStarted(this); } } <commit_msg>Just kidding about fixing the clang compile -- remove static qualifier to hopefully fix it for real.<commit_after>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // 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 other 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 "pch.hpp" #include <kiss_fftr.h> #include <core/debug.h> #include <core/audio/Player.h> #include <core/audio/Stream.h> #include <core/audio/Visualizer.h> #include <core/plugin/PluginFactory.h> #include <algorithm> #include <math.h> #include <future> #define MAX_PREBUFFER_QUEUE_COUNT 8 #define FFT_N 512 #define PI 3.14159265358979323846 using namespace musik::core::audio; using namespace musik::core::sdk; using std::min; using std::max; static std::string TAG = "Player"; static float* hammingWindow = nullptr; namespace musik { namespace core { namespace audio { void playerThreadLoop(Player* player); struct FftContext { FftContext() { samples = 0; cfg = nullptr; deinterleaved = nullptr; scratch = nullptr; } ~FftContext() { Reset(); } void Reset() { kiss_fftr_free(cfg); delete[] deinterleaved; delete[] scratch; cfg = nullptr; deinterleaved = nullptr; scratch = nullptr; } void Init(int samples) { if (!cfg || samples != this->samples) { Reset(); cfg = kiss_fftr_alloc(FFT_N, false, 0, 0); deinterleaved = new float[samples]; scratch = new kiss_fft_cpx[(FFT_N / 2) + 1]; this->samples = samples; } } int samples; kiss_fftr_cfg cfg; float* deinterleaved; kiss_fft_cpx* scratch; }; } } } Player* Player::Create(const std::string &url, OutputPtr output) { return new Player(url, output); } OutputPtr Player::CreateDefaultOutput() { /* if no output is specified, find all output plugins, and select the first one. */ typedef std::vector<OutputPtr> OutputVector; OutputVector outputs = musik::core::PluginFactory::Instance().QueryInterface< IOutput, musik::core::PluginFactory::DestroyDeleter<IOutput> >("GetAudioOutput"); if (!outputs.empty()) { musik::debug::info(TAG, "found an IOutput device!"); return outputs.front(); } return OutputPtr(); } Player::Player(const std::string &url, OutputPtr output) : state(Player::Precache) , url(url) , currentPosition(0) , output(output) , notifiedStarted(false) , setPosition(-1) , fftContext(nullptr) { musik::debug::info(TAG, "new instance created"); this->spectrum = new float[FFT_N / 2]; /* we allow callers to specify an output device; but if they don't, we will create and manage our own. */ if (!this->output) { throw std::runtime_error("output cannot be null!"); } /* each player instance is driven by a background thread. start it. */ this->thread.reset(new std::thread(std::bind(&musik::core::audio::playerThreadLoop, this))); } Player::~Player() { delete[] this->spectrum; delete fftContext; } void Player::Play() { std::unique_lock<std::mutex> lock(this->queueMutex); if (this->state != Player::Quit) { this->state = Player::Playing; this->writeToOutputCondition.notify_all(); } } void Player::Destroy() { { std::unique_lock<std::mutex> lock(this->queueMutex); if (this->state == Player::Quit && !this->thread) { return; /* already terminated (or terminating) */ } this->state = Player::Quit; this->writeToOutputCondition.notify_all(); this->thread->detach(); } } double Player::Position() { std::unique_lock<std::mutex> lock(this->positionMutex); return this->currentPosition; } void Player::SetPosition(double seconds) { std::unique_lock<std::mutex> lock(this->positionMutex); this->setPosition = std::max(0.0, seconds); } int Player::State() { std::unique_lock<std::mutex> lock(this->queueMutex); return this->state; } void musik::core::audio::playerThreadLoop(Player* player) { player->stream = Stream::Create(); BufferPtr buffer; if (player->stream->OpenStream(player->url)) { /* precache until buffers are full */ bool keepPrecaching = true; while (player->State() == Player::Precache && keepPrecaching) { keepPrecaching = player->PreBuffer(); } /* wait until we enter the Playing or Quit state; we may still be in the Precache state. */ { std::unique_lock<std::mutex> lock(player->queueMutex); while (player->state == Player::Precache) { player->writeToOutputCondition.wait(lock); } } /* we're ready to go.... */ bool finished = false; while (!finished && !player->Exited()) { /* see if we've been asked to seek since the last sample was played. if we have, clear our output buffer and seek the stream. */ double position = -1; { std::unique_lock<std::mutex> lock(player->positionMutex); position = player->setPosition; player->setPosition = -1; } if (position != -1) { player->output->Stop(); /* flush all buffers */ player->output->Resume(); /* start it back up */ /* if we've allocated a buffer, but it hasn't been written to the output yet, unlock it. this is an important step, and if not performed, will result in a deadlock just below while waiting for all buffers to complete. */ if (buffer) { player->OnBufferProcessed(buffer.get()); buffer.reset(); } { std::unique_lock<std::mutex> lock(player->queueMutex); while (player->lockedBuffers.size() > 0) { player->writeToOutputCondition.wait(lock); } } player->stream->SetPosition(position); { std::unique_lock<std::mutex> lock(player->queueMutex); player->prebufferQueue.clear(); } } /* let's see if we can find some samples to play */ if (!buffer) { std::unique_lock<std::mutex> lock(player->queueMutex); /* the buffer queue may already have some available if it was prefetched. */ if (!player->prebufferQueue.empty()) { buffer = player->prebufferQueue.front(); player->prebufferQueue.pop_front(); } /* otherwise, we need to grab a buffer from the stream and add it to the queue */ else { buffer = player->stream->GetNextProcessedOutputBuffer(); } /* lock it down until it's processed */ if (buffer) { player->lockedBuffers.push_back(buffer); } } /* if we have a decoded, processed buffer available. let's try to send it to the output device. */ if (buffer) { if (player->output->Play(buffer.get(), player)) { /* success! the buffer was accepted by the output.*/ /* lock it down so it's not destroyed until the output device lets us know it's done with it. */ std::unique_lock<std::mutex> lock(player->queueMutex); if (player->lockedBuffers.size() == 1) { player->currentPosition = buffer->Position(); } buffer.reset(); /* important! we're done with this one locally. */ } else { /* the output device queue is full. we should block and wait until the output lets us know that it needs more data */ std::unique_lock<std::mutex> lock(player->queueMutex); player->writeToOutputCondition.wait(lock); } } /* if we're unable to obtain a buffer, it means we're out of data and the player is finished. terminate the thread. */ else { finished = true; } } /* if the Quit flag isn't set, that means the stream has ended "naturally", i.e. it wasn't stopped by the user. raise the "almost ended" flag. */ if (!player->Exited()) { player->PlaybackAlmostEnded(player); } } /* if the stream failed to open... */ else { player->PlaybackError(player); } player->state = Player::Quit; /* unlock any remaining buffers... see comment above */ if (buffer) { player->OnBufferProcessed(buffer.get()); buffer.reset(); } /* wait until all remaining buffers have been written, set final state... */ { std::unique_lock<std::mutex> lock(player->queueMutex); while (player->lockedBuffers.size() > 0) { player->writeToOutputCondition.wait(lock); } } player->PlaybackFinished(player); delete player; } void Player::ReleaseAllBuffers() { std::unique_lock<std::mutex> lock(this->queueMutex); this->lockedBuffers.empty(); } bool Player::PreBuffer() { /* don't prebuffer if the buffer is already full */ if (this->prebufferQueue.size() < MAX_PREBUFFER_QUEUE_COUNT) { BufferPtr newBuffer = this->stream->GetNextProcessedOutputBuffer(); if (newBuffer) { std::unique_lock<std::mutex> lock(this->queueMutex); this->prebufferQueue.push_back(newBuffer); } return true; } return false; } bool Player::Exited() { std::unique_lock<std::mutex> lock(this->queueMutex); return (this->state == Player::Quit); } static inline void initHammingWindow() { delete hammingWindow; hammingWindow = new float[FFT_N]; for (int i = 0; i < FFT_N; i++) { hammingWindow[i] = 0.54f - 0.46f * (float) cos((2 * PI * i) / (FFT_N - 1)); } } static inline bool performFft(IBuffer* buffer, FftContext* fft, float* output, int outputSize) { long samples = buffer->Samples(); int channels = buffer->Channels(); long samplesPerChannel = samples / channels; if (samplesPerChannel < FFT_N || outputSize != FFT_N / 2) { return false; } if (!hammingWindow) { initHammingWindow(); } memset(output, 0, outputSize * sizeof(float)); float* input = buffer->BufferPointer(); fft->Init(samples); for (int i = 0; i < samples; i++) { const int to = ((i % channels) * samplesPerChannel) + (i / channels); fft->deinterleaved[to] = input[i] * hammingWindow[to % FFT_N]; } int offset = 0; int iterations = samples / FFT_N; for (int i = 0; i < iterations; i++) { kiss_fftr(fft->cfg, fft->deinterleaved + offset, fft->scratch); for (int z = 0; z < outputSize; z++) { /* convert to decibels */ double db = (fft->scratch[z].r * fft->scratch[z].r + fft->scratch[z].i + fft->scratch[z].i); output[z] += (db < 1 ? 0 : 20 * (float) log10(db)) / iterations; /* frequencies over all channels */ } offset += FFT_N; } return true; } void Player::OnBufferProcessed(IBuffer *buffer) { bool started = false; bool found = false; /* process visualizer data, and write to the selected plugin, if applicable */ ISpectrumVisualizer* specVis = vis::SpectrumVisualizer(); IPcmVisualizer* pcmVis = vis::PcmVisualizer(); if (specVis && specVis->Visible()) { if (!fftContext) { fftContext = new FftContext(); } if (performFft(buffer, fftContext, spectrum, FFT_N / 2)) { vis::SpectrumVisualizer()->Write(spectrum, FFT_N / 2); } } else if (pcmVis && pcmVis->Visible()) { vis::PcmVisualizer()->Write(buffer); } /* free the buffer */ { std::unique_lock<std::mutex> lock(this->queueMutex); /* removes the specified buffer from the list of locked buffers, and also lets the stream know it can be recycled. */ BufferList::iterator it = this->lockedBuffers.begin(); while (it != this->lockedBuffers.end() && !found) { if (it->get() == buffer) { found = true; if (this->stream) { this->stream->OnBufferProcessedByPlayer(*it); } bool isFront = this->lockedBuffers.front() == *it; it = this->lockedBuffers.erase(it); /* this sets the current time in the stream. it does this by grabbing the time at the next buffer in the queue */ if (this->lockedBuffers.empty() || isFront) { this->currentPosition = ((Buffer*)buffer)->Position(); } else { /* if the queue is drained, use the position from the buffer that was just processed */ this->currentPosition = this->lockedBuffers.front()->Position(); } /* if the output device's internal buffers are full, it will stop accepting new samples. now that a buffer has been processed, we can try to enqueue another sample. the thread loop blocks on this condition */ this->writeToOutputCondition.notify_all(); } else { ++it; } } if (!this->notifiedStarted) { this->notifiedStarted = true; started = true; } } /* we notify our listeners that we've started playing only after the first buffer has been consumed. this is because sometimes we precache buffers and send them to the output before they are actually processed by the output device */ if (started) { this->PlaybackStarted(this); } } <|endoftext|>
<commit_before>/** @defgroup SLAM Slam files * * @brief Files use for SLAM algorithm */ /** * @class Slam * * @ingroup SLAM * * @brief Main Slam algorithm class * * This class is meant as a entry point to Slam algorithm for an Agent * * @author Nicolas * * @version 1.0 * * @date 28/04/2015 * */ #ifndef _SLAM_HH_ # define _SLAM_HH_ #include <pcl/common/common.h> #include <pcl/impl/point_types.hpp> #include <pcl/common/projection_matrix.h> #include "DataAssociation.hh" #include "KalmanGainMatrice.hh" #include "SystemStateMatrice.hh" #include "CovarianceMatrice.hh" #include "Landmarks.hh" #include "Agent.hh" class Slam { public: /** * @brief SLAM constructor * @details Take an agent wich will be link to the SLAM algorithm and * initialize all SLAM matrices with default values * * @param agent Agent on wich the API is installed */ Slam(Agent *agent); ~Slam(); /** * @brief Update agent state * @details Take the current mapping and the current agent state * (upated with the odometry), apply SLAM algorithm and update agent state * with new values * @warning Must be used after agent update odometry * * @param cloud Current mapping * @param agent Agent we want the state updated */ void updateState(pcl::PointCloud<pcl::PointXYZ> const &cloud, Agent &agent); /** * @brief Add a landmark * @details Function to ass a landmark to SLAM matrices * * @param newLandmarks New landmark extracted from the current mapping */ void addLandmarks(std::vector<Landmarks::Landmark *> const &newLandmarks); private: Slam(); private: Agent *_agent; Landmarks *_landmarkDb; DataAssociation *_data; KalmanGainMatrice _kg; SystemStateMatrice *_state; CovarianceMatrice *_covariance; }; #endif /*! _SLAM_HH_ */ <commit_msg>Slam: Set landmarkdb in public<commit_after>/** @defgroup SLAM Slam files * * @brief Files use for SLAM algorithm */ /** * @class Slam * * @ingroup SLAM * * @brief Main Slam algorithm class * * This class is meant as a entry point to Slam algorithm for an Agent * * @author Nicolas * * @version 1.0 * * @date 28/04/2015 * */ #ifndef _SLAM_HH_ # define _SLAM_HH_ #include <pcl/common/common.h> #include <pcl/impl/point_types.hpp> #include <pcl/common/projection_matrix.h> #include "DataAssociation.hh" #include "KalmanGainMatrice.hh" #include "SystemStateMatrice.hh" #include "CovarianceMatrice.hh" #include "Landmarks.hh" #include "Agent.hh" class Slam { public: /** * @brief SLAM constructor * @details Take an agent wich will be link to the SLAM algorithm and * initialize all SLAM matrices with default values * * @param agent Agent on wich the API is installed */ Slam(Agent *agent); ~Slam(); /** * @brief Update agent state * @details Take the current mapping and the current agent state * (upated with the odometry), apply SLAM algorithm and update agent state * with new values * @warning Must be used after agent update odometry * * @param cloud Current mapping * @param agent Agent we want the state updated */ void updateState(pcl::PointCloud<pcl::PointXYZ> const &cloud, Agent &agent); /** * @brief Add a landmark * @details Function to ass a landmark to SLAM matrices * * @param newLandmarks New landmark extracted from the current mapping */ void addLandmarks(std::vector<Landmarks::Landmark *> const &newLandmarks); private: Slam(); private: Agent *_agent; DataAssociation *_data; KalmanGainMatrice _kg; SystemStateMatrice *_state; CovarianceMatrice *_covariance; public: Landmarks *_landmarkDb; }; #endif /*! _SLAM_HH_ */ <|endoftext|>
<commit_before>#ifndef SRC_CORE_CONNECTABLES_HPP_ #define SRC_CORE_CONNECTABLES_HPP_ #include <cmath> #include <cassert> namespace fc { /** * A collection of different useful connectables. * A lot of them are names for simple lambdas to make code less verbose. */ /// Increments input using prefix operator ++. auto increment = [](auto in) { return ++in; }; /// Decrements input using prefix operator --. auto decrement = [](auto in) { return --in; }; /// Returns input unchanged. auto identity = [](auto in) { return in; }; /// Adds a constant addend to inputs. auto add_to = [](const auto summand) { return [summand](auto in){ return in + summand; }; }; /// Subtracts a constant subtrahend from inputs. auto subtract_value = [](const auto subtrahend) { return [subtrahend](auto in){ return in - subtrahend; }; }; /// Multiples input by a constant factor. auto multiply_with = [](const auto factor) { return [factor](auto in) { return factor * in; }; }; /// Divides inputs by a constant divisor. auto divide_by = [](const auto divisor) { return [divisor](auto in) { return in / divisor; }; }; /// Returns absolute value on input using std::abs. auto absolute = [](auto in) { return std::abs(in); }; /// Negates input using unary -. auto negate = [](auto in) { return -in; }; /// Returns logical not (operator !) of input. auto logical_not = [](auto in) { return !in; }; /** * \brief Clamps input to closed range [min, max]. * * \pre min <= max * \post output >= min && output <= max */ auto clamp = [](auto min, auto max) { assert(min <= max); return [min, max](auto in) { return in < min ? min: (max < in ? max : in); }; }; } // namespace fc #endif /* SRC_CORE_CONNECTABLES_HPP_ */ <commit_msg>Added connectables for mapping to sin, tri, saw and rect wave<commit_after>#ifndef SRC_CORE_CONNECTABLES_HPP_ #define SRC_CORE_CONNECTABLES_HPP_ #include <cmath> #include <cassert> namespace fc { /** * A collection of different useful connectables. * A lot of them are names for simple lambdas to make code less verbose. */ /// Increments input using prefix operator ++. auto increment = [](auto in) { return ++in; }; /// Decrements input using prefix operator --. auto decrement = [](auto in) { return --in; }; /// Returns input unchanged. auto identity = [](auto in) { return in; }; /// Adds a constant addend to inputs. auto add_to = [](const auto summand) { return [summand](auto in){ return in + summand; }; }; /// Subtracts a constant subtrahend from inputs. auto subtract_value = [](const auto subtrahend) { return [subtrahend](auto in){ return in - subtrahend; }; }; /// Multiples input by a constant factor. auto multiply_with = [](const auto factor) { return [factor](auto in) { return factor * in; }; }; /// Divides inputs by a constant divisor. auto divide_by = [](const auto divisor) { return [divisor](auto in) { return in / divisor; }; }; /// Returns absolute value on input using std::abs. auto absolute = [](auto in) { return std::abs(in); }; /// Negates input using unary -. auto negate = [](auto in) { return -in; }; /// Returns logical not (operator !) of input. auto logical_not = [](auto in) { return !in; }; /** * \brief Clamps input to closed range [min, max]. * * \pre min <= max * \post output >= min && output <= max */ auto clamp = [](auto min, auto max) { assert(min <= max); return [min, max](auto in) { return in < min ? min: (max < in ? max : in); }; }; /// Applies sin wave function to the input, wavelength is 1 double sin_wave = [](double in) { return std::sin(in * 2 * M_PI); }; /// Applies a saw wave function to the input, wavelength is 1 double saw_wave = [](double in) { in = (in < 2 ? 2 : 0) + fmod(in, 2); return 2*(2*in - floor(in)) - 1; }; /// Applies a triangular wave function to the input, wavelength is 1 double tri_wave = [](double in) { return 2*std::abs(saw_wave(in)) - 1; }; /// Applies a rectangular wave function to the input, wavelength is 1 double rec_wave = [](double in) { in = (in < 0 ? 2 : 0), + fmod(in, 2); return in > 1 ? -1 : 1; }; } // namespace fc #endif /* SRC_CORE_CONNECTABLES_HPP_ */ <|endoftext|>
<commit_before>#ifndef _htl_core_log_hpp #define _htl_core_log_hpp /* #include <htl_core_log.hpp> */ #include <stdio.h> #include <errno.h> #include <string.h> #include <string> class DateTime { private: // %d-%02d-%02d %02d:%02d:%02d.%03d #define DATE_LEN 24 char time_data[DATE_LEN]; public: DateTime(); virtual ~DateTime(); public: virtual const char* FormatTime(); }; class LogContext { private: DateTime time; public: LogContext(); virtual ~LogContext(); public: virtual void SetId(int id) = 0; virtual int GetId(); public: virtual const char* FormatTime(); }; // user must implements the LogContext and define a global instance. extern LogContext* context; #if 1 #define Verbose(msg, ...) printf("[%s][%d][verbs] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf("\n") #define Info(msg, ...) printf("[%s][%d][infos] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf("\n") #define Trace(msg, ...) printf("[%s][%d][trace] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf("\n") #define Warn(msg, ...) printf("[%s][%d][warns] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf(" errno=%d(%s)", errno, strerror(errno));printf("\n") #define Error(msg, ...) printf("[%s][%d][error] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf(" errno=%d(%s)", errno, strerror(errno));printf("\n") #else #define Verbose(msg, ...) printf("[%s][%d][verbs][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf("\n") #define Info(msg, ...) printf("[%s][%d][infos][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf("\n") #define Trace(msg, ...) printf("[%s][%d][trace][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf("\n") #define Warn(msg, ...) printf("[%s][%d][warns][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf(" errno=%d(%s)", errno, strerror(errno));printf("\n") #define Error(msg, ...) printf("[%s][%d][error][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf(" errno=%d(%s)", errno, strerror(errno));printf("\n") #endif #if 1 #undef Verbose #define Verbose(msg, ...) (void)0 #endif #if 0 #undef Info #define Info(msg, ...) (void)0 #endif // for summary/report thread, print to stderr. #define LReport(msg, ...) fprintf(stderr, "[%s] ", context->FormatTime());fprintf(stderr, msg, ##__VA_ARGS__);fprintf(stderr, "\n") #endif<commit_msg>rtmp load tool, support interlaced chunk stream.<commit_after>#ifndef _htl_core_log_hpp #define _htl_core_log_hpp /* #include <htl_core_log.hpp> */ #include <stdio.h> #include <errno.h> #include <string.h> #include <string> class DateTime { private: // %d-%02d-%02d %02d:%02d:%02d.%03d #define DATE_LEN 24 char time_data[DATE_LEN]; public: DateTime(); virtual ~DateTime(); public: virtual const char* FormatTime(); }; class LogContext { private: DateTime time; public: LogContext(); virtual ~LogContext(); public: virtual void SetId(int id) = 0; virtual int GetId(); public: virtual const char* FormatTime(); }; // user must implements the LogContext and define a global instance. extern LogContext* context; #if 1 #define Verbose(msg, ...) printf("[%s][%d][verbs] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf("\n") #define Info(msg, ...) printf("[%s][%d][infos] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf("\n") #define Trace(msg, ...) printf("[%s][%d][trace] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf("\n") #define Warn(msg, ...) printf("[%s][%d][warns] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf(" errno=%d(%s)", errno, strerror(errno));printf("\n") #define Error(msg, ...) printf("[%s][%d][error] ", context->FormatTime(), context->GetId());printf(msg, ##__VA_ARGS__);printf(" errno=%d(%s)", errno, strerror(errno));printf("\n") #else #define Verbose(msg, ...) printf("[%s][%d][verbs][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf("\n") #define Info(msg, ...) printf("[%s][%d][infos][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf("\n") #define Trace(msg, ...) printf("[%s][%d][trace][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf("\n") #define Warn(msg, ...) printf("[%s][%d][warns][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf(" errno=%d(%s)", errno, strerror(errno));printf("\n") #define Error(msg, ...) printf("[%s][%d][error][%s] ", context->FormatTime(), context->GetId(), __FUNCTION__);printf(msg, ##__VA_ARGS__);printf(" errno=%d(%s)", errno, strerror(errno));printf("\n") #endif #if 1 #undef Verbose #define Verbose(msg, ...) (void)0 #endif #if 1 #undef Info #define Info(msg, ...) (void)0 #endif // for summary/report thread, print to stderr. #define LReport(msg, ...) fprintf(stderr, "[%s] ", context->FormatTime());fprintf(stderr, msg, ##__VA_ARGS__);fprintf(stderr, "\n") #endif<|endoftext|>
<commit_before><commit_msg>remove unused bIsOwner field in SfxHint<commit_after><|endoftext|>
<commit_before>/******************************************************************************* * include/wm_dd_pc.hpp * * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #ifndef WM_DOMAIN_DECOMPOSITION_PREFIX_COUNTING #define WM_DOMAIN_DECOMPOSITION_PREFIX_COUNTING #include <algorithm> #include <chrono> #include <cstring> #include <omp.h> #include <vector> #include "common.hpp" template <typename AlphabetType, typename SizeType> class wm_dd_pc { public: wm_dd_pc(const std::vector<AlphabetType>& text, const SizeType size, const SizeType levels) : _bv(levels), _zeros(levels, 0) { if(text.size() == 0) { return; } #pragma omp parallel { const size_t omp_rank = omp_get_thread_num(); const size_t omp_size = omp_get_num_threads(); const SizeType local_size = (size / omp_size) + ((omp_rank < size % omp_size) ? 1 : 0); const SizeType offset = (omp_rank * (size / omp_size)) + std::min<SizeType>(omp_rank, size % omp_size); SizeType cur_max_char = (1 << levels); std::vector<SizeType> bit_reverse = BitReverse<SizeType>(levels - 1); std::vector<SizeType> hist(cur_max_char, 0); std::vector<SizeType> borders(cur_max_char, 0); std::vector<uint64_t*> tmp_bv(levels); tmp_bv[0] = new uint64_t[((local_size + 63ULL) >> 6) * levels]; // memset is ok (all to 0) memset(tmp_bv[0], 0, (((local_size + 63ULL) >> 6) * sizeof(uint64_t)) * levels); for (SizeType level = 1; level < levels; ++level) { tmp_bv[level] = tmp_bv[level - 1] + ((local_size + 63ULL) >> 6); } // While initializing the histogram, we also compute the fist level SizeType cur_pos = 0; for (; cur_pos + 64 <= local_size; cur_pos += 64) { uint64_t word = 0ULL; for (SizeType i = offset; i < 64 + offset; ++i) { ++hist[text[cur_pos + i]]; word <<= 1; word |= ((text[cur_pos + i] >> (levels - 1)) & 1ULL); } tmp_bv[0][cur_pos >> 6] = word; } if (local_size & 63ULL) { uint64_t word = 0ULL; for (SizeType i = offset; i < local_size - cur_pos + offset; ++i) { ++hist[text[cur_pos + i]]; word <<= 1; word |= ((text[cur_pos + i] >> (levels - 1)) & 1ULL); } word <<= (64 - (local_size & 63ULL)); tmp_bv[0][local_size >> 6] = word; } // The number of 0s at the last level is the number of "even" characters for (SizeType i = 0; i < cur_max_char; i += 2) { _zeros[levels - 1] += hist[i]; } // Now we compute the WM bottom-up, i.e., the last level first for (SizeType level = levels - 1; level > 0; --level) { const SizeType prefix_shift = (levels - level); const SizeType cur_bit_shift = prefix_shift - 1; // Update the maximum value of a feasible a bit prefix and update the // histogram of the bit prefixes cur_max_char >>= 1; for (SizeType i = 0; i < cur_max_char; ++i) { hist[i] = hist[i << 1] + hist[(i << 1) + 1]; } // Compute the starting positions of characters with respect to their // bit prefixes and the bit-reversal permutation borders[0] = 0; for (SizeType i = 1; i < cur_max_char; ++i) { borders[bit_reverse[i]] = borders[bit_reverse[i - 1]] + hist[bit_reverse[i - 1]]; bit_reverse[i - 1] >>= 1; } // The number of 0s is the position of the first 1 in the previous level _zeros[level - 1] = borders[1]; // Now we insert the bits with respect to their bit prefixes for (SizeType i = offset; i < local_size + offset; ++i) { const SizeType pos = borders[text[i] >> prefix_shift]++; tmp_bv[level][pos >> 6] |= (((text[i] >> cur_bit_shift) & 1ULL) << (63ULL - (pos & 63ULL))); } } } } auto get_bv_and_zeros() const { return std::make_pair(_bv, _zeros); } private: std::vector<uint64_t*> _bv; std::vector<SizeType> _zeros; }; // class wm_dd_pc #endif // WM_DOMAIN_DECOMPOSITION_PREFIX_COUNTING /******************************************************************************/ <commit_msg>delet old dd variant<commit_after><|endoftext|>
<commit_before>/* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2016, Daemon Developers 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 Daemon developers 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 DAEMON DEVELOPERS 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 "Common.h" #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #include <fcntl.h> #include <signal.h> #ifdef __linux__ #include <linux/version.h> #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,17,0) #include <sys/syscall.h> #include <linux/random.h> #define HAS_GETRANDOM_SYSCALL 1 #endif #endif #ifdef __native_client__ #include <nacl/nacl_exception.h> #include <nacl/nacl_minidump.h> #include <nacl/nacl_random.h> #else #include <dlfcn.h> #endif #endif #ifdef BUILD_VM #include "shared/CommonProxies.h" #else #include "qcommon/sys.h" #endif namespace Sys { #ifdef _WIN32 SteadyClock::time_point SteadyClock::now() NOEXCEPT { // Determine performance counter frequency static double nanosec_per_tic = 0.0; if (nanosec_per_tic == 0.0) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); nanosec_per_tic = 1000000000.0 / freq.QuadPart; } LARGE_INTEGER time; QueryPerformanceCounter(&time); return time_point(duration(rep(nanosec_per_tic * time.QuadPart))); } #endif void SleepFor(SteadyClock::duration time) { #ifdef _WIN32 static ULONG maxRes = 0; static NTSTATUS(WINAPI *pNtSetTimerResolution) (ULONG resolution, BOOLEAN set_resolution, ULONG* current_resolution); static NTSTATUS(WINAPI *pNtDelayExecution) (BOOLEAN alertable, const LARGE_INTEGER* timeout); if (maxRes == 0) { // Load ntdll.dll functions std::string errorString; DynamicLib ntdll = DynamicLib::Open("ntdll.dll", errorString); if (!ntdll) Sys::Error("Failed to load ntdll.dll: %s", errorString); auto pNtQueryTimerResolution = ntdll.LoadSym<NTSTATUS WINAPI(ULONG*, ULONG*, ULONG*)>("NtQueryTimerResolution", errorString); if (!pNtQueryTimerResolution) Sys::Error("Failed to load NtQueryTimerResolution from ntdll.dll: %s", errorString); pNtSetTimerResolution = ntdll.LoadSym<NTSTATUS WINAPI(ULONG, BOOLEAN, ULONG*)>("NtSetTimerResolution", errorString); if (!pNtSetTimerResolution) Sys::Error("Failed to load NtSetTimerResolution from ntdll.dll: %s", errorString); pNtDelayExecution = ntdll.LoadSym<NTSTATUS WINAPI(BOOLEAN, const LARGE_INTEGER*)>("NtDelayExecution", errorString); if (!pNtDelayExecution) Sys::Error("Failed to load NtDelayExecution from ntdll.dll: %s", errorString); // Determine the maximum available timer resolution ULONG minRes, curRes; if (pNtQueryTimerResolution(&minRes, &maxRes, &curRes) != 0) maxRes = 10000; // Default to 1ms } // Increase the system timer resolution for the duration of the sleep ULONG curRes; pNtSetTimerResolution(maxRes, TRUE, &curRes); // Convert to NT units of 100ns using NTDuration = std::chrono::duration<int64_t, std::ratio<1, 10000000>>; auto ntTime = std::chrono::duration_cast<NTDuration>(time); // Store the delay as a negative number to indicate a relative sleep LARGE_INTEGER duration; duration.QuadPart = -ntTime.count(); pNtDelayExecution(FALSE, &duration); // Restore timer resolution after sleeping pNtSetTimerResolution(maxRes, FALSE, &curRes); #else std::this_thread::sleep_for(time); #endif } SteadyClock::time_point SleepUntil(SteadyClock::time_point time) { // Early exit if we are already past the deadline auto now = SteadyClock::now(); if (now >= time) { // We were already past our deadline, which means that the previous frame // ran for too long. Use the current time as the base for the next frame. return now; } // Perform the actual sleep SleepFor(time - now); // We may have overslept, so use the target time rather than the // current time as the base for the next frame. That way we ensure // that the frame rate remains consistent. return time; } int Milliseconds() { #ifdef BUILD_VM return trap_Milliseconds(); #else static Sys::SteadyClock::time_point baseTime = Sys::SteadyClock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(Sys::SteadyClock::now() - baseTime).count(); #endif } void Drop(Str::StringRef message) { // Transform into a fatal error if too many errors are generated in quick // succession. static Sys::SteadyClock::time_point lastError; Sys::SteadyClock::time_point now = Sys::SteadyClock::now(); static int errorCount = 0; if (now - lastError < std::chrono::milliseconds(100)) { if (++errorCount > 3) Sys::Error(message); } else errorCount = 0; lastError = now; throw DropErr(true, message); } #ifdef _WIN32 std::string Win32StrError(uint32_t error) { std::string out; char* message; if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, nullptr)) { out = message; // FormatMessage adds ".\r\n" to messages, but we don't want those if (out.back() == '\n') out.pop_back(); if (out.back() == '\r') out.pop_back(); if (out.back() == '.') out.pop_back(); LocalFree(message); } else out = Str::Format("Unknown error 0x%08lx", error); return out; } #endif // Setup crash handling #ifdef _WIN32 static const char *WindowsExceptionString(DWORD code) { switch (code) { case EXCEPTION_ACCESS_VIOLATION: return "Access violation"; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "Array bounds exceeded"; case EXCEPTION_BREAKPOINT: return "Breakpoint was encountered"; case EXCEPTION_DATATYPE_MISALIGNMENT: return "Datatype misalignment"; case EXCEPTION_FLT_DENORMAL_OPERAND: return "Float: Denormal operand"; case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "Float: Divide by zero"; case EXCEPTION_FLT_INEXACT_RESULT: return "Float: Inexact result"; case EXCEPTION_FLT_INVALID_OPERATION: return "Float: Invalid operation"; case EXCEPTION_FLT_OVERFLOW: return "Float: Overflow"; case EXCEPTION_FLT_STACK_CHECK: return "Float: Stack check"; case EXCEPTION_FLT_UNDERFLOW: return "Float: Underflow"; case EXCEPTION_ILLEGAL_INSTRUCTION: return "Illegal instruction"; case EXCEPTION_IN_PAGE_ERROR: return "Page error"; case EXCEPTION_INT_DIVIDE_BY_ZERO: return "Integer: Divide by zero"; case EXCEPTION_INT_OVERFLOW: return "Integer: Overflow"; case EXCEPTION_INVALID_DISPOSITION: return "Invalid disposition"; case EXCEPTION_NONCONTINUABLE_EXCEPTION: return "Noncontinuable exception"; case EXCEPTION_PRIV_INSTRUCTION: return "Privileged instruction"; case EXCEPTION_SINGLE_STEP: return "Single step"; case EXCEPTION_STACK_OVERFLOW: return "Stack overflow"; default: return "Unknown exception"; } } ALIGN_STACK_FOR_MINGW static LONG WINAPI CrashHandler(PEXCEPTION_POINTERS ExceptionInfo) { // Reset handler so that any future errors cause a crash SetUnhandledExceptionFilter(nullptr); // TODO: backtrace Sys::Error("Crashed with exception 0x%lx: %s", ExceptionInfo->ExceptionRecord->ExceptionCode, WindowsExceptionString(ExceptionInfo->ExceptionRecord->ExceptionCode)); return EXCEPTION_CONTINUE_EXECUTION; } void SetupCrashHandler() { SetUnhandledExceptionFilter(CrashHandler); } #elif defined(__native_client__) static void CrashHandler(const void* data, size_t n) { VM::CrashDump(static_cast<const uint8_t*>(data), n); Sys::Error("Crashed with NaCl exception"); } void SetupCrashHandler() { nacl_minidump_register_crash_handler(); nacl_minidump_set_callback(CrashHandler); } #else static void CrashHandler(int sig) { // TODO: backtrace Sys::Error("Crashed with signal %d: %s", sig, strsignal(sig)); } void SetupCrashHandler() { struct sigaction sa; sa.sa_flags = SA_RESETHAND | SA_NODEFER; sa.sa_handler = CrashHandler; sigemptyset(&sa.sa_mask); for (int sig: {SIGILL, SIGFPE, SIGSEGV, SIGABRT, SIGBUS, SIGTRAP}) sigaction(sig, &sa, nullptr); } #endif #ifndef __native_client__ void DynamicLib::Close() { if (!handle) return; #ifdef _WIN32 FreeLibrary(static_cast<HMODULE>(handle)); #else dlclose(handle); #endif handle = nullptr; } DynamicLib DynamicLib::Open(Str::StringRef filename, std::string& errorString) { #ifdef _WIN32 void* handle = LoadLibraryW(Str::UTF8To16(filename).c_str()); if (!handle) errorString = Win32StrError(GetLastError()); #else // Handle relative paths correctly const char* dlopenFilename = filename.c_str(); std::string relativePath; if (filename.find('/') == std::string::npos) { relativePath = "./" + filename; dlopenFilename = relativePath.c_str(); } void* handle = dlopen(dlopenFilename, RTLD_NOW); if (!handle) errorString = dlerror(); #endif DynamicLib out; out.handle = handle; return out; } intptr_t DynamicLib::InternalLoadSym(Str::StringRef sym, std::string& errorString) { #ifdef _WIN32 intptr_t p = reinterpret_cast<intptr_t>(GetProcAddress(static_cast<HMODULE>(handle), sym.c_str())); if (!p) errorString = Win32StrError(GetLastError()); return p; #else intptr_t p = reinterpret_cast<intptr_t>(dlsym(handle, sym.c_str())); if (!p) errorString = dlerror(); return p; #endif } #endif // __native_client__ bool processTerminating = false; void OSExit(int exitCode) { processTerminating = true; exit(exitCode); } bool IsProcessTerminating() { return processTerminating; } void GenRandomBytes(void* dest, size_t size) { #ifdef _WIN32 HCRYPTPROV prov; if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) Sys::Error("CryptAcquireContext failed: %s", Win32StrError(GetLastError())); if (!CryptGenRandom(prov, size, (BYTE*)dest)) Sys::Error("CryptGenRandom failed: %s", Win32StrError(GetLastError())); CryptReleaseContext(prov, 0); #elif defined(__native_client__) size_t bytes_written; if (nacl_secure_random(dest, size, &bytes_written) != 0 || bytes_written != size) Sys::Error("nacl_secure_random failed"); #elif defined(__linux__) && defined(HAS_GETRANDOM_SYSCALL) if (syscall(SYS_getrandom, dest, size, GRND_NONBLOCK) == -1) Sys::Error("Failed getrandom syscall: %s", strerror(errno)); #elif defined(__linux__) int fd = open("/dev/urandom", O_RDONLY); if (fd == -1) Sys::Error("Failed to open /dev/urandom: %s", strerror(errno)); if (read(fd, dest, size) != (ssize_t) size) Sys::Error("Failed to read from /dev/urandom: %s", strerror(errno)); close(fd); #else arc4random_buf(dest, size); #endif } } // namespace Sys // Global operator new/delete override to not throw an exception when out of // memory. Instead, it is preferable to simply crash with an error. void* operator new(size_t n) { void* p = malloc(n); if (!p) Sys::Error("Out of memory"); return p; } void operator delete(void* p) NOEXCEPT { if (!Sys::processTerminating) { free(p); } } /** * Both client and server can use this, and it will * do the appropriate things. */ void PRINTF_LIKE(2) Com_Error(errorParm_t code, const char *fmt, ...) { char buf[4096]; va_list argptr; va_start(argptr, fmt); Q_vsnprintf(buf, sizeof(buf), fmt, argptr); va_end(argptr); if (code == errorParm_t::ERR_FATAL) Sys::Error(buf); else Sys::Drop(buf); } <commit_msg>Drop Com_Error<commit_after>/* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2016, Daemon Developers 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 Daemon developers 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 DAEMON DEVELOPERS 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 "Common.h" #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #include <fcntl.h> #include <signal.h> #ifdef __linux__ #include <linux/version.h> #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,17,0) #include <sys/syscall.h> #include <linux/random.h> #define HAS_GETRANDOM_SYSCALL 1 #endif #endif #ifdef __native_client__ #include <nacl/nacl_exception.h> #include <nacl/nacl_minidump.h> #include <nacl/nacl_random.h> #else #include <dlfcn.h> #endif #endif #ifdef BUILD_VM #include "shared/CommonProxies.h" #else #include "qcommon/sys.h" #endif namespace Sys { #ifdef _WIN32 SteadyClock::time_point SteadyClock::now() NOEXCEPT { // Determine performance counter frequency static double nanosec_per_tic = 0.0; if (nanosec_per_tic == 0.0) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); nanosec_per_tic = 1000000000.0 / freq.QuadPart; } LARGE_INTEGER time; QueryPerformanceCounter(&time); return time_point(duration(rep(nanosec_per_tic * time.QuadPart))); } #endif void SleepFor(SteadyClock::duration time) { #ifdef _WIN32 static ULONG maxRes = 0; static NTSTATUS(WINAPI *pNtSetTimerResolution) (ULONG resolution, BOOLEAN set_resolution, ULONG* current_resolution); static NTSTATUS(WINAPI *pNtDelayExecution) (BOOLEAN alertable, const LARGE_INTEGER* timeout); if (maxRes == 0) { // Load ntdll.dll functions std::string errorString; DynamicLib ntdll = DynamicLib::Open("ntdll.dll", errorString); if (!ntdll) Sys::Error("Failed to load ntdll.dll: %s", errorString); auto pNtQueryTimerResolution = ntdll.LoadSym<NTSTATUS WINAPI(ULONG*, ULONG*, ULONG*)>("NtQueryTimerResolution", errorString); if (!pNtQueryTimerResolution) Sys::Error("Failed to load NtQueryTimerResolution from ntdll.dll: %s", errorString); pNtSetTimerResolution = ntdll.LoadSym<NTSTATUS WINAPI(ULONG, BOOLEAN, ULONG*)>("NtSetTimerResolution", errorString); if (!pNtSetTimerResolution) Sys::Error("Failed to load NtSetTimerResolution from ntdll.dll: %s", errorString); pNtDelayExecution = ntdll.LoadSym<NTSTATUS WINAPI(BOOLEAN, const LARGE_INTEGER*)>("NtDelayExecution", errorString); if (!pNtDelayExecution) Sys::Error("Failed to load NtDelayExecution from ntdll.dll: %s", errorString); // Determine the maximum available timer resolution ULONG minRes, curRes; if (pNtQueryTimerResolution(&minRes, &maxRes, &curRes) != 0) maxRes = 10000; // Default to 1ms } // Increase the system timer resolution for the duration of the sleep ULONG curRes; pNtSetTimerResolution(maxRes, TRUE, &curRes); // Convert to NT units of 100ns using NTDuration = std::chrono::duration<int64_t, std::ratio<1, 10000000>>; auto ntTime = std::chrono::duration_cast<NTDuration>(time); // Store the delay as a negative number to indicate a relative sleep LARGE_INTEGER duration; duration.QuadPart = -ntTime.count(); pNtDelayExecution(FALSE, &duration); // Restore timer resolution after sleeping pNtSetTimerResolution(maxRes, FALSE, &curRes); #else std::this_thread::sleep_for(time); #endif } SteadyClock::time_point SleepUntil(SteadyClock::time_point time) { // Early exit if we are already past the deadline auto now = SteadyClock::now(); if (now >= time) { // We were already past our deadline, which means that the previous frame // ran for too long. Use the current time as the base for the next frame. return now; } // Perform the actual sleep SleepFor(time - now); // We may have overslept, so use the target time rather than the // current time as the base for the next frame. That way we ensure // that the frame rate remains consistent. return time; } int Milliseconds() { #ifdef BUILD_VM return trap_Milliseconds(); #else static Sys::SteadyClock::time_point baseTime = Sys::SteadyClock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(Sys::SteadyClock::now() - baseTime).count(); #endif } void Drop(Str::StringRef message) { // Transform into a fatal error if too many errors are generated in quick // succession. static Sys::SteadyClock::time_point lastError; Sys::SteadyClock::time_point now = Sys::SteadyClock::now(); static int errorCount = 0; if (now - lastError < std::chrono::milliseconds(100)) { if (++errorCount > 3) Sys::Error(message); } else errorCount = 0; lastError = now; throw DropErr(true, message); } #ifdef _WIN32 std::string Win32StrError(uint32_t error) { std::string out; char* message; if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, nullptr)) { out = message; // FormatMessage adds ".\r\n" to messages, but we don't want those if (out.back() == '\n') out.pop_back(); if (out.back() == '\r') out.pop_back(); if (out.back() == '.') out.pop_back(); LocalFree(message); } else out = Str::Format("Unknown error 0x%08lx", error); return out; } #endif // Setup crash handling #ifdef _WIN32 static const char *WindowsExceptionString(DWORD code) { switch (code) { case EXCEPTION_ACCESS_VIOLATION: return "Access violation"; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "Array bounds exceeded"; case EXCEPTION_BREAKPOINT: return "Breakpoint was encountered"; case EXCEPTION_DATATYPE_MISALIGNMENT: return "Datatype misalignment"; case EXCEPTION_FLT_DENORMAL_OPERAND: return "Float: Denormal operand"; case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "Float: Divide by zero"; case EXCEPTION_FLT_INEXACT_RESULT: return "Float: Inexact result"; case EXCEPTION_FLT_INVALID_OPERATION: return "Float: Invalid operation"; case EXCEPTION_FLT_OVERFLOW: return "Float: Overflow"; case EXCEPTION_FLT_STACK_CHECK: return "Float: Stack check"; case EXCEPTION_FLT_UNDERFLOW: return "Float: Underflow"; case EXCEPTION_ILLEGAL_INSTRUCTION: return "Illegal instruction"; case EXCEPTION_IN_PAGE_ERROR: return "Page error"; case EXCEPTION_INT_DIVIDE_BY_ZERO: return "Integer: Divide by zero"; case EXCEPTION_INT_OVERFLOW: return "Integer: Overflow"; case EXCEPTION_INVALID_DISPOSITION: return "Invalid disposition"; case EXCEPTION_NONCONTINUABLE_EXCEPTION: return "Noncontinuable exception"; case EXCEPTION_PRIV_INSTRUCTION: return "Privileged instruction"; case EXCEPTION_SINGLE_STEP: return "Single step"; case EXCEPTION_STACK_OVERFLOW: return "Stack overflow"; default: return "Unknown exception"; } } ALIGN_STACK_FOR_MINGW static LONG WINAPI CrashHandler(PEXCEPTION_POINTERS ExceptionInfo) { // Reset handler so that any future errors cause a crash SetUnhandledExceptionFilter(nullptr); // TODO: backtrace Sys::Error("Crashed with exception 0x%lx: %s", ExceptionInfo->ExceptionRecord->ExceptionCode, WindowsExceptionString(ExceptionInfo->ExceptionRecord->ExceptionCode)); return EXCEPTION_CONTINUE_EXECUTION; } void SetupCrashHandler() { SetUnhandledExceptionFilter(CrashHandler); } #elif defined(__native_client__) static void CrashHandler(const void* data, size_t n) { VM::CrashDump(static_cast<const uint8_t*>(data), n); Sys::Error("Crashed with NaCl exception"); } void SetupCrashHandler() { nacl_minidump_register_crash_handler(); nacl_minidump_set_callback(CrashHandler); } #else static void CrashHandler(int sig) { // TODO: backtrace Sys::Error("Crashed with signal %d: %s", sig, strsignal(sig)); } void SetupCrashHandler() { struct sigaction sa; sa.sa_flags = SA_RESETHAND | SA_NODEFER; sa.sa_handler = CrashHandler; sigemptyset(&sa.sa_mask); for (int sig: {SIGILL, SIGFPE, SIGSEGV, SIGABRT, SIGBUS, SIGTRAP}) sigaction(sig, &sa, nullptr); } #endif #ifndef __native_client__ void DynamicLib::Close() { if (!handle) return; #ifdef _WIN32 FreeLibrary(static_cast<HMODULE>(handle)); #else dlclose(handle); #endif handle = nullptr; } DynamicLib DynamicLib::Open(Str::StringRef filename, std::string& errorString) { #ifdef _WIN32 void* handle = LoadLibraryW(Str::UTF8To16(filename).c_str()); if (!handle) errorString = Win32StrError(GetLastError()); #else // Handle relative paths correctly const char* dlopenFilename = filename.c_str(); std::string relativePath; if (filename.find('/') == std::string::npos) { relativePath = "./" + filename; dlopenFilename = relativePath.c_str(); } void* handle = dlopen(dlopenFilename, RTLD_NOW); if (!handle) errorString = dlerror(); #endif DynamicLib out; out.handle = handle; return out; } intptr_t DynamicLib::InternalLoadSym(Str::StringRef sym, std::string& errorString) { #ifdef _WIN32 intptr_t p = reinterpret_cast<intptr_t>(GetProcAddress(static_cast<HMODULE>(handle), sym.c_str())); if (!p) errorString = Win32StrError(GetLastError()); return p; #else intptr_t p = reinterpret_cast<intptr_t>(dlsym(handle, sym.c_str())); if (!p) errorString = dlerror(); return p; #endif } #endif // __native_client__ bool processTerminating = false; void OSExit(int exitCode) { processTerminating = true; exit(exitCode); } bool IsProcessTerminating() { return processTerminating; } void GenRandomBytes(void* dest, size_t size) { #ifdef _WIN32 HCRYPTPROV prov; if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) Sys::Error("CryptAcquireContext failed: %s", Win32StrError(GetLastError())); if (!CryptGenRandom(prov, size, (BYTE*)dest)) Sys::Error("CryptGenRandom failed: %s", Win32StrError(GetLastError())); CryptReleaseContext(prov, 0); #elif defined(__native_client__) size_t bytes_written; if (nacl_secure_random(dest, size, &bytes_written) != 0 || bytes_written != size) Sys::Error("nacl_secure_random failed"); #elif defined(__linux__) && defined(HAS_GETRANDOM_SYSCALL) if (syscall(SYS_getrandom, dest, size, GRND_NONBLOCK) == -1) Sys::Error("Failed getrandom syscall: %s", strerror(errno)); #elif defined(__linux__) int fd = open("/dev/urandom", O_RDONLY); if (fd == -1) Sys::Error("Failed to open /dev/urandom: %s", strerror(errno)); if (read(fd, dest, size) != (ssize_t) size) Sys::Error("Failed to read from /dev/urandom: %s", strerror(errno)); close(fd); #else arc4random_buf(dest, size); #endif } } // namespace Sys // Global operator new/delete override to not throw an exception when out of // memory. Instead, it is preferable to simply crash with an error. void* operator new(size_t n) { void* p = malloc(n); if (!p) Sys::Error("Out of memory"); return p; } void operator delete(void* p) NOEXCEPT { if (!Sys::processTerminating) { free(p); } } <|endoftext|>
<commit_before>/* * FileMode.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef CORE_SYSTEM_FILE_MODE_HPP #define CORE_SYSTEM_FILE_MODE_HPP #ifdef _WIN32 #error FileMode.hpp is is not supported on Windows #endif #include <sys/stat.h> #include <core/Error.hpp> #include <core/FilePath.hpp> namespace core { namespace system { enum FileMode { UserReadWriteMode, UserReadWriteGroupReadMode, EveryoneReadMode, EveryoneReadWriteMode, EveryoneReadWriteExecuteMode }; inline Error changeFileMode(const FilePath& filePath, FileMode fileMode, bool stickyBit) { mode_t mode ; switch(fileMode) { case UserReadWriteMode: mode = S_IRUSR | S_IWUSR; break; case UserReadWriteGroupReadMode: mode = S_IRUSR | S_IWUSR | S_IRGRP ; break; case EveryoneReadMode: mode = S_IRUSR | S_IRGRP | S_IROTH; break; case EveryoneReadWriteMode: mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; break; case EveryoneReadWriteExecuteMode: mode = S_IRWXU | S_IRWXG | S_IRWXO; break; default: return systemError(ENOTSUP, ERROR_LOCATION); } // check for sticky bit if (stickyBit) mode |= S_ISVTX; // change the mode errno = 0; if (::chmod(filePath.absolutePath().c_str(), mode) < 0) { Error error = systemError(errno, ERROR_LOCATION); error.addProperty("path", filePath); return error; } else return Success(); } inline Error changeFileMode(const FilePath& filePath, FileMode fileMode) { return changeFileMode(filePath, fileMode, false); } } // namespace system } // namespace core #endif // CORE_SYSTEM_FILE_MODE_HPP <commit_msg>add user read/write/execute to file mode enumeration<commit_after>/* * FileMode.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef CORE_SYSTEM_FILE_MODE_HPP #define CORE_SYSTEM_FILE_MODE_HPP #ifdef _WIN32 #error FileMode.hpp is is not supported on Windows #endif #include <sys/stat.h> #include <core/Error.hpp> #include <core/FilePath.hpp> namespace core { namespace system { enum FileMode { UserReadWriteMode, UserReadWriteExecuteMode, UserReadWriteGroupReadMode, EveryoneReadMode, EveryoneReadWriteMode, EveryoneReadWriteExecuteMode }; inline Error changeFileMode(const FilePath& filePath, FileMode fileMode, bool stickyBit) { mode_t mode ; switch(fileMode) { case UserReadWriteMode: mode = S_IRUSR | S_IWUSR; break; case UserReadWriteExecuteMode: mode = S_IRUSR | S_IWUSR | S_IXUSR; break; case UserReadWriteGroupReadMode: mode = S_IRUSR | S_IWUSR | S_IRGRP ; break; case EveryoneReadMode: mode = S_IRUSR | S_IRGRP | S_IROTH; break; case EveryoneReadWriteMode: mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; break; case EveryoneReadWriteExecuteMode: mode = S_IRWXU | S_IRWXG | S_IRWXO; break; default: return systemError(ENOTSUP, ERROR_LOCATION); } // check for sticky bit if (stickyBit) mode |= S_ISVTX; // change the mode errno = 0; if (::chmod(filePath.absolutePath().c_str(), mode) < 0) { Error error = systemError(errno, ERROR_LOCATION); error.addProperty("path", filePath); return error; } else return Success(); } inline Error changeFileMode(const FilePath& filePath, FileMode fileMode) { return changeFileMode(filePath, fileMode, false); } } // namespace system } // namespace core #endif // CORE_SYSTEM_FILE_MODE_HPP <|endoftext|>
<commit_before>/* * MLPLM.cpp * * Created on: 20.11.2013 * Author: cls */ #include "PLM.h" #include <omp.h> #include "../coarsening/PartitionCoarsening.h" #include "../coarsening/ClusterContractor.h" #include "../coarsening/ClusteringProjector.h" #include "../auxiliary/Log.h" #include <sstream> namespace NetworKit { PLM::PLM(bool refine, double gamma, std::string par, count maxIter) : parallelism(par), refine(refine), gamma(gamma), maxIter(maxIter) { } Partition PLM::run(Graph& G) { DEBUG("calling run method on " , G.toString()); count z = G.upperNodeIdBound(); std::vector<bool> activeNodes(z); // record if node must be processed activeNodes.assign(z, true); // init communities to singletons Partition zeta(z); G.forNodes([&](node v) { zeta.toSingleton(v); }); index o = zeta.upperBound(); // init graph-dependent temporaries std::vector<double> volNode(z, 0.0); // $\omega(E)$ edgeweight total = G.totalEdgeWeight(); DEBUG("total edge weight: " , total); edgeweight divisor = (2 * total * total); // needed in modularity calculation G.parallelForNodes([&](node u) { // calculate and store volume of each node volNode[u] += G.weightedDegree(u); volNode[u] += G.weight(u, u); // consider self-loop twice TRACE("init volNode[" , u , "] to " , volNode[u]); }); // init community-dependent temporaries std::vector<double> volCommunity(o, 0.0); zeta.parallelForEntries([&](node u, index C) { // set volume for all communities volCommunity[C] = volNode[u]; }); // first move phase bool moved = false; // indicates whether any node has been moved in the last pass bool change = false; // indicates whether the communities have changed at all /* * try to improve modularity by moving a node to neighboring clusters */ auto tryMove = [&](node u) { TRACE("trying to move node " , u); // collect edge weight to neighbor clusters std::map<index, edgeweight> affinity; G.forWeightedNeighborsOf(u, [&](node v, edgeweight weight) { if (u != v) { index C = zeta[v]; affinity[C] += weight; } }); // sub-functions // $\vol(C \ {x})$ - volume of cluster C excluding node x auto volCommunityMinusNode = [&](index C, node x) { double volC = 0.0; double volN = 0.0; volC = volCommunity[C]; if (zeta[x] == C) { volN = volNode[x]; return volC - volN; } else { return volC; } }; auto modGain = [&](node u, index C, index D) { double volN = 0.0; volN = volNode[u]; double delta = (affinity[D] - affinity[C]) / total + this->gamma * ((volCommunityMinusNode(C, u) - volCommunityMinusNode(D, u)) * volN) / divisor; TRACE("(" , affinity[D] , " - " , affinity[C] , ") / " , total , " + " , this->gamma , " * ((" , volCommunityMinusNode(C, u) , " - " , volCommunityMinusNode(D, u) , ") *" , volN , ") / 2 * " , (total * total)); return delta; }; index best = none; index C = none; index D = none; double deltaBest = -1; C = zeta[u]; TRACE("Processing neighborhood of node " , u , ", which is in cluster " , C); G.forNeighborsOf(u, [&](node v) { D = zeta[v]; if (D != C) { // consider only nodes in other clusters (and implicitly only nodes other than u) double delta = modGain(u, C, D); TRACE("mod gain: " , delta); if (delta > deltaBest) { deltaBest = delta; best = D; } } }); TRACE("deltaBest=" , deltaBest); if (deltaBest > 0) { // if modularity improvement possible assert (best != C && best != none);// do not "move" to original cluster zeta[u] = best; // move to best cluster TRACE("node " , u , " moved"); // mod update double volN = 0.0; volN = volNode[u]; // update the volume of the two clusters #pragma omp atomic update volCommunity[C] -= volN; #pragma omp atomic update volCommunity[best] += volN; moved = true; // change to clustering has been made } else { TRACE("node " , u , " not moved"); } }; // performs node moves auto movePhase = [&](){ count iter = 0; do { moved = false; // apply node movement according to parallelization strategy if (this->parallelism == "none") { G.forNodes(tryMove); } else if (this->parallelism == "simple") { G.parallelForNodes(tryMove); } else if (this->parallelism == "balanced") { G.balancedParallelForNodes(tryMove); } else { ERROR("unknown parallelization strategy: " , this->parallelism); throw std::runtime_error("unknown parallelization strategy"); } if (moved) change = true; if (iter == maxIter) { WARN("move phase aborted after ", maxIter, " iterations"); } iter += 1; } while (moved && (iter <= maxIter)); DEBUG("iterations in move phase: ", iter); }; // first move phase movePhase(); if (change) { DEBUG("nodes moved, so begin coarsening and recursive call"); std::pair<Graph, std::vector<node>> coarsened = coarsen(G, zeta); // coarsen graph according to communitites Partition zetaCoarse = run(coarsened.first); zeta = prolong(coarsened.first, zetaCoarse, G, coarsened.second); // unpack communities in coarse graph onto fine graph // refinement phase if (refine) { DEBUG("refinement phase"); // reinit community-dependent temporaries o = zeta.upperBound(); volCommunity.clear(); volCommunity.resize(o, 0.0); zeta.parallelForEntries([&](node u, index C) { // set volume for all communities edgeweight volN = volNode[u]; #pragma omp atomic update volCommunity[C] += volN; }); // second move phase movePhase(); } } return zeta; } std::string NetworKit::PLM::toString() const { std::string refined; if (refine) { refined = "refinement"; } else { refined = ""; } std::stringstream stream; stream << "PLM(" << parallelism << "," << refined << ")"; return stream.str(); } std::pair<Graph, std::vector<node> > PLM::coarsen(const Graph& G, const Partition& zeta) { bool parallelCoarsening = false; // switch between parallel and sequential coarsening if (parallelCoarsening) { PartitionCoarsening parCoarsening; return parCoarsening.run(G, zeta); } else { ClusterContractor seqCoarsening; return seqCoarsening.run(G, zeta); } } Partition PLM::prolong(const Graph& Gcoarse, const Partition& zetaCoarse, const Graph& Gfine, std::vector<node> nodeToMetaNode) { Partition zetaFine(Gfine.upperNodeIdBound()); zetaFine.setUpperBound(zetaCoarse.upperBound()); Gfine.forNodes([&](node v) { node mv = nodeToMetaNode[v]; index cv = zetaCoarse[mv]; zetaFine[v] = cv; }); return zetaFine; } } /* namespace NetworKit */ <commit_msg>commented TRACE<commit_after>/* * MLPLM.cpp * * Created on: 20.11.2013 * Author: cls */ #include "PLM.h" #include <omp.h> #include "../coarsening/PartitionCoarsening.h" #include "../coarsening/ClusterContractor.h" #include "../coarsening/ClusteringProjector.h" #include "../auxiliary/Log.h" #include <sstream> namespace NetworKit { PLM::PLM(bool refine, double gamma, std::string par, count maxIter) : parallelism(par), refine(refine), gamma(gamma), maxIter(maxIter) { } Partition PLM::run(Graph& G) { DEBUG("calling run method on " , G.toString()); count z = G.upperNodeIdBound(); std::vector<bool> activeNodes(z); // record if node must be processed activeNodes.assign(z, true); // init communities to singletons Partition zeta(z); G.forNodes([&](node v) { zeta.toSingleton(v); }); index o = zeta.upperBound(); // init graph-dependent temporaries std::vector<double> volNode(z, 0.0); // $\omega(E)$ edgeweight total = G.totalEdgeWeight(); DEBUG("total edge weight: " , total); edgeweight divisor = (2 * total * total); // needed in modularity calculation G.parallelForNodes([&](node u) { // calculate and store volume of each node volNode[u] += G.weightedDegree(u); volNode[u] += G.weight(u, u); // consider self-loop twice // TRACE("init volNode[" , u , "] to " , volNode[u]); }); // init community-dependent temporaries std::vector<double> volCommunity(o, 0.0); zeta.parallelForEntries([&](node u, index C) { // set volume for all communities volCommunity[C] = volNode[u]; }); // first move phase bool moved = false; // indicates whether any node has been moved in the last pass bool change = false; // indicates whether the communities have changed at all /* * try to improve modularity by moving a node to neighboring clusters */ auto tryMove = [&](node u) { // TRACE("trying to move node " , u); // collect edge weight to neighbor clusters std::map<index, edgeweight> affinity; G.forWeightedNeighborsOf(u, [&](node v, edgeweight weight) { if (u != v) { index C = zeta[v]; affinity[C] += weight; } }); // sub-functions // $\vol(C \ {x})$ - volume of cluster C excluding node x auto volCommunityMinusNode = [&](index C, node x) { double volC = 0.0; double volN = 0.0; volC = volCommunity[C]; if (zeta[x] == C) { volN = volNode[x]; return volC - volN; } else { return volC; } }; auto modGain = [&](node u, index C, index D) { double volN = 0.0; volN = volNode[u]; double delta = (affinity[D] - affinity[C]) / total + this->gamma * ((volCommunityMinusNode(C, u) - volCommunityMinusNode(D, u)) * volN) / divisor; // TRACE("(" , affinity[D] , " - " , affinity[C] , ") / " , total , " + " , this->gamma , " * ((" , volCommunityMinusNode(C, u) , " - " , volCommunityMinusNode(D, u) , ") *" , volN , ") / 2 * " , (total * total)); return delta; }; index best = none; index C = none; index D = none; double deltaBest = -1; C = zeta[u]; // TRACE("Processing neighborhood of node " , u , ", which is in cluster " , C); G.forNeighborsOf(u, [&](node v) { D = zeta[v]; if (D != C) { // consider only nodes in other clusters (and implicitly only nodes other than u) double delta = modGain(u, C, D); TRACE("mod gain: " , delta); if (delta > deltaBest) { deltaBest = delta; best = D; } } }); // TRACE("deltaBest=" , deltaBest); if (deltaBest > 0) { // if modularity improvement possible assert (best != C && best != none);// do not "move" to original cluster zeta[u] = best; // move to best cluster // TRACE("node " , u , " moved"); // mod update double volN = 0.0; volN = volNode[u]; // update the volume of the two clusters #pragma omp atomic update volCommunity[C] -= volN; #pragma omp atomic update volCommunity[best] += volN; moved = true; // change to clustering has been made } else { // TRACE("node " , u , " not moved"); } }; // performs node moves auto movePhase = [&](){ count iter = 0; do { moved = false; // apply node movement according to parallelization strategy if (this->parallelism == "none") { G.forNodes(tryMove); } else if (this->parallelism == "simple") { G.parallelForNodes(tryMove); } else if (this->parallelism == "balanced") { G.balancedParallelForNodes(tryMove); } else { ERROR("unknown parallelization strategy: " , this->parallelism); throw std::runtime_error("unknown parallelization strategy"); } if (moved) change = true; if (iter == maxIter) { WARN("move phase aborted after ", maxIter, " iterations"); } iter += 1; } while (moved && (iter <= maxIter)); DEBUG("iterations in move phase: ", iter); }; // first move phase movePhase(); if (change) { DEBUG("nodes moved, so begin coarsening and recursive call"); std::pair<Graph, std::vector<node>> coarsened = coarsen(G, zeta); // coarsen graph according to communitites Partition zetaCoarse = run(coarsened.first); zeta = prolong(coarsened.first, zetaCoarse, G, coarsened.second); // unpack communities in coarse graph onto fine graph // refinement phase if (refine) { DEBUG("refinement phase"); // reinit community-dependent temporaries o = zeta.upperBound(); volCommunity.clear(); volCommunity.resize(o, 0.0); zeta.parallelForEntries([&](node u, index C) { // set volume for all communities edgeweight volN = volNode[u]; #pragma omp atomic update volCommunity[C] += volN; }); // second move phase movePhase(); } } return zeta; } std::string NetworKit::PLM::toString() const { std::string refined; if (refine) { refined = "refinement"; } else { refined = ""; } std::stringstream stream; stream << "PLM(" << parallelism << "," << refined << ")"; return stream.str(); } std::pair<Graph, std::vector<node> > PLM::coarsen(const Graph& G, const Partition& zeta) { bool parallelCoarsening = false; // switch between parallel and sequential coarsening if (parallelCoarsening) { PartitionCoarsening parCoarsening; return parCoarsening.run(G, zeta); } else { ClusterContractor seqCoarsening; return seqCoarsening.run(G, zeta); } } Partition PLM::prolong(const Graph& Gcoarse, const Partition& zetaCoarse, const Graph& Gfine, std::vector<node> nodeToMetaNode) { Partition zetaFine(Gfine.upperNodeIdBound()); zetaFine.setUpperBound(zetaCoarse.upperBound()); Gfine.forNodes([&](node v) { node mv = nodeToMetaNode[v]; index cv = zetaCoarse[mv]; zetaFine[v] = cv; }); return zetaFine; } } /* namespace NetworKit */ <|endoftext|>
<commit_before>#include "player.h" Player::Player(int health, float speed, int damage, int width, int height, Texture* texture, Camera * camera, b2World * world) : Person::Person(health, speed, damage, width, height, texture, camera, world) { staff = new Staff(1000.0f, world, 100, 200, glm::vec2(0.0f, -0.0f), ResourceManager::GetTexture("staff"), camera); staff->localPosition.x = -25; staff->localPosition.y = -50; this->AddChild(staff); } Player::~Player() { delete staff; } void Player::Update(double deltaTime) { // If mouse down start shooting a laser if (Input::MouseDown(GLFW_MOUSE_BUTTON_1)) { staff->Shoot(); } // Movement player glm::vec2 velocity = glm::vec2(0.0f, 0.0f); if (Input::KeyDown(GLFW_KEY_W) || Input::KeyDown(GLFW_KEY_UP)) { velocity.y += 1.0f; } if (Input::KeyDown(GLFW_KEY_S) || Input::KeyDown(GLFW_KEY_DOWN)) { velocity.y += -1.0f; } if (Input::KeyDown(GLFW_KEY_A) || Input::KeyDown(GLFW_KEY_LEFT)) { velocity.x += -1.0f; } if (Input::KeyDown(GLFW_KEY_D) || Input::KeyDown(GLFW_KEY_RIGHT)) { velocity.x += 1.0f; } // The velocity has to be not equal to zero otherwise if I normalze the vec2 it will return nand-id if (velocity.x != 0 || velocity.y != 0) { velocity = glm::normalize(velocity); velocity *= 10.0f; } localPosition = ApplyVelocityB2body(velocity); camera->SetPosition(glm::vec2(GetGlobalPosition().x - camera->GetWidth()/2, GetGlobalPosition().y - camera->GetHeight()/2)); // Rotate the player towards the mouse glm::vec2 mousePos = Input::GetMousePositionWorldSpace(camera); glm::vec2 direction = mousePos - GetGlobalPosition(); this->localAngle = std::atan2(direction.y, direction.x) + glm::radians(180.0f); // Rotate the staff towards the mouse glm::vec2 dirStaff = mousePos - glm::vec2(staff->GetGlobalPosition().x, staff->GetGlobalPosition().y); staff->localAngle = glm::atan(dirStaff.y, dirStaff.x) - localAngle + glm::radians(180.0f); // There is a issue where sometimes the angle goes to a really high number and doing -360.0f fixes it from going to high if (glm::degrees(staff->localAngle) > 10.0f) { staff->localAngle = glm::radians(glm::degrees(staff->localAngle) - 360.0f); } // The angle of the staff cant go any lower then -35 degrees otherwise the player will hit itself if (glm::degrees(staff->localAngle) < -35.0f) { staff->localAngle = glm::radians(-35.0f); } for (int i = 0; i < contacts.size(); i++) { //std::cout << "contact amount = " << contacts.size() << std::endl; if (dynamic_cast<Rotator*>(contacts[i]) != NULL) { // Get the pointer of the rotator Rotator* rot = dynamic_cast<Rotator*>(contacts[i]); // Position 'a' is the pivot point of the rotator, The reason I do minus 0.0001f is because otherwise the value will be zero and normaling zero will return nan-id glm::vec2 a = (glm::vec2(rot->GetGlobalPosition().x - 0.001f, rot->GetGlobalPosition().y) - rot->GetGlobalPosition()); a = glm::normalize(a); // Position 'b' is the the position from the player relative to the pivot point from the rotator glm::vec2 b = GetGlobalPosition() - rot->GetGlobalPosition(); b = glm::normalize(b); // Dot product between pivot rotator and player float dot = glm::dot(a, b);// # dot product //angle = atan2(det, dot) # atan2(y, x) or atan2(sin, cos) float det = a.x*b.y - a.y*b.x;// # determinant float anglePlayer = (glm::atan(det, dot) * 180.0f / M_PI);//(glm::acos(glm::dot(a, b)) * 180.0f / M_PI); //std::cout << " angle player = " << anglePlayer << std::endl; float angleRot = (rot->GetRotation() * 180.0f / M_PI); //std::cout << " angle rotator = " << angleRot << std::endl; float difference = anglePlayer - angleRot; //std::cout << " difference = " << anglePlayer - angleRot << std::endl; // Rotate the mirror's rotator // Sometimes there is a huge difference betweent the angle of the player and the rotator // so a hacky kinda way is: asking if it higher or lower helps me find out of what side the player is pushing from if (difference > -250.0f && difference < 0.0f || difference > 250.0f) { rot->Rotate(true, (50.0f * deltaTime)); } else if (difference >= 0.0f || difference < -250.0f) { rot->Rotate(false, (50.0f * deltaTime)); } } } } void Player::SetCamera(Camera * camera) { this->camera = camera; staff->SetCamera(camera); } <commit_msg>Set the camera position to the position of the player<commit_after>#include "player.h" Player::Player(int health, float speed, int damage, int width, int height, Texture* texture, Camera * camera, b2World * world) : Person::Person(health, speed, damage, width, height, texture, camera, world) { staff = new Staff(1000.0f, world, 100, 200, glm::vec2(0.0f, -0.0f), ResourceManager::GetTexture("staff"), camera); staff->localPosition.x = -25; staff->localPosition.y = -50; this->AddChild(staff); } Player::~Player() { delete staff; } void Player::Update(double deltaTime) { // If mouse down start shooting a laser if (Input::MouseDown(GLFW_MOUSE_BUTTON_1)) { staff->Shoot(); } // Movement player glm::vec2 velocity = glm::vec2(0.0f, 0.0f); if (Input::KeyDown(GLFW_KEY_W) || Input::KeyDown(GLFW_KEY_UP)) { velocity.y += 1.0f; } if (Input::KeyDown(GLFW_KEY_S) || Input::KeyDown(GLFW_KEY_DOWN)) { velocity.y += -1.0f; } if (Input::KeyDown(GLFW_KEY_A) || Input::KeyDown(GLFW_KEY_LEFT)) { velocity.x += -1.0f; } if (Input::KeyDown(GLFW_KEY_D) || Input::KeyDown(GLFW_KEY_RIGHT)) { velocity.x += 1.0f; } // The velocity has to be not equal to zero otherwise if I normalze the vec2 it will return nand-id if (velocity.x != 0 || velocity.y != 0) { velocity = glm::normalize(velocity); velocity *= 10.0f; } localPosition = ApplyVelocityB2body(velocity); camera->SetPosition(GetGlobalPosition()); // Rotate the player towards the mouse glm::vec2 mousePos = Input::GetMousePositionWorldSpace(camera); glm::vec2 direction = mousePos - GetGlobalPosition(); this->localAngle = std::atan2(direction.y, direction.x) + glm::radians(180.0f); // Rotate the staff towards the mouse glm::vec2 dirStaff = mousePos - glm::vec2(staff->GetGlobalPosition().x, staff->GetGlobalPosition().y); staff->localAngle = glm::atan(dirStaff.y, dirStaff.x) - localAngle + glm::radians(180.0f); // There is a issue where sometimes the angle goes to a really high number and doing -360.0f fixes it from going to high if (glm::degrees(staff->localAngle) > 10.0f) { staff->localAngle = glm::radians(glm::degrees(staff->localAngle) - 360.0f); } // The angle of the staff cant go any lower then -35 degrees otherwise the player will hit itself if (glm::degrees(staff->localAngle) < -35.0f) { staff->localAngle = glm::radians(-35.0f); } for (int i = 0; i < contacts.size(); i++) { //std::cout << "contact amount = " << contacts.size() << std::endl; if (dynamic_cast<Rotator*>(contacts[i]) != NULL) { // Get the pointer of the rotator Rotator* rot = dynamic_cast<Rotator*>(contacts[i]); // Position 'a' is the pivot point of the rotator, The reason I do minus 0.0001f is because otherwise the value will be zero and normaling zero will return nan-id glm::vec2 a = (glm::vec2(rot->GetGlobalPosition().x - 0.001f, rot->GetGlobalPosition().y) - rot->GetGlobalPosition()); a = glm::normalize(a); // Position 'b' is the the position from the player relative to the pivot point from the rotator glm::vec2 b = GetGlobalPosition() - rot->GetGlobalPosition(); b = glm::normalize(b); // Dot product between pivot rotator and player float dot = glm::dot(a, b);// # dot product //angle = atan2(det, dot) # atan2(y, x) or atan2(sin, cos) float det = a.x*b.y - a.y*b.x;// # determinant float anglePlayer = (glm::atan(det, dot) * 180.0f / M_PI);//(glm::acos(glm::dot(a, b)) * 180.0f / M_PI); //std::cout << " angle player = " << anglePlayer << std::endl; float angleRot = (rot->GetRotation() * 180.0f / M_PI); //std::cout << " angle rotator = " << angleRot << std::endl; float difference = anglePlayer - angleRot; //std::cout << " difference = " << anglePlayer - angleRot << std::endl; // Rotate the mirror's rotator // Sometimes there is a huge difference betweent the angle of the player and the rotator // so a hacky kinda way is: asking if it higher or lower helps me find out of what side the player is pushing from if (difference > -250.0f && difference < 0.0f || difference > 250.0f) { rot->Rotate(true, (50.0f * deltaTime)); } else if (difference >= 0.0f || difference < -250.0f) { rot->Rotate(false, (50.0f * deltaTime)); } } } } void Player::SetCamera(Camera * camera) { this->camera = camera; staff->SetCamera(camera); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pe_file.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-19 12:04:01 $ * * 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 * ************************************************************************/ #include <precomp.h> #include "pe_file.hxx" // NOT FULLY DECLARED SERVICES #include "pe_defs.hxx" #include "pe_enum.hxx" #include "pe_namsp.hxx" #include "pe_tpltp.hxx" #include "pe_tydef.hxx" #include "pe_vafu.hxx" #include "pe_ignor.hxx" // NOT FULLY DECLARED SERVICES namespace cpp { PE_File::PE_File( cpp::PeEnvironment & io_rEnv) : Cpp_PE(io_rEnv), pEnv(&io_rEnv), pStati( new PeStatusArray<PE_File> ), // pSpNamespace, // pSpTypedef, // pSpVarFunc, // pSpIgnore, // pSpuNamespace, // pSpuClass, // pSpuTypedef, // pSpuVarFunc, // pSpuTemplate, // pSpuUsing, // pSpuIgnoreFailure, bWithinSingleExternC(false) { Setup_StatusFunctions(); pSpNamespace = new SP_Namespace(*this); pSpTypedef = new SP_Typedef(*this); pSpVarFunc = new SP_VarFunc(*this); pSpTemplate = new SP_Template(*this); pSpDefs = new SP_Defines(*this); pSpIgnore = new SP_Ignore(*this); pSpuNamespace = new SPU_Namespace(*pSpNamespace, 0, 0); pSpuTypedef = new SPU_Typedef(*pSpTypedef, 0, 0); pSpuVarFunc = new SPU_VarFunc(*pSpVarFunc, 0, &PE_File::SpReturn_VarFunc); pSpuTemplate = new SPU_Template(*pSpTemplate, 0, &PE_File::SpReturn_Template); pSpuDefs = new SPU_Defines(*pSpDefs, 0, 0); pSpuUsing = new SPU_Ignore(*pSpIgnore, 0, 0); pSpuIgnoreFailure = new SPU_Ignore(*pSpIgnore, 0, 0); } PE_File::~PE_File() { } void PE_File::Call_Handler( const cpp::Token & i_rTok ) { pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text()); } Cpp_PE * PE_File::Handle_ChildFailure() { SetCurSPU(pSpuIgnoreFailure.Ptr()); return &pSpuIgnoreFailure->Child(); } ary::cpp::RwGate & PE_File::AryGate() const { return const_cast< PE_File& >(*this).access_Env().AryGate(); } void PE_File::Setup_StatusFunctions() { typedef CallFunction<PE_File>::F_Tok F_Tok; static F_Tok stateF_std[] = { &PE_File::On_std_VarFunc, &PE_File::On_std_ClassKey, &PE_File::On_std_ClassKey, &PE_File::On_std_ClassKey, &PE_File::On_std_enum, &PE_File::On_std_typedef, &PE_File::On_std_template, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc, &PE_File::On_std_extern, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc, &PE_File::On_std_namespace, &PE_File::On_std_using, &PE_File::On_std_SwBracketRight, &PE_File::On_std_VarFunc, &PE_File::On_std_DefineName, &PE_File::On_std_MacroName, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc }; static INT16 stateT_std[] = { Tid_Identifier, Tid_class, Tid_struct, Tid_union, Tid_enum, Tid_typedef, Tid_template, Tid_const, Tid_volatile, Tid_extern, Tid_static, Tid_register, Tid_inline, Tid_namespace, Tid_using, Tid_SwBracket_Right, Tid_DoubleColon, Tid_DefineName, Tid_MacroName, Tid_BuiltInType, Tid_TypeSpecializer, Tid_typename }; static F_Tok stateF_in_extern[] = { &PE_File::On_in_extern_Constant }; static INT16 stateT_in_extern[] = { Tid_Constant }; static F_Tok stateF_in_externC[] = { &PE_File::On_in_externC_SwBracket_Left }; static INT16 stateT_in_externC[] = { Tid_SwBracket_Left }; SEMPARSE_CREATE_STATUS(PE_File, std, Hdl_SyntaxError); SEMPARSE_CREATE_STATUS(PE_File, in_extern, On_in_extern_Ignore); SEMPARSE_CREATE_STATUS(PE_File, in_externC, On_in_externC_NoBlock); } void PE_File::InitData() { pStati->SetCur(std); } void PE_File::TransferData() { pStati->SetCur(size_of_states); } void PE_File::Hdl_SyntaxError( const char * i_sText) { if ( *i_sText == ';' ) { Cerr() << Env().CurFileName() << ", line " << Env().LineCount() << ": Sourcecode warning: ';' as a toplevel declaration is deprecated." << Endl(); SetTokenResult(done,stay); return; } StdHandlingOfSyntaxError(i_sText); } void PE_File::SpReturn_VarFunc() { if (bWithinSingleExternC) { access_Env().CloseBlock(); bWithinSingleExternC = false; } } void PE_File::SpReturn_Template() { access_Env().OpenTemplate( pSpuTemplate->Child().Result_Parameters() ); } void PE_File::On_std_namespace(const char * ) { pSpuNamespace->Push(done); } void PE_File::On_std_ClassKey(const char * ) { pSpuVarFunc->Push(not_done); // This is correct, // classes are parsed via PE_Type. } void PE_File::On_std_typedef(const char * ) { pSpuTypedef->Push(not_done); } void PE_File::On_std_enum(const char * ) { pSpuVarFunc->Push(not_done); // This is correct, // enums are parsed via PE_Type. } void PE_File::On_std_VarFunc(const char * ) { pSpuVarFunc->Push(not_done); } void PE_File::On_std_template(const char * ) { pSpuTemplate->Push(done); } void PE_File::On_std_extern(const char * ) { SetTokenResult(done, stay); pStati->SetCur(in_extern); } void PE_File::On_std_using(const char * ) { pSpuUsing->Push(done); } void PE_File::On_std_SwBracketRight(const char * ) { SetTokenResult(done,stay); access_Env().CloseBlock(); } void PE_File::On_std_DefineName(const char * ) { pSpuDefs->Push(not_done); } void PE_File::On_std_MacroName(const char * ) { pSpuDefs->Push(not_done); } void PE_File::On_in_extern_Constant(const char * ) { SetTokenResult(done,stay); pStati->SetCur(in_externC); access_Env().OpenExternC(); } void PE_File::On_in_extern_Ignore(const char * ) { SetTokenResult(not_done, stay); pStati->SetCur(std); } void PE_File::On_in_externC_SwBracket_Left(const char * ) { SetTokenResult(done, stay); pStati->SetCur(std); } void PE_File::On_in_externC_NoBlock(const char * ) { SetTokenResult(not_done, stay); pStati->SetCur(std); bWithinSingleExternC = true; } } // namespace cpp <commit_msg>INTEGRATION: CWS pchfix02 (1.7.6); FILE MERGED 2006/09/01 17:15:43 kaib 1.7.6.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pe_file.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-16 17:01:59 $ * * 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_autodoc.hxx" #include <precomp.h> #include "pe_file.hxx" // NOT FULLY DECLARED SERVICES #include "pe_defs.hxx" #include "pe_enum.hxx" #include "pe_namsp.hxx" #include "pe_tpltp.hxx" #include "pe_tydef.hxx" #include "pe_vafu.hxx" #include "pe_ignor.hxx" // NOT FULLY DECLARED SERVICES namespace cpp { PE_File::PE_File( cpp::PeEnvironment & io_rEnv) : Cpp_PE(io_rEnv), pEnv(&io_rEnv), pStati( new PeStatusArray<PE_File> ), // pSpNamespace, // pSpTypedef, // pSpVarFunc, // pSpIgnore, // pSpuNamespace, // pSpuClass, // pSpuTypedef, // pSpuVarFunc, // pSpuTemplate, // pSpuUsing, // pSpuIgnoreFailure, bWithinSingleExternC(false) { Setup_StatusFunctions(); pSpNamespace = new SP_Namespace(*this); pSpTypedef = new SP_Typedef(*this); pSpVarFunc = new SP_VarFunc(*this); pSpTemplate = new SP_Template(*this); pSpDefs = new SP_Defines(*this); pSpIgnore = new SP_Ignore(*this); pSpuNamespace = new SPU_Namespace(*pSpNamespace, 0, 0); pSpuTypedef = new SPU_Typedef(*pSpTypedef, 0, 0); pSpuVarFunc = new SPU_VarFunc(*pSpVarFunc, 0, &PE_File::SpReturn_VarFunc); pSpuTemplate = new SPU_Template(*pSpTemplate, 0, &PE_File::SpReturn_Template); pSpuDefs = new SPU_Defines(*pSpDefs, 0, 0); pSpuUsing = new SPU_Ignore(*pSpIgnore, 0, 0); pSpuIgnoreFailure = new SPU_Ignore(*pSpIgnore, 0, 0); } PE_File::~PE_File() { } void PE_File::Call_Handler( const cpp::Token & i_rTok ) { pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text()); } Cpp_PE * PE_File::Handle_ChildFailure() { SetCurSPU(pSpuIgnoreFailure.Ptr()); return &pSpuIgnoreFailure->Child(); } ary::cpp::RwGate & PE_File::AryGate() const { return const_cast< PE_File& >(*this).access_Env().AryGate(); } void PE_File::Setup_StatusFunctions() { typedef CallFunction<PE_File>::F_Tok F_Tok; static F_Tok stateF_std[] = { &PE_File::On_std_VarFunc, &PE_File::On_std_ClassKey, &PE_File::On_std_ClassKey, &PE_File::On_std_ClassKey, &PE_File::On_std_enum, &PE_File::On_std_typedef, &PE_File::On_std_template, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc, &PE_File::On_std_extern, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc, &PE_File::On_std_namespace, &PE_File::On_std_using, &PE_File::On_std_SwBracketRight, &PE_File::On_std_VarFunc, &PE_File::On_std_DefineName, &PE_File::On_std_MacroName, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc, &PE_File::On_std_VarFunc }; static INT16 stateT_std[] = { Tid_Identifier, Tid_class, Tid_struct, Tid_union, Tid_enum, Tid_typedef, Tid_template, Tid_const, Tid_volatile, Tid_extern, Tid_static, Tid_register, Tid_inline, Tid_namespace, Tid_using, Tid_SwBracket_Right, Tid_DoubleColon, Tid_DefineName, Tid_MacroName, Tid_BuiltInType, Tid_TypeSpecializer, Tid_typename }; static F_Tok stateF_in_extern[] = { &PE_File::On_in_extern_Constant }; static INT16 stateT_in_extern[] = { Tid_Constant }; static F_Tok stateF_in_externC[] = { &PE_File::On_in_externC_SwBracket_Left }; static INT16 stateT_in_externC[] = { Tid_SwBracket_Left }; SEMPARSE_CREATE_STATUS(PE_File, std, Hdl_SyntaxError); SEMPARSE_CREATE_STATUS(PE_File, in_extern, On_in_extern_Ignore); SEMPARSE_CREATE_STATUS(PE_File, in_externC, On_in_externC_NoBlock); } void PE_File::InitData() { pStati->SetCur(std); } void PE_File::TransferData() { pStati->SetCur(size_of_states); } void PE_File::Hdl_SyntaxError( const char * i_sText) { if ( *i_sText == ';' ) { Cerr() << Env().CurFileName() << ", line " << Env().LineCount() << ": Sourcecode warning: ';' as a toplevel declaration is deprecated." << Endl(); SetTokenResult(done,stay); return; } StdHandlingOfSyntaxError(i_sText); } void PE_File::SpReturn_VarFunc() { if (bWithinSingleExternC) { access_Env().CloseBlock(); bWithinSingleExternC = false; } } void PE_File::SpReturn_Template() { access_Env().OpenTemplate( pSpuTemplate->Child().Result_Parameters() ); } void PE_File::On_std_namespace(const char * ) { pSpuNamespace->Push(done); } void PE_File::On_std_ClassKey(const char * ) { pSpuVarFunc->Push(not_done); // This is correct, // classes are parsed via PE_Type. } void PE_File::On_std_typedef(const char * ) { pSpuTypedef->Push(not_done); } void PE_File::On_std_enum(const char * ) { pSpuVarFunc->Push(not_done); // This is correct, // enums are parsed via PE_Type. } void PE_File::On_std_VarFunc(const char * ) { pSpuVarFunc->Push(not_done); } void PE_File::On_std_template(const char * ) { pSpuTemplate->Push(done); } void PE_File::On_std_extern(const char * ) { SetTokenResult(done, stay); pStati->SetCur(in_extern); } void PE_File::On_std_using(const char * ) { pSpuUsing->Push(done); } void PE_File::On_std_SwBracketRight(const char * ) { SetTokenResult(done,stay); access_Env().CloseBlock(); } void PE_File::On_std_DefineName(const char * ) { pSpuDefs->Push(not_done); } void PE_File::On_std_MacroName(const char * ) { pSpuDefs->Push(not_done); } void PE_File::On_in_extern_Constant(const char * ) { SetTokenResult(done,stay); pStati->SetCur(in_externC); access_Env().OpenExternC(); } void PE_File::On_in_extern_Ignore(const char * ) { SetTokenResult(not_done, stay); pStati->SetCur(std); } void PE_File::On_in_externC_SwBracket_Left(const char * ) { SetTokenResult(done, stay); pStati->SetCur(std); } void PE_File::On_in_externC_NoBlock(const char * ) { SetTokenResult(not_done, stay); pStati->SetCur(std); bWithinSingleExternC = true; } } // namespace cpp <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS jl61 (1.37.10); FILE MERGED 2007/05/07 10:03:08 ab 1.37.10.1: #i77021# Support Decoration property<commit_after><|endoftext|>
<commit_before>#include "df_message_dialog.h" #if 0 #include <windows.h> int MessageDialog(char const *title, char const *message, MessageDialogType type) { switch (type) { case MsgDlgTypeYesNo: type = (MessageDialogType)MB_YESNO; break; case MsgDlgTypeYesNoCancel: type = (MessageDialogType)MB_YESNOCANCEL; break; case MsgDlgTypeOk: type = (MessageDialogType)MB_OK; break; case MsgDlgTypeOkCancel: type = (MessageDialogType)MB_OKCANCEL; break; } int rv = -1; if (type != -1) { switch (MessageBox(NULL, message, title, type)) { case IDABORT: rv = MsgDlgRtnCode_Abort; break; case IDCANCEL: rv = MsgDlgRtnCode_Cancel; break; case IDNO: rv = MsgDlgRtnCode_No; break; case IDOK: rv = MsgDlgRtnCode_Ok; break; case IDRETRY: rv = MsgDlgRtnCode_Retry; break; case IDYES: rv = MsgDlgRtnCode_Yes; break; } } return rv; } #else // TODO - Make this dialog scale itself according to the screen DPI. #include "fonts/df_prop.h" #include "df_font.h" #include "df_window.h" #include <stdlib.h> #include <string.h> struct Button { char const *label; int x, y, w, h; }; static bool DoButton(DfWindow *win, DfFont *font, Button *button, bool isSelected) { DfColour light = { 0xffa0a0a0 }; DfColour dark = { 0xff646464 }; int x = button->x, y = button->y, w = button->w, h = button->h; int mx = win->input.mouseX; int my = win->input.mouseY; bool mouseOver = mx >= x && my >= y && mx < (x + w) && my < (y + h); RectOutline(win->bmp, x, y, w, h, dark); DfColour tlColour = g_colourWhite; DfColour brColour = light; if (win->input.lmb && mouseOver) { tlColour = light; brColour = g_colourWhite; } HLine(win->bmp, x + 1, y + 1, w - 3, tlColour); VLine(win->bmp, x + 1, y + 2, h - 4, tlColour); HLine(win->bmp, x + 2, y+h-2, w - 4, brColour); VLine(win->bmp, x+w-2, y + 2, h - 3, brColour); int textY = y + h / 2 - font->charHeight / 2; DrawTextCentre(font, g_colourBlack, win->bmp, x + w/2, textY, button->label); if (isSelected) RectOutline(win->bmp, button->x + 4, button->y + 4, button->w - 8, button->h - 8, light); if (win->input.lmbUnClicked && mouseOver) return true; if (win->input.keyDowns[KEY_ENTER]) return true; return false; } int MessageDialog(char const *title, char const *message, MessageDialogType type) { DfFont *font = LoadFontFromMemory(df_prop_8x15, sizeof(df_prop_8x15)); int numLines = 0; int longestLinePixels = 0; { char const *lineStart = message; for (char const *c = message;; c++) { if (*c == '\n' || *c == '\0') { int lineLen = GetTextWidth(font, lineStart, c - lineStart); if (lineLen > longestLinePixels) longestLinePixels = lineLen; lineStart = c + 1; numLines++; } if (*c == '\0') break; } } int textSpaceX = font->charHeight * 1.5; int textSpaceY = font->charHeight * 2; int buttonHeight = font->charHeight * 2; int buttonBarHeight = buttonHeight * 2; int buttonBarTop = textSpaceY * 2 + numLines * font->charHeight; int buttonTop = buttonBarTop + font->charHeight; int buttonWidth = font->charHeight * 6; DfColour buttonColour = { 0xffe0e0e0 }; Button buttons[3]; int numButtons; switch (type) { case MsgDlgTypeYesNo: numButtons = 2; buttons[0].label = "Yes"; buttons[1].label = "No"; break; case MsgDlgTypeYesNoCancel: numButtons = 3; buttons[0].label = "Yes"; buttons[1].label = "No"; buttons[2].label = "Cancel"; break; case MsgDlgTypeOk: numButtons = 1; buttons[0].label = "OK"; break; case MsgDlgTypeOkCancel: numButtons = 2; buttons[0].label = "OK"; buttons[1].label = "Cancel"; break; } int widthNeededForButtons = textSpaceX * (3 + numButtons) + buttonWidth * numButtons; int winWidth = textSpaceX * 2 + longestLinePixels; if (widthNeededForButtons > winWidth) winWidth = widthNeededForButtons; int winHeight = buttonBarTop + buttonBarHeight; // Place buttons, right-most first. { int x = winWidth - textSpaceX * 2 - buttonWidth; for (int i = numButtons - 1; i > -1; i--) { buttons[i].x = x; buttons[i].y = buttonTop; buttons[i].w = buttonWidth; buttons[i].h = buttonHeight; x -= buttonWidth + textSpaceX; } } DfWindow *win = CreateWin(winWidth, winHeight, WT_WINDOWED_FIXED, title); int selectedButton = 0; int result = -1; while (!win->windowClosed && !win->input.keys[KEY_ESC] && result == -1) { InputPoll(win); RectFill(win->bmp, 0, 0, winWidth, buttonBarTop, g_colourWhite); unsigned x = textSpaceX; unsigned y = textSpaceY; char const *lineStart = message; while (1) { char const *lineEnd = strchr(lineStart, '\n'); if (!lineEnd) lineEnd = strchr(lineStart, '\0'); DrawTextSimpleLen(font, g_colourBlack, win->bmp, x, y, lineStart, lineEnd - lineStart); if (*lineEnd == '\0') break; lineStart = lineEnd + 1; y += font->charHeight; } RectFill(win->bmp, 0, buttonBarTop, winWidth, buttonBarHeight, buttonColour); if (win->input.keyDowns[KEY_TAB]) if (win->input.keys[KEY_SHIFT]) selectedButton = (selectedButton + numButtons - 1) % numButtons; else selectedButton = (selectedButton + 1) % numButtons; for (int i = 0; i < numButtons; i++) { bool clicked = DoButton(win, font, &buttons[i], i == selectedButton); if (clicked) result = i; } UpdateWin(win); WaitVsync(); } DestroyWin(win); FontDelete(font); switch (type) { case MsgDlgTypeYesNo: case MsgDlgTypeYesNoCancel: switch (result) { case 0: return MsgDlgRtnCode_Yes; case 1: return MsgDlgRtnCode_No; case 2: return MsgDlgRtnCode_Cancel; } break; case MsgDlgTypeOk: case MsgDlgTypeOkCancel: switch (result) { case 0: return MsgDlgRtnCode_Ok; case 1: return MsgDlgRtnCode_Cancel; } break; } return MsgDlgRtnCode_Abort; } #endif <commit_msg>More tweaks to the new message dialog. 1) add accelerator keys for the buttons, 2) let the selected button be manipulated via cursor left / right, 3) fix a bug, where pressing enter with the selected button being something other than the first button would return the wrong result.<commit_after>#include "df_message_dialog.h" #if 0 #include <windows.h> int MessageDialog(char const *title, char const *message, MessageDialogType type) { switch (type) { case MsgDlgTypeYesNo: type = (MessageDialogType)MB_YESNO; break; case MsgDlgTypeYesNoCancel: type = (MessageDialogType)MB_YESNOCANCEL; break; case MsgDlgTypeOk: type = (MessageDialogType)MB_OK; break; case MsgDlgTypeOkCancel: type = (MessageDialogType)MB_OKCANCEL; break; } int rv = -1; if (type != -1) { switch (MessageBox(NULL, message, title, type)) { case IDABORT: rv = MsgDlgRtnCode_Abort; break; case IDCANCEL: rv = MsgDlgRtnCode_Cancel; break; case IDNO: rv = MsgDlgRtnCode_No; break; case IDOK: rv = MsgDlgRtnCode_Ok; break; case IDRETRY: rv = MsgDlgRtnCode_Retry; break; case IDYES: rv = MsgDlgRtnCode_Yes; break; } } return rv; } #else // TODO - Make this dialog scale itself according to the screen DPI. #include "fonts/df_prop.h" #include "df_font.h" #include "df_window.h" #include <ctype.h> #include <stdlib.h> #include <string.h> struct Button { char const *label; int x, y, w, h; }; static bool DoButton(DfWindow *win, DfFont *font, Button *button, bool isSelected) { DfColour light = { 0xffa0a0a0 }; DfColour dark = { 0xff646464 }; int x = button->x, y = button->y, w = button->w, h = button->h; int mx = win->input.mouseX; int my = win->input.mouseY; bool mouseOver = mx >= x && my >= y && mx < (x + w) && my < (y + h); RectOutline(win->bmp, x, y, w, h, dark); DfColour tlColour = g_colourWhite; DfColour brColour = light; if (win->input.lmb && mouseOver) { tlColour = light; brColour = g_colourWhite; } HLine(win->bmp, x + 1, y + 1, w - 3, tlColour); VLine(win->bmp, x + 1, y + 2, h - 4, tlColour); HLine(win->bmp, x + 2, y+h-2, w - 4, brColour); VLine(win->bmp, x+w-2, y + 2, h - 3, brColour); int textY = y + h / 2 - font->charHeight / 2; int textWidth = GetTextWidth(font, button->label); int buttonCentreX = x + w / 2; int labelX = buttonCentreX - textWidth / 2; int accelKeyUnderlineY = textY + font->charHeight * 0.88; int accelKeyUnderlineWidth = font->charHeight * 0.55; DrawTextSimple(font, g_colourBlack, win->bmp, labelX, textY, button->label); HLine(win->bmp, labelX, accelKeyUnderlineY, accelKeyUnderlineWidth, g_colourBlack); if (isSelected) RectOutline(win->bmp, button->x + 4, button->y + 4, button->w - 8, button->h - 8, light); if (win->input.lmbUnClicked && mouseOver) return true; if (isSelected && win->input.keyDowns[KEY_ENTER]) return true; if (win->input.numKeysTyped > 0 && win->input.keysTyped[0] == tolower(button->label[0])) return true; return false; } int MessageDialog(char const *title, char const *message, MessageDialogType type) { DfFont *font = LoadFontFromMemory(df_prop_8x15, sizeof(df_prop_8x15)); int numLines = 0; int longestLinePixels = 0; { char const *lineStart = message; for (char const *c = message;; c++) { if (*c == '\n' || *c == '\0') { int lineLen = GetTextWidth(font, lineStart, c - lineStart); if (lineLen > longestLinePixels) longestLinePixels = lineLen; lineStart = c + 1; numLines++; } if (*c == '\0') break; } } int textSpaceX = font->charHeight * 1.5; int textSpaceY = font->charHeight * 2; int buttonHeight = font->charHeight * 2; int buttonBarHeight = buttonHeight * 2; int buttonBarTop = textSpaceY * 2 + numLines * font->charHeight; int buttonTop = buttonBarTop + font->charHeight; int buttonWidth = font->charHeight * 6; DfColour buttonColour = { 0xffe0e0e0 }; Button buttons[3]; int numButtons; switch (type) { case MsgDlgTypeYesNo: numButtons = 2; buttons[0].label = "Yes"; buttons[1].label = "No"; break; case MsgDlgTypeYesNoCancel: numButtons = 3; buttons[0].label = "Yes"; buttons[1].label = "No"; buttons[2].label = "Cancel"; break; case MsgDlgTypeOk: numButtons = 1; buttons[0].label = "OK"; break; case MsgDlgTypeOkCancel: numButtons = 2; buttons[0].label = "OK"; buttons[1].label = "Cancel"; break; } int widthNeededForButtons = textSpaceX * (3 + numButtons) + buttonWidth * numButtons; int winWidth = textSpaceX * 2 + longestLinePixels; if (widthNeededForButtons > winWidth) winWidth = widthNeededForButtons; int winHeight = buttonBarTop + buttonBarHeight; // Place buttons, right-most first. { int x = winWidth - textSpaceX * 2 - buttonWidth; for (int i = numButtons - 1; i > -1; i--) { buttons[i].x = x; buttons[i].y = buttonTop; buttons[i].w = buttonWidth; buttons[i].h = buttonHeight; x -= buttonWidth + textSpaceX; } } DfWindow *win = CreateWin(winWidth, winHeight, WT_WINDOWED_FIXED, title); int selectedButton = 0; int result = -1; while (!win->windowClosed && !win->input.keys[KEY_ESC] && result == -1) { InputPoll(win); RectFill(win->bmp, 0, 0, winWidth, buttonBarTop, g_colourWhite); unsigned x = textSpaceX; unsigned y = textSpaceY; char const *lineStart = message; while (1) { char const *lineEnd = strchr(lineStart, '\n'); if (!lineEnd) lineEnd = strchr(lineStart, '\0'); DrawTextSimpleLen(font, g_colourBlack, win->bmp, x, y, lineStart, lineEnd - lineStart); if (*lineEnd == '\0') break; lineStart = lineEnd + 1; y += font->charHeight; } RectFill(win->bmp, 0, buttonBarTop, winWidth, buttonBarHeight, buttonColour); if (win->input.keyDowns[KEY_LEFT] || (win->input.keyDowns[KEY_TAB] && win->input.keys[KEY_SHIFT])) { selectedButton = (selectedButton + numButtons - 1) % numButtons; } if (win->input.keyDowns[KEY_RIGHT] || (win->input.keyDowns[KEY_TAB] && !win->input.keys[KEY_SHIFT])) { selectedButton = (selectedButton + 1) % numButtons; } for (int i = 0; i < numButtons; i++) { bool clicked = DoButton(win, font, &buttons[i], i == selectedButton); if (clicked) result = i; } UpdateWin(win); WaitVsync(); } DestroyWin(win); FontDelete(font); switch (type) { case MsgDlgTypeYesNo: case MsgDlgTypeYesNoCancel: switch (result) { case 0: return MsgDlgRtnCode_Yes; case 1: return MsgDlgRtnCode_No; case 2: return MsgDlgRtnCode_Cancel; } break; case MsgDlgTypeOk: case MsgDlgTypeOkCancel: switch (result) { case 0: return MsgDlgRtnCode_Ok; case 1: return MsgDlgRtnCode_Cancel; } break; } return MsgDlgRtnCode_Abort; } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/lazy_list_fn.h" #include "util/flet.h" #include "kernel/instantiate.h" #include "kernel/for_each_fn.h" #include "kernel/abstract.h" #include "library/unifier.h" #include "library/reducible.h" #include "library/metavar_closure.h" #include "library/error_handling/error_handling.h" #include "frontends/lean/util.h" #include "frontends/lean/class.h" #include "frontends/lean/tactic_hint.h" #include "frontends/lean/local_context.h" #include "frontends/lean/choice_iterator.h" namespace lean { /** \brief Context for handling placeholder metavariable choice constraint */ struct placeholder_context { io_state m_ios; name_generator m_ngen; type_checker_ptr m_tc; local_context m_ctx; bool m_relax; bool m_use_local_instances; placeholder_context(environment const & env, io_state const & ios, local_context const & ctx, name const & prefix, bool relax, bool use_local_instances): m_ios(ios), m_ngen(prefix), m_tc(mk_type_checker(env, m_ngen.mk_child(), relax)), m_ctx(ctx), m_relax(relax), m_use_local_instances(use_local_instances) { } environment const & env() const { return m_tc->env(); } io_state const & ios() const { return m_ios; } bool use_local_instances() const { return m_use_local_instances; } type_checker & tc() const { return *m_tc; } }; pair<expr, constraint> mk_placeholder_elaborator(std::shared_ptr<placeholder_context> const & C, optional<expr> const & type, tag g); /** \brief Whenever the elaborator finds a placeholder '_' or introduces an implicit argument, it creates a metavariable \c ?m. It also creates a delayed choice constraint (?m in fn). The function \c fn produces a stream of alternative solutions for ?m. In this case, \c fn will do the following: 1) if the elaborated type of ?m is a 'class' C, then the stream will start with a) all local instances of class C (if elaborator.local_instances == true) b) solutions produced by tactic_hints for class C 2) if the elaborated type of ?m is not a class, then the stream will only contain the solutions produced by tactic_hints. The unifier only process delayed choice constraints when there are no other kind of constraint to be processed. This is a helper class for implementing this choice function. */ struct placeholder_elaborator : public choice_iterator { std::shared_ptr<placeholder_context> m_C; expr m_meta; // elaborated type of the metavariable expr m_meta_type; // local instances that should also be included in the // class-instance resolution. // This information is retrieved from the local context list<expr> m_local_instances; // global declaration names that are class instances. // This information is retrieved using #get_class_instances. list<name> m_instances; // Tactic hints for the class list<tactic_hint_entry> m_tactics; // result produce by last executed tactic. proof_state_seq m_tactic_result; justification m_jst; placeholder_elaborator(std::shared_ptr<placeholder_context> const & C, expr const & meta, expr const & meta_type, list<expr> const & local_insts, list<name> const & instances, list<tactic_hint_entry> const & tacs, justification const & j): choice_iterator(), m_C(C), m_meta(meta), m_meta_type(meta_type), m_local_instances(local_insts), m_instances(instances), m_tactics(tacs), m_jst(j) { } constraints mk_constraints(constraint const & c, buffer<constraint> const & cs) { return cons(c, to_list(cs.begin(), cs.end())); } optional<constraints> try_instance(expr const & inst, expr const & inst_type) { type_checker & tc = m_C->tc(); name_generator & ngen = m_C->m_ngen; tag g = inst.get_tag(); local_context & ctx = m_C->m_ctx; try { flet<local_context> scope(ctx, ctx); buffer<expr> locals; expr meta_type = m_meta_type; while (true) { meta_type = tc.whnf(meta_type).first; if (!is_pi(meta_type)) break; expr local = mk_local(ngen.next(), binding_name(meta_type), binding_domain(meta_type), binding_info(meta_type)); ctx.add_local(local); locals.push_back(local); meta_type = instantiate(binding_body(meta_type), local); } expr type = inst_type; expr r = inst; buffer<constraint> cs; while (true) { type = tc.whnf(type).first; if (!is_pi(type)) break; pair<expr, constraint> ac = mk_placeholder_elaborator(m_C, some_expr(binding_domain(type)), g); expr arg = ac.first; cs.push_back(ac.second); r = mk_app(r, arg).set_tag(g); type = instantiate(binding_body(type), arg); } r = Fun(locals, r); bool relax = m_C->m_relax; constraint c = mk_eq_cnstr(m_meta, r, m_jst, relax); return optional<constraints>(mk_constraints(c, cs)); } catch (exception &) { return optional<constraints>(); } } optional<constraints> try_instance(name const & inst) { environment const & env = m_C->env(); if (auto decl = env.find(inst)) { name_generator & ngen = m_C->m_ngen; buffer<level> ls_buffer; unsigned num_univ_ps = length(decl->get_univ_params()); for (unsigned i = 0; i < num_univ_ps; i++) ls_buffer.push_back(mk_meta_univ(ngen.next())); levels ls = to_list(ls_buffer.begin(), ls_buffer.end()); expr inst_cnst = copy_tag(m_meta, mk_constant(inst, ls)); expr inst_type = instantiate_type_univ_params(*decl, ls); return try_instance(inst_cnst, inst_type); } else { return optional<constraints>(); } } optional<constraints> get_next_tactic_result() { while (auto next = m_tactic_result.pull()) { m_tactic_result = next->second; if (!empty(next->first.get_goals())) continue; // has unsolved goals substitution subst = next->first.get_subst(); expr const & mvar = get_app_fn(m_meta); bool relax = m_C->m_relax; constraints cs = metavar_closure(m_meta_type).mk_constraints(subst, m_jst, relax); constraint c = mk_eq_cnstr(mvar, subst.instantiate(mvar), m_jst, relax); return some(cons(c, cs)); } return optional<constraints>(); } virtual optional<constraints> next() { while (!empty(m_local_instances)) { expr inst = head(m_local_instances); m_local_instances = tail(m_local_instances); if (!is_local(inst)) continue; if (auto r = try_instance(inst, mlocal_type(inst))) return r; } while (!empty(m_instances)) { name inst = head(m_instances); m_instances = tail(m_instances); if (auto cs = try_instance(inst)) return cs; } if (auto cs = get_next_tactic_result()) return cs; while (!empty(m_tactics)) { tactic const & tac = head(m_tactics).get_tactic(); m_tactics = tail(m_tactics); proof_state ps(goals(goal(m_meta, m_meta_type)), substitution(), m_C->m_ngen.mk_child()); try { m_tactic_result = tac(m_C->env(), m_C->ios(), ps); if (auto cs = get_next_tactic_result()) return cs; } catch (exception &) {} } return optional<constraints>(); } }; constraint mk_placeholder_cnstr(std::shared_ptr<placeholder_context> const & C, expr const & m) { environment const & env = C->env(); justification j = mk_failed_to_synthesize_jst(env, m); auto choice_fn = [=](expr const & meta, expr const & meta_type, substitution const & s, name_generator const & /* ngen */) { expr const & mvar = get_app_fn(meta); if (auto cls_name_it = is_ext_class(C->tc(), meta_type)) { name cls_name = *cls_name_it; list<expr> const & ctx = C->m_ctx.get_data(); list<expr> local_insts; if (C->use_local_instances()) local_insts = get_local_instances(C->tc(), ctx, cls_name); list<name> insts = get_class_instances(env, cls_name); list<tactic_hint_entry> tacs; if (!s.is_assigned(mvar)) tacs = get_tactic_hints(env, cls_name); if (empty(local_insts) && empty(insts) && empty(tacs)) return lazy_list<constraints>(); // nothing to be done // we are always strict with placeholders associated with classes return choose(std::make_shared<placeholder_elaborator>(C, meta, meta_type, local_insts, insts, tacs, j)); } else { // do nothing, type is not a class... return lazy_list<constraints>(constraints()); } }; bool owner = false; bool relax = C->m_relax; return mk_choice_cnstr(m, choice_fn, to_delay_factor(cnstr_group::ClassInstance), owner, j, relax); } pair<expr, constraint> mk_placeholder_elaborator(std::shared_ptr<placeholder_context> const & C, optional<expr> const & type, tag g) { expr m = C->m_ctx.mk_meta(C->m_ngen, type, g); constraint c = mk_placeholder_cnstr(C, m); return mk_pair(m, c); } /** \brief Similar to has_expr_metavar, but ignores metavariables occurring in the type of local constants */ static bool has_expr_metavar_relaxed(expr const & e) { if (!has_expr_metavar(e)) return false; bool found = false; for_each(e, [&](expr const & e, unsigned) { if (found || !has_expr_metavar(e)) return false; if (is_metavar(e)) { found = true; return false; } if (is_local(e)) return false; // do not visit type return true; }); return found; } constraint mk_placeholder_root_cnstr(std::shared_ptr<placeholder_context> const & C, expr const & m, bool is_strict, unifier_config const & cfg, delay_factor const & factor) { environment const & env = C->env(); justification j = mk_failed_to_synthesize_jst(env, m); auto choice_fn = [=](expr const & meta, expr const & meta_type, substitution const & s, name_generator const & ngen) { if (!is_ext_class(C->tc(), meta_type)) { // do nothing, since type is not a class. return lazy_list<constraints>(constraints()); } pair<expr, justification> mj = update_meta(meta, s); expr new_meta = mj.first; justification new_j = mj.second; constraint c = mk_placeholder_cnstr(C, new_meta); unifier_config new_cfg(cfg); new_cfg.m_discard = false; new_cfg.m_use_exceptions = false; unify_result_seq seq1 = unify(env, 1, &c, ngen, new_cfg); unify_result_seq seq2 = filter(seq1, [=](pair<substitution, constraints> const & p) { substitution new_s = p.first; expr result = new_s.instantiate(new_meta); // We only keep complete solution (modulo universe metavariables) return !has_expr_metavar_relaxed(result); }); lazy_list<constraints> seq3 = map2<constraints>(seq2, [=](pair<substitution, constraints> const & p) { substitution new_s = p.first; // some constraints may have been postponed (example: universe level constraints) constraints postponed = map(p.second, [&](constraint const & c) { // we erase internal justifications return update_justification(c, new_j); }); metavar_closure cls(new_meta); cls.add(meta_type); bool relax = C->m_relax; constraints cs = cls.mk_constraints(new_s, new_j, relax); return append(cs, postponed); }); if (is_strict) { return seq3; } else { // make sure it does not fail by appending empty set of constraints return append(seq3, lazy_list<constraints>(constraints())); } }; bool owner = false; bool relax = C->m_relax; return mk_choice_cnstr(m, choice_fn, factor, owner, j, relax); } /** \brief Create a metavariable, and attach choice constraint for generating solutions using class-instances and tactic-hints. */ pair<expr, constraint> mk_placeholder_elaborator( environment const & env, io_state const & ios, local_context const & ctx, name const & prefix, bool relax, bool use_local_instances, bool is_strict, optional<expr> const & type, tag g, unifier_config const & cfg) { auto C = std::make_shared<placeholder_context>(env, ios, ctx, prefix, relax, use_local_instances); expr m = C->m_ctx.mk_meta(C->m_ngen, type, g); constraint c = mk_placeholder_root_cnstr(C, m, is_strict, cfg, delay_factor()); return mk_pair(m, c); } } <commit_msg>chore(frontends/lean/placeholder_elaborator): indent code<commit_after>/* Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/lazy_list_fn.h" #include "util/flet.h" #include "kernel/instantiate.h" #include "kernel/for_each_fn.h" #include "kernel/abstract.h" #include "library/unifier.h" #include "library/reducible.h" #include "library/metavar_closure.h" #include "library/error_handling/error_handling.h" #include "frontends/lean/util.h" #include "frontends/lean/class.h" #include "frontends/lean/tactic_hint.h" #include "frontends/lean/local_context.h" #include "frontends/lean/choice_iterator.h" namespace lean { /** \brief Context for handling placeholder metavariable choice constraint */ struct placeholder_context { io_state m_ios; name_generator m_ngen; type_checker_ptr m_tc; local_context m_ctx; bool m_relax; bool m_use_local_instances; placeholder_context(environment const & env, io_state const & ios, local_context const & ctx, name const & prefix, bool relax, bool use_local_instances): m_ios(ios), m_ngen(prefix), m_tc(mk_type_checker(env, m_ngen.mk_child(), relax)), m_ctx(ctx), m_relax(relax), m_use_local_instances(use_local_instances) { } environment const & env() const { return m_tc->env(); } io_state const & ios() const { return m_ios; } bool use_local_instances() const { return m_use_local_instances; } type_checker & tc() const { return *m_tc; } }; pair<expr, constraint> mk_placeholder_elaborator(std::shared_ptr<placeholder_context> const & C, optional<expr> const & type, tag g); /** \brief Whenever the elaborator finds a placeholder '_' or introduces an implicit argument, it creates a metavariable \c ?m. It also creates a delayed choice constraint (?m in fn). The function \c fn produces a stream of alternative solutions for ?m. In this case, \c fn will do the following: 1) if the elaborated type of ?m is a 'class' C, then the stream will start with a) all local instances of class C (if elaborator.local_instances == true) b) solutions produced by tactic_hints for class C 2) if the elaborated type of ?m is not a class, then the stream will only contain the solutions produced by tactic_hints. The unifier only process delayed choice constraints when there are no other kind of constraint to be processed. This is a helper class for implementing this choice function. */ struct placeholder_elaborator : public choice_iterator { std::shared_ptr<placeholder_context> m_C; expr m_meta; // elaborated type of the metavariable expr m_meta_type; // local instances that should also be included in the // class-instance resolution. // This information is retrieved from the local context list<expr> m_local_instances; // global declaration names that are class instances. // This information is retrieved using #get_class_instances. list<name> m_instances; // Tactic hints for the class list<tactic_hint_entry> m_tactics; // result produce by last executed tactic. proof_state_seq m_tactic_result; justification m_jst; placeholder_elaborator(std::shared_ptr<placeholder_context> const & C, expr const & meta, expr const & meta_type, list<expr> const & local_insts, list<name> const & instances, list<tactic_hint_entry> const & tacs, justification const & j): choice_iterator(), m_C(C), m_meta(meta), m_meta_type(meta_type), m_local_instances(local_insts), m_instances(instances), m_tactics(tacs), m_jst(j) { } constraints mk_constraints(constraint const & c, buffer<constraint> const & cs) { return cons(c, to_list(cs.begin(), cs.end())); } optional<constraints> try_instance(expr const & inst, expr const & inst_type) { type_checker & tc = m_C->tc(); name_generator & ngen = m_C->m_ngen; tag g = inst.get_tag(); local_context & ctx = m_C->m_ctx; try { flet<local_context> scope(ctx, ctx); buffer<expr> locals; expr meta_type = m_meta_type; while (true) { meta_type = tc.whnf(meta_type).first; if (!is_pi(meta_type)) break; expr local = mk_local(ngen.next(), binding_name(meta_type), binding_domain(meta_type), binding_info(meta_type)); ctx.add_local(local); locals.push_back(local); meta_type = instantiate(binding_body(meta_type), local); } expr type = inst_type; expr r = inst; buffer<constraint> cs; while (true) { type = tc.whnf(type).first; if (!is_pi(type)) break; pair<expr, constraint> ac = mk_placeholder_elaborator(m_C, some_expr(binding_domain(type)), g); expr arg = ac.first; cs.push_back(ac.second); r = mk_app(r, arg).set_tag(g); type = instantiate(binding_body(type), arg); } r = Fun(locals, r); bool relax = m_C->m_relax; constraint c = mk_eq_cnstr(m_meta, r, m_jst, relax); return optional<constraints>(mk_constraints(c, cs)); } catch (exception &) { return optional<constraints>(); } } optional<constraints> try_instance(name const & inst) { environment const & env = m_C->env(); if (auto decl = env.find(inst)) { name_generator & ngen = m_C->m_ngen; buffer<level> ls_buffer; unsigned num_univ_ps = length(decl->get_univ_params()); for (unsigned i = 0; i < num_univ_ps; i++) ls_buffer.push_back(mk_meta_univ(ngen.next())); levels ls = to_list(ls_buffer.begin(), ls_buffer.end()); expr inst_cnst = copy_tag(m_meta, mk_constant(inst, ls)); expr inst_type = instantiate_type_univ_params(*decl, ls); return try_instance(inst_cnst, inst_type); } else { return optional<constraints>(); } } optional<constraints> get_next_tactic_result() { while (auto next = m_tactic_result.pull()) { m_tactic_result = next->second; if (!empty(next->first.get_goals())) continue; // has unsolved goals substitution subst = next->first.get_subst(); expr const & mvar = get_app_fn(m_meta); bool relax = m_C->m_relax; constraints cs = metavar_closure(m_meta_type).mk_constraints(subst, m_jst, relax); constraint c = mk_eq_cnstr(mvar, subst.instantiate(mvar), m_jst, relax); return some(cons(c, cs)); } return optional<constraints>(); } virtual optional<constraints> next() { while (!empty(m_local_instances)) { expr inst = head(m_local_instances); m_local_instances = tail(m_local_instances); if (!is_local(inst)) continue; if (auto r = try_instance(inst, mlocal_type(inst))) return r; } while (!empty(m_instances)) { name inst = head(m_instances); m_instances = tail(m_instances); if (auto cs = try_instance(inst)) return cs; } if (auto cs = get_next_tactic_result()) return cs; while (!empty(m_tactics)) { tactic const & tac = head(m_tactics).get_tactic(); m_tactics = tail(m_tactics); proof_state ps(goals(goal(m_meta, m_meta_type)), substitution(), m_C->m_ngen.mk_child()); try { m_tactic_result = tac(m_C->env(), m_C->ios(), ps); if (auto cs = get_next_tactic_result()) return cs; } catch (exception &) {} } return optional<constraints>(); } }; constraint mk_placeholder_cnstr(std::shared_ptr<placeholder_context> const & C, expr const & m) { environment const & env = C->env(); justification j = mk_failed_to_synthesize_jst(env, m); auto choice_fn = [=](expr const & meta, expr const & meta_type, substitution const & s, name_generator const & /* ngen */) { expr const & mvar = get_app_fn(meta); if (auto cls_name_it = is_ext_class(C->tc(), meta_type)) { name cls_name = *cls_name_it; list<expr> const & ctx = C->m_ctx.get_data(); list<expr> local_insts; if (C->use_local_instances()) local_insts = get_local_instances(C->tc(), ctx, cls_name); list<name> insts = get_class_instances(env, cls_name); list<tactic_hint_entry> tacs; if (!s.is_assigned(mvar)) tacs = get_tactic_hints(env, cls_name); if (empty(local_insts) && empty(insts) && empty(tacs)) return lazy_list<constraints>(); // nothing to be done // we are always strict with placeholders associated with classes return choose(std::make_shared<placeholder_elaborator>(C, meta, meta_type, local_insts, insts, tacs, j)); } else { // do nothing, type is not a class... return lazy_list<constraints>(constraints()); } }; bool owner = false; bool relax = C->m_relax; return mk_choice_cnstr(m, choice_fn, to_delay_factor(cnstr_group::ClassInstance), owner, j, relax); } pair<expr, constraint> mk_placeholder_elaborator(std::shared_ptr<placeholder_context> const & C, optional<expr> const & type, tag g) { expr m = C->m_ctx.mk_meta(C->m_ngen, type, g); constraint c = mk_placeholder_cnstr(C, m); return mk_pair(m, c); } /** \brief Similar to has_expr_metavar, but ignores metavariables occurring in the type of local constants */ static bool has_expr_metavar_relaxed(expr const & e) { if (!has_expr_metavar(e)) return false; bool found = false; for_each(e, [&](expr const & e, unsigned) { if (found || !has_expr_metavar(e)) return false; if (is_metavar(e)) { found = true; return false; } if (is_local(e)) return false; // do not visit type return true; }); return found; } constraint mk_placeholder_root_cnstr(std::shared_ptr<placeholder_context> const & C, expr const & m, bool is_strict, unifier_config const & cfg, delay_factor const & factor) { environment const & env = C->env(); justification j = mk_failed_to_synthesize_jst(env, m); auto choice_fn = [=](expr const & meta, expr const & meta_type, substitution const & s, name_generator const & ngen) { if (!is_ext_class(C->tc(), meta_type)) { // do nothing, since type is not a class. return lazy_list<constraints>(constraints()); } pair<expr, justification> mj = update_meta(meta, s); expr new_meta = mj.first; justification new_j = mj.second; constraint c = mk_placeholder_cnstr(C, new_meta); unifier_config new_cfg(cfg); new_cfg.m_discard = false; new_cfg.m_use_exceptions = false; unify_result_seq seq1 = unify(env, 1, &c, ngen, new_cfg); unify_result_seq seq2 = filter(seq1, [=](pair<substitution, constraints> const & p) { substitution new_s = p.first; expr result = new_s.instantiate(new_meta); // We only keep complete solution (modulo universe metavariables) return !has_expr_metavar_relaxed(result); }); lazy_list<constraints> seq3 = map2<constraints>(seq2, [=](pair<substitution, constraints> const & p) { substitution new_s = p.first; // some constraints may have been postponed (example: universe level constraints) constraints postponed = map(p.second, [&](constraint const & c) { // we erase internal justifications return update_justification(c, mk_composite1(j, new_j)); }); metavar_closure cls(new_meta); cls.add(meta_type); bool relax = C->m_relax; constraints cs = cls.mk_constraints(new_s, new_j, relax); return append(cs, postponed); }); if (is_strict) { return seq3; } else { // make sure it does not fail by appending empty set of constraints return append(seq3, lazy_list<constraints>(constraints())); } }; bool owner = false; bool relax = C->m_relax; return mk_choice_cnstr(m, choice_fn, factor, owner, j, relax); } /** \brief Create a metavariable, and attach choice constraint for generating solutions using class-instances and tactic-hints. */ pair<expr, constraint> mk_placeholder_elaborator( environment const & env, io_state const & ios, local_context const & ctx, name const & prefix, bool relax, bool use_local_instances, bool is_strict, optional<expr> const & type, tag g, unifier_config const & cfg) { auto C = std::make_shared<placeholder_context>(env, ios, ctx, prefix, relax, use_local_instances); expr m = C->m_ctx.mk_meta(C->m_ngen, type, g); constraint c = mk_placeholder_root_cnstr(C, m, is_strict, cfg, delay_factor()); return mk_pair(m, c); } } <|endoftext|>
<commit_before>/***************************************************************************** * Copyright (C) 2011-2016 Michael Ira Krufky * * Author: Michael Ira Krufky <mkrufky@linuxtv.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <stdio.h> #include "demux.h" #include "log.h" #define CLASS_MODULE "demux" #define DBG_DEMUX DBG_PARSE #define dPrintf(fmt, arg...) __dPrintf(DBG_DEMUX, fmt, ##arg) demux::demux() { dPrintf("()"); out.clear(); } demux::~demux() { dPrintf("()"); sleep(2); for (map_output::const_iterator iter = out.begin(); iter != out.end(); ++iter) ((output_stream)(iter->second)).stop_after_drain(); out.clear(); } int demux::push(uint16_t pid, uint8_t *p) { if (!out.count(pid)) { map_pidtype pids; #if 0 /* we pass in an empty map to reduce unnecessary CPU - * no need to demux AGAIN, but for documentation's sake, * we could subscribe to this and only this pid like so: */ pids[pid] = 0; #endif char newfile[16] = { 0 }; snprintf(newfile, sizeof(newfile), "file://%04x.ts", pid); int ret = out[pid].add(newfile, pids); if (ret < 0) return ret; out[pid].start(); } return (out[pid].push(p, 188)) ? 0 : -1; } <commit_msg>demux: fix 'uninitialized pointer read' in destructor<commit_after>/***************************************************************************** * Copyright (C) 2011-2016 Michael Ira Krufky * * Author: Michael Ira Krufky <mkrufky@linuxtv.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <stdio.h> #include "demux.h" #include "log.h" #define CLASS_MODULE "demux" #define DBG_DEMUX DBG_PARSE #define dPrintf(fmt, arg...) __dPrintf(DBG_DEMUX, fmt, ##arg) demux::demux() { dPrintf("()"); out.clear(); } demux::~demux() { dPrintf("()"); sleep(2); for (map_output::iterator iter = out.begin(); iter != out.end(); ++iter) (iter->second).stop_after_drain(); out.clear(); } int demux::push(uint16_t pid, uint8_t *p) { if (!out.count(pid)) { map_pidtype pids; #if 0 /* we pass in an empty map to reduce unnecessary CPU - * no need to demux AGAIN, but for documentation's sake, * we could subscribe to this and only this pid like so: */ pids[pid] = 0; #endif char newfile[16] = { 0 }; snprintf(newfile, sizeof(newfile), "file://%04x.ts", pid); int ret = out[pid].add(newfile, pids); if (ret < 0) return ret; out[pid].start(); } return (out[pid].push(p, 188)) ? 0 : -1; } <|endoftext|>
<commit_before>/* Copyright (C) 2014-2017 Alexandr Akulich <akulichalexander@gmail.com> This file is a part of TelegramQt library. 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. */ #ifndef TELEGRAMNAMESPACE_HPP #define TELEGRAMNAMESPACE_HPP #include "telegramqt_global.h" #include <QObject> #include <QFlags> #include <QMetaType> #include <QVector> #ifndef Q_ENUM #define Q_ENUM(x) Q_ENUMS(x) #endif namespace Telegram { TELEGRAMQT_EXPORT QString version(); TELEGRAMQT_EXPORT QString buildVersion(); struct Peer { Q_GADGET Q_PROPERTY(Telegram::Peer::Type type MEMBER type) Q_PROPERTY(quint32 id MEMBER id) public: enum Type { User, Chat, Channel, }; Q_ENUM(Type) Peer(quint32 id = 0, Type t = User) : type(t), id(id) { } Type type; quint32 id; Q_INVOKABLE bool isValid() const { return id; } bool operator==(const Peer &p) const { return (p.id == id) && (p.type == type); } bool operator!=(const Peer &p) const { return (p.id != id) || (p.type != type); } static Peer fromUserId(quint32 id) { return Peer(id, User); } static Peer fromChatId(quint32 id) { return Peer(id, Chat); } static Peer fromChannelId(quint32 id) { return Peer(id, Channel); } QString toString() const; static Peer fromString(const QString &string); }; using PeerList = QVector<Peer>; inline uint qHash(const Peer &key, uint seed) { return ::qHash(static_cast<ulong>(key.id | (static_cast<quint64>(key.type) << (sizeof(key.id) * 8))), seed); } } // Telegram namespace class TELEGRAMQT_EXPORT TelegramNamespace : public QObject { Q_OBJECT public: enum ContactStatus { ContactStatusUnknown, ContactStatusOffline, ContactStatusOnline }; Q_ENUM(ContactStatus) enum MessageFlag { MessageFlagNone = 0x0, MessageFlagRead = 0x1, // Message was read MessageFlagOut = 0x2, // Message is outgoing MessageFlagForwarded = 0x4, MessageFlagIsReply = 0x8, }; Q_ENUM(MessageFlag) Q_DECLARE_FLAGS(MessageFlags, MessageFlag) enum MessageType { MessageTypeUnsupported = 0x00, MessageTypeText = 0x01, MessageTypePhoto = 0x02, MessageTypeAudio = 0x04, MessageTypeVideo = 0x08, MessageTypeContact = 0x10, MessageTypeDocument = 0x20, MessageTypeGeo = 0x40, MessageTypeWebPage = 0x80, MessageTypeAll = 0xff }; Q_ENUM(MessageType) Q_DECLARE_FLAGS(MessageTypeFlags, MessageType) enum AuthSignError { AuthSignErrorUnknown, AuthSignErrorAppIdIsInvalid, AuthSignErrorPhoneNumberIsInvalid, AuthSignErrorPhoneNumberIsOccupied, AuthSignErrorPhoneNumberIsUnoccupied, AuthSignErrorPhoneCodeIsInvalid, AuthSignErrorPhoneCodeIsExpired, AuthSignErrorPasswordHashInvalid, AuthSignErrorFirstNameIsInvalid, AuthSignErrorLastNameIsInvalid }; Q_ENUM(AuthSignError) enum UnauthorizedError { UnauthorizedUnknownError, UnauthorizedErrorKeyUnregistered, UnauthorizedErrorKeyInvalid, UnauthorizedErrorUserDeactivated, UnauthorizedErrorUserSessionRevoked, UnauthorizedErrorUserSessionExpired, UnauthorizedErrorActiveUserRequired, UnauthorizedErrorNeedPermanentKey, UnauthorizedSessionPasswordNeeded, }; Q_ENUM(UnauthorizedError) enum UserNameStatus { UserNameStatusUnknown, UserNameStatusIsInvalid, UserNameStatusIsOccupied, UserNameStatusIsNotModified, UserNameStatusCanBeUsed, UserNameStatusCanNotBeUsed, UserNameStatusResolved, UserNameStatusAccepted }; Q_ENUM(UserNameStatus) enum ContactLastOnline { ContactLastOnlineUnknown, ContactLastOnlineRecently, ContactLastOnlineLastWeek, ContactLastOnlineLastMonth, ContactLastOnlineMask = 0xf }; enum MessageAction { MessageActionNone, // Cancel MessageActionTyping, MessageActionRecordVideo, MessageActionRecordAudio, MessageActionUploadVideo, MessageActionUploadAudio, MessageActionUploadPhoto, MessageActionUploadDocument, MessageActionGeoLocation, MessageActionChooseContact }; Q_ENUM(MessageAction) static void registerTypes(); Q_INVOKABLE static Telegram::Peer emptyPeer(); Q_INVOKABLE static Telegram::Peer peerFromChatId(quint32 id); Q_INVOKABLE static Telegram::Peer peerFromChannelId(quint32 id); Q_INVOKABLE static Telegram::Peer peerFromUserId(quint32 id); }; namespace Telegram { void initialize(); struct RsaKey { QByteArray modulus; QByteArray exponent; QByteArray secretExponent; quint64 fingerprint; RsaKey() : fingerprint(0) { } RsaKey(const QByteArray &initialModulus, const QByteArray &initialExponent, const quint64 initialFingersprint = 0) : modulus(initialModulus), exponent(initialExponent), fingerprint(initialFingersprint) { } RsaKey &operator=(const RsaKey &otherKey) { modulus = otherKey.modulus; exponent = otherKey.exponent; secretExponent = otherKey.secretExponent; fingerprint = otherKey.fingerprint; return *this; } void updateFingersprint(); bool isValid() const; void loadFromFile(const QString &fileName); static RsaKey fromFile(const QString &fileName); }; class UserInfo; class RemoteFile; class MessageMediaInfo; enum class PeerPictureSize { Small, Big, }; struct DcOption { enum Flags { Ipv6 = 1 << 0, MediaOnly = 1 << 1, TcpOnly = 1 << 2, Cdn = 1 << 3, IsStatic = 1 << 4, }; DcOption() = default; DcOption(const QString &a, quint16 p, quint32 dcId = 0) : address(a), id(dcId), port(p) { } bool operator==(const DcOption &option) const; bool isValid() const { return id && port && !address.isEmpty(); } QString address; quint32 id = 0; quint16 port = 0; quint16 flags = 0; }; inline bool DcOption::operator==(const DcOption &option) const { return (option.id == id) && (option.port == port) && (option.address == address) && (option.flags == flags); } struct Message { Message() : replyToMessageId(0), forwardContactId(0), id(0), timestamp(0), fwdTimestamp(0), type(TelegramNamespace::MessageTypeUnsupported), flags(TelegramNamespace::MessageFlagNone) { } quint32 fromId; // Telegram user id const Peer peer() const { return m_peer; } void setPeer(const Peer &peer) { m_peer = peer; } const Peer forwardFromPeer() const { return m_forwardPeer; } void setForwardFromPeer(const Peer &peer) { m_forwardPeer = peer; } quint32 replyToMessageId; quint32 forwardContactId; QString text; quint32 id; quint32 timestamp; quint32 fwdTimestamp; TelegramNamespace::MessageType type; TelegramNamespace::MessageFlags flags; private: Peer m_peer; Peer m_forwardPeer; }; class MessageMediaInfo { public: MessageMediaInfo(); MessageMediaInfo(const MessageMediaInfo &info); ~MessageMediaInfo(); MessageMediaInfo &operator=(const MessageMediaInfo &info); void setUploadFile(TelegramNamespace::MessageType type, const RemoteFile &file); bool getRemoteFileInfo(RemoteFile *file) const; TelegramNamespace::MessageType type() const; quint32 size() const; quint32 duration() const; bool setDuration(quint32 duration); QString documentFileName() const; bool setDocumentFileName(const QString &fileName); // Photo, Video QString caption() const; void setCaption(const QString &caption); // Valid for Document and Audio QString mimeType() const; bool setMimeType(const QString &mimeType); // Contact bool getContactInfo(UserInfo *info) const; void setContactInfo(const UserInfo *info); // Valid for GeoPoint and Document/Sticker QString alt() const; // GeoPoint double latitude() const; double longitude() const; void setGeoPoint(double latitude, double longitude); QString url() const; QString displayUrl() const; QString siteName() const; QString title() const; QString description() const; struct Private; protected: Private *d; }; class RemoteFile { public: enum Type { Undefined, Download, Upload }; RemoteFile(); RemoteFile(const RemoteFile &file); ~RemoteFile(); RemoteFile &operator=(const RemoteFile &file); Type type() const; bool isValid() const; QString getUniqueId() const; static RemoteFile fromUniqueId(const QString &uniqueId); QString fileName() const; quint32 size() const; QString md5Sum() const; struct Private; protected: Private *d; }; class DialogInfo { public: DialogInfo(); DialogInfo(const DialogInfo &info); virtual ~DialogInfo(); DialogInfo &operator=(const DialogInfo &info); quint32 unreadCount() const; QString draft() const; quint32 lastMessageId() const; Peer peer() const; quint32 muteUntil() const; bool isStillMuted() const; struct Private; protected: Private *d; }; class UserInfo { public: UserInfo(); UserInfo(const UserInfo &info); ~UserInfo(); UserInfo &operator=(const UserInfo &info); quint32 id() const; QString firstName() const; QString lastName() const; QString userName() const; QString phone() const; TelegramNamespace::ContactStatus status() const; quint32 wasOnline() const; bool isBot() const; bool isSelf() const; bool isContact() const; bool isMutualContact() const; bool isDeleted() const; quint32 botVersion() const; bool getPeerPicture(RemoteFile *file, PeerPictureSize size = PeerPictureSize::Small) const; // See TelegramNamespace::ContactLastOnline enum and a documentation for the contactLastOnline() method in the cpp file. struct Private; protected: Private *d; }; class ChatInfo { public: ChatInfo(); ChatInfo(const ChatInfo &info); ~ChatInfo(); ChatInfo &operator=(const ChatInfo &info); Peer peer() const; QString title() const; quint32 participantsCount() const; quint32 date() const; bool left() const; bool broadcast() const; Peer migratedTo() const; bool getPeerPicture(RemoteFile *file, PeerPictureSize size = PeerPictureSize::Small) const; struct Private; protected: Private *d; }; namespace Utils { QString maskPhoneNumber(const QString &identifier); QStringList maskPhoneNumber(const QStringList &list); template <typename T> T maskPhoneNumber(T container, const QString &key) { if (container.contains(key)) { container.insert(key, maskPhoneNumber(container.value(key).toString())); } return container; } } // Utils namespace } // Telegram namespace Q_DECLARE_METATYPE(Telegram::Peer) Q_DECLARE_METATYPE(Telegram::Peer::Type) Q_DECLARE_METATYPE(Telegram::PeerList) Q_DECLARE_METATYPE(Telegram::DcOption) Q_DECLARE_METATYPE(Telegram::Message) Q_DECLARE_METATYPE(Telegram::ChatInfo) Q_DECLARE_METATYPE(Telegram::RemoteFile) Q_DECLARE_METATYPE(Telegram::UserInfo) Q_DECLARE_TYPEINFO(Telegram::DcOption, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(Telegram::Message, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(Telegram::ChatInfo, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(Telegram::RemoteFile, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(Telegram::UserInfo, Q_MOVABLE_TYPE); Q_DECLARE_OPERATORS_FOR_FLAGS(TelegramNamespace::MessageFlags) Q_DECLARE_OPERATORS_FOR_FLAGS(TelegramNamespace::MessageTypeFlags) #endif // TELEGRAMNAMESPACE_HPP <commit_msg>TelegramNamespace: Expand MessageType type to 16 bit<commit_after>/* Copyright (C) 2014-2017 Alexandr Akulich <akulichalexander@gmail.com> This file is a part of TelegramQt library. 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. */ #ifndef TELEGRAMNAMESPACE_HPP #define TELEGRAMNAMESPACE_HPP #include "telegramqt_global.h" #include <QObject> #include <QFlags> #include <QMetaType> #include <QVector> #ifndef Q_ENUM #define Q_ENUM(x) Q_ENUMS(x) #endif namespace Telegram { TELEGRAMQT_EXPORT QString version(); TELEGRAMQT_EXPORT QString buildVersion(); struct Peer { Q_GADGET Q_PROPERTY(Telegram::Peer::Type type MEMBER type) Q_PROPERTY(quint32 id MEMBER id) public: enum Type { User, Chat, Channel, }; Q_ENUM(Type) Peer(quint32 id = 0, Type t = User) : type(t), id(id) { } Type type; quint32 id; Q_INVOKABLE bool isValid() const { return id; } bool operator==(const Peer &p) const { return (p.id == id) && (p.type == type); } bool operator!=(const Peer &p) const { return (p.id != id) || (p.type != type); } static Peer fromUserId(quint32 id) { return Peer(id, User); } static Peer fromChatId(quint32 id) { return Peer(id, Chat); } static Peer fromChannelId(quint32 id) { return Peer(id, Channel); } QString toString() const; static Peer fromString(const QString &string); }; using PeerList = QVector<Peer>; inline uint qHash(const Peer &key, uint seed) { return ::qHash(static_cast<ulong>(key.id | (static_cast<quint64>(key.type) << (sizeof(key.id) * 8))), seed); } } // Telegram namespace class TELEGRAMQT_EXPORT TelegramNamespace : public QObject { Q_OBJECT public: enum ContactStatus { ContactStatusUnknown, ContactStatusOffline, ContactStatusOnline }; Q_ENUM(ContactStatus) enum MessageFlag { MessageFlagNone = 0x0, MessageFlagRead = 0x1, // Message was read MessageFlagOut = 0x2, // Message is outgoing MessageFlagForwarded = 0x4, MessageFlagIsReply = 0x8, }; Q_ENUM(MessageFlag) Q_DECLARE_FLAGS(MessageFlags, MessageFlag) enum MessageType { MessageTypeUnsupported = 0x0000, MessageTypeText = 0x0001, MessageTypePhoto = 0x0002, MessageTypeAudio = 0x0004, MessageTypeVideo = 0x0008, MessageTypeContact = 0x0010, MessageTypeDocument = 0x0020, MessageTypeGeo = 0x0040, MessageTypeWebPage = 0x0080, MessageTypeAll = 0xffff, }; Q_ENUM(MessageType) Q_DECLARE_FLAGS(MessageTypeFlags, MessageType) enum AuthSignError { AuthSignErrorUnknown, AuthSignErrorAppIdIsInvalid, AuthSignErrorPhoneNumberIsInvalid, AuthSignErrorPhoneNumberIsOccupied, AuthSignErrorPhoneNumberIsUnoccupied, AuthSignErrorPhoneCodeIsInvalid, AuthSignErrorPhoneCodeIsExpired, AuthSignErrorPasswordHashInvalid, AuthSignErrorFirstNameIsInvalid, AuthSignErrorLastNameIsInvalid }; Q_ENUM(AuthSignError) enum UnauthorizedError { UnauthorizedUnknownError, UnauthorizedErrorKeyUnregistered, UnauthorizedErrorKeyInvalid, UnauthorizedErrorUserDeactivated, UnauthorizedErrorUserSessionRevoked, UnauthorizedErrorUserSessionExpired, UnauthorizedErrorActiveUserRequired, UnauthorizedErrorNeedPermanentKey, UnauthorizedSessionPasswordNeeded, }; Q_ENUM(UnauthorizedError) enum UserNameStatus { UserNameStatusUnknown, UserNameStatusIsInvalid, UserNameStatusIsOccupied, UserNameStatusIsNotModified, UserNameStatusCanBeUsed, UserNameStatusCanNotBeUsed, UserNameStatusResolved, UserNameStatusAccepted }; Q_ENUM(UserNameStatus) enum ContactLastOnline { ContactLastOnlineUnknown, ContactLastOnlineRecently, ContactLastOnlineLastWeek, ContactLastOnlineLastMonth, ContactLastOnlineMask = 0xf }; enum MessageAction { MessageActionNone, // Cancel MessageActionTyping, MessageActionRecordVideo, MessageActionRecordAudio, MessageActionUploadVideo, MessageActionUploadAudio, MessageActionUploadPhoto, MessageActionUploadDocument, MessageActionGeoLocation, MessageActionChooseContact }; Q_ENUM(MessageAction) static void registerTypes(); Q_INVOKABLE static Telegram::Peer emptyPeer(); Q_INVOKABLE static Telegram::Peer peerFromChatId(quint32 id); Q_INVOKABLE static Telegram::Peer peerFromChannelId(quint32 id); Q_INVOKABLE static Telegram::Peer peerFromUserId(quint32 id); }; namespace Telegram { void initialize(); struct RsaKey { QByteArray modulus; QByteArray exponent; QByteArray secretExponent; quint64 fingerprint; RsaKey() : fingerprint(0) { } RsaKey(const QByteArray &initialModulus, const QByteArray &initialExponent, const quint64 initialFingersprint = 0) : modulus(initialModulus), exponent(initialExponent), fingerprint(initialFingersprint) { } RsaKey &operator=(const RsaKey &otherKey) { modulus = otherKey.modulus; exponent = otherKey.exponent; secretExponent = otherKey.secretExponent; fingerprint = otherKey.fingerprint; return *this; } void updateFingersprint(); bool isValid() const; void loadFromFile(const QString &fileName); static RsaKey fromFile(const QString &fileName); }; class UserInfo; class RemoteFile; class MessageMediaInfo; enum class PeerPictureSize { Small, Big, }; struct DcOption { enum Flags { Ipv6 = 1 << 0, MediaOnly = 1 << 1, TcpOnly = 1 << 2, Cdn = 1 << 3, IsStatic = 1 << 4, }; DcOption() = default; DcOption(const QString &a, quint16 p, quint32 dcId = 0) : address(a), id(dcId), port(p) { } bool operator==(const DcOption &option) const; bool isValid() const { return id && port && !address.isEmpty(); } QString address; quint32 id = 0; quint16 port = 0; quint16 flags = 0; }; inline bool DcOption::operator==(const DcOption &option) const { return (option.id == id) && (option.port == port) && (option.address == address) && (option.flags == flags); } struct Message { Message() : replyToMessageId(0), forwardContactId(0), id(0), timestamp(0), fwdTimestamp(0), type(TelegramNamespace::MessageTypeUnsupported), flags(TelegramNamespace::MessageFlagNone) { } quint32 fromId; // Telegram user id const Peer peer() const { return m_peer; } void setPeer(const Peer &peer) { m_peer = peer; } const Peer forwardFromPeer() const { return m_forwardPeer; } void setForwardFromPeer(const Peer &peer) { m_forwardPeer = peer; } quint32 replyToMessageId; quint32 forwardContactId; QString text; quint32 id; quint32 timestamp; quint32 fwdTimestamp; TelegramNamespace::MessageType type; TelegramNamespace::MessageFlags flags; private: Peer m_peer; Peer m_forwardPeer; }; class MessageMediaInfo { public: MessageMediaInfo(); MessageMediaInfo(const MessageMediaInfo &info); ~MessageMediaInfo(); MessageMediaInfo &operator=(const MessageMediaInfo &info); void setUploadFile(TelegramNamespace::MessageType type, const RemoteFile &file); bool getRemoteFileInfo(RemoteFile *file) const; TelegramNamespace::MessageType type() const; quint32 size() const; quint32 duration() const; bool setDuration(quint32 duration); QString documentFileName() const; bool setDocumentFileName(const QString &fileName); // Photo, Video QString caption() const; void setCaption(const QString &caption); // Valid for Document and Audio QString mimeType() const; bool setMimeType(const QString &mimeType); // Contact bool getContactInfo(UserInfo *info) const; void setContactInfo(const UserInfo *info); // Valid for GeoPoint and Document/Sticker QString alt() const; // GeoPoint double latitude() const; double longitude() const; void setGeoPoint(double latitude, double longitude); QString url() const; QString displayUrl() const; QString siteName() const; QString title() const; QString description() const; struct Private; protected: Private *d; }; class RemoteFile { public: enum Type { Undefined, Download, Upload }; RemoteFile(); RemoteFile(const RemoteFile &file); ~RemoteFile(); RemoteFile &operator=(const RemoteFile &file); Type type() const; bool isValid() const; QString getUniqueId() const; static RemoteFile fromUniqueId(const QString &uniqueId); QString fileName() const; quint32 size() const; QString md5Sum() const; struct Private; protected: Private *d; }; class DialogInfo { public: DialogInfo(); DialogInfo(const DialogInfo &info); virtual ~DialogInfo(); DialogInfo &operator=(const DialogInfo &info); quint32 unreadCount() const; QString draft() const; quint32 lastMessageId() const; Peer peer() const; quint32 muteUntil() const; bool isStillMuted() const; struct Private; protected: Private *d; }; class UserInfo { public: UserInfo(); UserInfo(const UserInfo &info); ~UserInfo(); UserInfo &operator=(const UserInfo &info); quint32 id() const; QString firstName() const; QString lastName() const; QString userName() const; QString phone() const; TelegramNamespace::ContactStatus status() const; quint32 wasOnline() const; bool isBot() const; bool isSelf() const; bool isContact() const; bool isMutualContact() const; bool isDeleted() const; quint32 botVersion() const; bool getPeerPicture(RemoteFile *file, PeerPictureSize size = PeerPictureSize::Small) const; // See TelegramNamespace::ContactLastOnline enum and a documentation for the contactLastOnline() method in the cpp file. struct Private; protected: Private *d; }; class ChatInfo { public: ChatInfo(); ChatInfo(const ChatInfo &info); ~ChatInfo(); ChatInfo &operator=(const ChatInfo &info); Peer peer() const; QString title() const; quint32 participantsCount() const; quint32 date() const; bool left() const; bool broadcast() const; Peer migratedTo() const; bool getPeerPicture(RemoteFile *file, PeerPictureSize size = PeerPictureSize::Small) const; struct Private; protected: Private *d; }; namespace Utils { QString maskPhoneNumber(const QString &identifier); QStringList maskPhoneNumber(const QStringList &list); template <typename T> T maskPhoneNumber(T container, const QString &key) { if (container.contains(key)) { container.insert(key, maskPhoneNumber(container.value(key).toString())); } return container; } } // Utils namespace } // Telegram namespace Q_DECLARE_METATYPE(Telegram::Peer) Q_DECLARE_METATYPE(Telegram::Peer::Type) Q_DECLARE_METATYPE(Telegram::PeerList) Q_DECLARE_METATYPE(Telegram::DcOption) Q_DECLARE_METATYPE(Telegram::Message) Q_DECLARE_METATYPE(Telegram::ChatInfo) Q_DECLARE_METATYPE(Telegram::RemoteFile) Q_DECLARE_METATYPE(Telegram::UserInfo) Q_DECLARE_TYPEINFO(Telegram::DcOption, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(Telegram::Message, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(Telegram::ChatInfo, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(Telegram::RemoteFile, Q_MOVABLE_TYPE); Q_DECLARE_TYPEINFO(Telegram::UserInfo, Q_MOVABLE_TYPE); Q_DECLARE_OPERATORS_FOR_FLAGS(TelegramNamespace::MessageFlags) Q_DECLARE_OPERATORS_FOR_FLAGS(TelegramNamespace::MessageTypeFlags) #endif // TELEGRAMNAMESPACE_HPP <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "TimeSource.h" #include "Logger.h" #include "Exception.h" #ifdef _WIN32 #include <time.h> #include <sys/timeb.h> #include <windows.h> #include <Mmsystem.h> #else #include <sys/time.h> #include <unistd.h> #include <fcntl.h> #endif #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <iostream> #include <sstream> using namespace std; namespace avg { TimeSource* TimeSource::m_pTimeSource = 0; TimeSource * TimeSource::get() { if (!m_pTimeSource) { #ifdef _WIN32 TIMECAPS tc; UINT wTimerRes; MMRESULT err = timeGetDevCaps(&tc, sizeof(TIMECAPS)); AVG_ASSERT(err == TIMERR_NOERROR); wTimerRes = max(tc.wPeriodMin, 1); timeBeginPeriod(wTimerRes); #endif m_pTimeSource = new TimeSource; } return m_pTimeSource; } TimeSource::TimeSource() { #ifdef __APPLE__ mach_timebase_info(&m_TimebaseInfo); #endif } TimeSource::~TimeSource() { } long long TimeSource::getCurrentMillisecs() { return getCurrentMicrosecs()/1000; } long long TimeSource::getCurrentMicrosecs() { long long ticks; #ifdef _WIN32 ticks = (long long)(timeGetTime())*1000; #else #ifdef __APPLE__ long long systemTime = mach_absolute_time(); ticks = (systemTime * m_TimebaseInfo.numer/m_TimebaseInfo.denom)/1000; #else struct timeval now; gettimeofday(&now, NULL); ticks=((long long)now.tv_sec)*1000000+now.tv_usec; #endif #endif return(ticks); } void TimeSource::sleepUntil(long long targetTime) { long long now = getCurrentMillisecs(); #ifdef __APPLE__ if (targetTime > now) { msleep(targetTime-now); } #else while (now<targetTime) { if (targetTime-now<=2) { msleep(0); } else { msleep(int(targetTime-now-2)); } now = getCurrentMillisecs(); } #endif } void msleep(int millisecs) { #if _WIN32 Sleep(millisecs); #else usleep((long long)(millisecs)*1000); #endif } } <commit_msg>Linux time is now monotonic. Fixes bug #176.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "TimeSource.h" #include "Logger.h" #include "Exception.h" #ifdef _WIN32 #include <time.h> #include <sys/timeb.h> #include <windows.h> #include <Mmsystem.h> #else #include <sys/time.h> #endif #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <assert.h> #include <iostream> #include <sstream> using namespace std; namespace avg { TimeSource* TimeSource::m_pTimeSource = 0; TimeSource * TimeSource::get() { if (!m_pTimeSource) { #ifdef _WIN32 TIMECAPS tc; UINT wTimerRes; MMRESULT err = timeGetDevCaps(&tc, sizeof(TIMECAPS)); AVG_ASSERT(err == TIMERR_NOERROR); wTimerRes = max(tc.wPeriodMin, 1); timeBeginPeriod(wTimerRes); #endif m_pTimeSource = new TimeSource; } return m_pTimeSource; } TimeSource::TimeSource() { #ifdef __APPLE__ mach_timebase_info(&m_TimebaseInfo); #endif } TimeSource::~TimeSource() { } long long TimeSource::getCurrentMillisecs() { return getCurrentMicrosecs()/1000; } long long TimeSource::getCurrentMicrosecs() { #ifdef _WIN32 return (long long)(timeGetTime())*1000; #else #ifdef __APPLE__ long long systemTime = mach_absolute_time(); return (systemTime * m_TimebaseInfo.numer/m_TimebaseInfo.denom)/1000; #else struct timespec now; int rc = clock_gettime(CLOCK_MONOTONIC, &now); assert(rc == 0); return ((long long)now.tv_sec)*1000000+now.tv_nsec/1000; #endif #endif } void TimeSource::sleepUntil(long long targetTime) { long long now = getCurrentMillisecs(); #ifdef __APPLE__ if (targetTime > now) { msleep(targetTime-now); } #else while (now<targetTime) { if (targetTime-now<=2) { msleep(0); } else { msleep(int(targetTime-now-2)); } now = getCurrentMillisecs(); } #endif } void msleep(int millisecs) { #if _WIN32 Sleep(millisecs); #else usleep((long long)(millisecs)*1000); #endif } } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android Open Source Project * * 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 <stddef.h> #include <stdint.h> #include "perfetto/base/utils.h" #include "src/ipc/buffered_frame_deserializer.h" #include "src/ipc/wire_protocol.pb.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { perfetto::ipc::BufferedFrameDeserializer bfd; auto rbuf = bfd.BeginReceive(); memcpy(rbuf.data, data, std::min(rbuf.size, size)); ::perfetto::base::ignore_result(bfd.EndReceive(size)); // TODO(fmayer): Determine if this has value. // This slows down fuzzing from 190k / s to 140k / sec. while (bfd.PopNextFrame() != nullptr) { } return 0; } <commit_msg>fuzzing: Consume everything in buffered_frame_deserialzier. am: ca5569f2c9 am: 292082487b<commit_after>/* * Copyright (C) 2017 The Android Open Source Project * * 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 <stddef.h> #include <stdint.h> #include "perfetto/base/utils.h" #include "src/ipc/buffered_frame_deserializer.h" #include "src/ipc/wire_protocol.pb.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { perfetto::ipc::BufferedFrameDeserializer bfd; size_t write_offset = 0; while (write_offset < size) { size_t available_size = size - write_offset; auto rbuf = bfd.BeginReceive(); size_t chunk_size = std::min(available_size, rbuf.size); memcpy(rbuf.data, data, chunk_size); if (!bfd.EndReceive(chunk_size)) break; write_offset += chunk_size; } return 0; } <|endoftext|>
<commit_before>/******************************************************* * Simple arrayfire matrix multiply example ********************************************************/ #include <arrayfire.h> #include <cstdio> #include <cstdlib> #include <Windows.h> // For GetTickCount() using namespace af; // Borrow simple Matrix facility from the companion raw CUDA implementation. // Matrices are stored in row-major order: // M(row, col) = *(M.elements + row * M.width + col) // Conveniently Arrayfire 2 dimensional arrays use the same storage, layout // which we leverage later as arrayfire doesn't provide good facilities for // accessing single elements. struct Matrix { int width; int height; int stride; float* elements; void alloc( int height_p, int width_p ) { height = height_p; width = width_p; elements = (float*)malloc(width * height * sizeof(float)); if( !elements ) { printf( "Panic: memory allocation error" ); exit(-1); } } void free() { ::free(elements); } // Initialise to a known pattern for reproducability void init() { for( int i=0; i<height; i++ ) for( int j=0; j<width; j++ ) elements[i*width + j] = (float)(i+j); } }; // Prototypes void CpuMatMul( const Matrix &A, const Matrix &B, Matrix &C ); // For simplicity, do square DIMxDIM matrices, only const int DIM=512; // min 16 for shared, max 512 // Arrayfire multiplicands static array M(DIM,DIM); static array N(DIM,DIM); // Get ready for tests void af_test_init() { printf( "size of M(%d,%d) = %d bytes, %f bytes per element\n", DIM, DIM, N.bytes(), ((float)N.bytes())/(DIM*DIM) ); // Initialising the arrayfire array like this works but is *extremely* slow, presumably because copying // individual elements to GPU memory is slow /* for(int i=0; i<DIM; i++) { for(int j=0; j<DIM; j++) { M(i,j) = (i+j); // in Arrayfire M(i,j) works as a LHS expression but not a RHS expression (!?) N(i,j) = (i+j); } } */ // So instead take advantage of the fact that the memory layout of a two dimensional arrayfire array is the same // as our simple Matrix convention Matrix src; src.alloc(DIM,DIM); src.init(); M.write(src.elements,M.bytes()); // This is the rather sad and poorly documented way to do a host->device transfer in Arrayfire N.write(src.elements,N.bytes()); src.free(); } // Make sure the matrix multiplication works at least once bool af_test_verify( Matrix &reference ) { bool ok=true; int idx=0; array A = matmul(M, N); // matrix multiply float *host_a = A.host<float>(); // must call af::freeHost() later for( int row=0; ok && row<DIM; row++ ) { for( int col=0; ok && col<DIM; col++ ) { float value1 = host_a[idx++]; float value2 = reference.elements[row * reference.width + col]; float delta = value1>=value2 ? value1-value2 : value2-value1; ok = delta < (value1/100000.0); //1000000000.0); // don't insist on bitwise float equality // Note that I've changed the demand for relative error // to be better than 1e-5 when previously I had 1e-9. This // was necessary to get a successful verification on the CPU // backend. This requires further study. See *NB* for more. if( !ok ) printf( "Verify error: element[%d][%d], value1=%f, value2=%f, delta=%f\n", row, col, value1, value2, delta ); if( row==0 && col==0 ) printf( "element[0][0] = %f (calc), %f (ref)\n", value1, value2 ); else if( row+1==DIM && col+1==DIM ) printf( "element[DIM-1][DIM-1] = %f (calc), %f (ref)\n", value1, value2 ); /* *NB* On the CUDA backend, we get, as expected element[0][0] = 44608184.000000 (calc), 44608184.000000 (ref) element[DIM-1][DIM-1] = 311995968.000000 (calc), 311995968.000000 (ref) But on the CPU backend we get element[0][0] = 44608204.000000 (calc), 44608184.000000 (ref) element[DIM-1][DIM-1] = 311995904.000000 (calc), 311995968.000000 (ref) As discussed above, this was the motivation for reducing the relative error acceptance threshold. For further study, I suspect either an out and out bug in Arrayfire, or perhaps reduced precision in the CPU backend for some reason. */ } } af::freeHost(host_a); return ok; } // One matrix multiply, for timing test void af_test_for_timing() { array B = matmul(M, N); // matrix multiply B.eval(); // ensure evaluated } int main() { try { // Select a device and display arrayfire info int device = 0; af::setDevice(device); // Print information about backend implementation af::info(); // Allocate the matrixes and init A and B to known values Matrix A, B, C; A.alloc( DIM, DIM ); A.init(); B.alloc( DIM, DIM ); B.init(); C.alloc( DIM, DIM ); // Initialise ArrayFire test printf( "Initialising array fire timing test\n" ); af_test_init(); // Use arrayfire timing facilities double af_time = timeit(af_test_for_timing); // time in seconds printf( "Arrayfire native GPU timing %.2f millisecs\n", af_time*1000 ); // Verify that array fire does the matrix multiply correctly once printf( "Verify that array fire does the matrix multiply correctly once\n" ); CpuMatMul(A, B, C); bool ok = af_test_verify(C); printf( "Verify %s\n", ok?"successful":"not successful" ); // Loop until satisfied with timing bool do_cpu=true; bool do_gpu=true; unsigned int ntimes_cpu=1; unsigned int ntimes_gpu=1; unsigned int time_cpu = 0; unsigned int time_gpu = 0; for(;;) { // Time Naive CPU multiplication unsigned int time_cpu_1 = GetTickCount(); for( unsigned int i=0; do_cpu && i<ntimes_cpu; i++ ) CpuMatMul(A, B, C); unsigned int time_cpu_2 = GetTickCount(); // Time arrayfire GPU implementation unsigned int time_gpu_1 = GetTickCount(); for( unsigned int i=0; do_gpu && i<ntimes_gpu; i++ ) af_test_for_timing(); unsigned int time_gpu_2 = GetTickCount(); // Report on timing if( do_cpu ) { time_cpu = time_cpu_2-time_cpu_1; if( ntimes_cpu == 1 ) printf( "CPU time %u milliseconds\n", time_cpu ); else printf( "CPU time %.2f milliseconds (per iteration, %u iterations, %u ms total)\n", ((float)time_cpu)/ntimes_cpu, ntimes_cpu, time_cpu ); } if( do_gpu ) { time_gpu = time_gpu_2-time_gpu_1; if( ntimes_gpu == 1 ) printf( "GPU time %u milliseconds\n", time_gpu ); else printf( "GPU time %.2f milliseconds (per iteration, %u iterations, %u ms total)\n", ((float)time_gpu)/ntimes_gpu, ntimes_gpu, time_gpu ); } // If necessary, repeat with looping to increase timing accuracy const unsigned int min_time_ms = 1000; if( do_cpu && time_cpu<min_time_ms ) ntimes_cpu *= 4; else do_cpu = false; if( do_gpu && time_gpu<min_time_ms ) ntimes_gpu *= 4; else do_gpu = false; if( do_cpu || do_gpu ) printf( "\nRepeating with more loops, to improve timing accuracy\n" ); else break; } printf( "\nTiming summary:\n" ); printf( "Naive CPU time %.2f milliseconds\n", ((float)time_cpu)/ntimes_cpu ); printf( "Arrayfire GPU time %.2f milliseconds\n", ((float)time_gpu)/ntimes_gpu ); printf( "For comparison, arrayfire GPU time using arrayfire hi-res timer %.2f millisecs\n", af_time*1000 ); // Free in reverse order to alloc() C.free(); B.free(); A.free(); } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); throw; } } // Naive but reliable and simple matrix multiplication - for reference void CpuMatMul( const Matrix &A, const Matrix &B, Matrix &C ) { for( int row=0; row<A.height; row++ ) { for( int col=0; col<A.width; col++ ) { float value=0; for( int e=0; e<A.width; ++e ) value += (A.elements[row * A.width + e]) * (B.elements[e * B.width + col]); C.elements[row * C.width + col] = value; } } } <commit_msg>Improve floating point precision comment<commit_after>/******************************************************* * Simple arrayfire matrix multiply example ********************************************************/ #include <arrayfire.h> #include <cstdio> #include <cstdlib> #include <Windows.h> // For GetTickCount() using namespace af; // Borrow simple Matrix facility from the companion raw CUDA implementation. // Matrices are stored in row-major order: // M(row, col) = *(M.elements + row * M.width + col) // Conveniently Arrayfire 2 dimensional arrays use the same storage, layout // which we leverage later as arrayfire doesn't provide good facilities for // accessing single elements. struct Matrix { int width; int height; int stride; float* elements; void alloc( int height_p, int width_p ) { height = height_p; width = width_p; elements = (float*)malloc(width * height * sizeof(float)); if( !elements ) { printf( "Panic: memory allocation error" ); exit(-1); } } void free() { ::free(elements); } // Initialise to a known pattern for reproducability void init() { for( int i=0; i<height; i++ ) for( int j=0; j<width; j++ ) elements[i*width + j] = (float)(i+j); } }; // Prototypes void CpuMatMul( const Matrix &A, const Matrix &B, Matrix &C ); // For simplicity, do square DIMxDIM matrices, only const int DIM=512; // min 16 for shared, max 512 // Arrayfire multiplicands static array M(DIM,DIM); static array N(DIM,DIM); // Get ready for tests void af_test_init() { printf( "size of M(%d,%d) = %d bytes, %f bytes per element\n", DIM, DIM, N.bytes(), ((float)N.bytes())/(DIM*DIM) ); // Initialising the arrayfire array like this works but is *extremely* slow, presumably because copying // individual elements to GPU memory is slow /* for(int i=0; i<DIM; i++) { for(int j=0; j<DIM; j++) { M(i,j) = (i+j); // in Arrayfire M(i,j) works as a LHS expression but not a RHS expression (!?) N(i,j) = (i+j); } } */ // So instead take advantage of the fact that the memory layout of a two dimensional arrayfire array is the same // as our simple Matrix convention Matrix src; src.alloc(DIM,DIM); src.init(); M.write(src.elements,M.bytes()); // This is the rather sad and poorly documented way to do a host->device transfer in Arrayfire N.write(src.elements,N.bytes()); src.free(); } // Make sure the matrix multiplication works at least once bool af_test_verify( Matrix &reference ) { bool ok=true; int idx=0; array A = matmul(M, N); // matrix multiply float *host_a = A.host<float>(); // must call af::freeHost() later for( int row=0; ok && row<DIM; row++ ) { for( int col=0; ok && col<DIM; col++ ) { float value1 = host_a[idx++]; float value2 = reference.elements[row * reference.width + col]; float delta = value1>=value2 ? value1-value2 : value2-value1; ok = delta < (value1/100000.0); //1000000000.0); // don't insist on bitwise float equality // Note that I've changed the demand for relative error // to be better than 1e-5 when previously I had 1e-9. This // was necessary to get a successful verification on the CPU // backend. See *NB* for explanation. if( !ok ) printf( "Verify error: element[%d][%d], value1=%f, value2=%f, delta=%f\n", row, col, value1, value2, delta ); if( row==0 && col==0 ) printf( "element[0][0] = %f (calc), %f (ref)\n", value1, value2 ); else if( row+1==DIM && col+1==DIM ) printf( "element[DIM-1][DIM-1] = %f (calc), %f (ref)\n", value1, value2 ); /* *NB* On the CUDA backend, we get, as expected element[0][0] = 44608184.000000 (calc), 44608184.000000 (ref) element[DIM-1][DIM-1] = 311995968.000000 (calc), 311995968.000000 (ref) But on the CPU backend we get element[0][0] = 44608204.000000 (calc), 44608184.000000 (ref) element[DIM-1][DIM-1] = 311995904.000000 (calc), 311995968.000000 (ref) What's going on here is that 32 bit floats have insufficient precision for getting this calculation exactly right, and in fact both backends are getting a (slightly) wrong answer. Integer arithmetic would give us the right numbers; element[0][0] = 44608256 element[DIM-1][DIM-1] = 311996160 There's a little more discussion in README.md */ } } af::freeHost(host_a); return ok; } // One matrix multiply, for timing test void af_test_for_timing() { array B = matmul(M, N); // matrix multiply B.eval(); // ensure evaluated } int main() { try { // Select a device and display arrayfire info int device = 0; af::setDevice(device); // Print information about backend implementation af::info(); // Allocate the matrixes and init A and B to known values Matrix A, B, C; A.alloc( DIM, DIM ); A.init(); B.alloc( DIM, DIM ); B.init(); C.alloc( DIM, DIM ); // Initialise ArrayFire test printf( "Initialising array fire timing test\n" ); af_test_init(); // Use arrayfire timing facilities double af_time = timeit(af_test_for_timing); // time in seconds printf( "Arrayfire native GPU timing %.2f millisecs\n", af_time*1000 ); // Verify that array fire does the matrix multiply correctly once printf( "Verify that array fire does the matrix multiply correctly once\n" ); CpuMatMul(A, B, C); bool ok = af_test_verify(C); printf( "Verify %s\n", ok?"successful":"not successful" ); // Loop until satisfied with timing bool do_cpu=true; bool do_gpu=true; unsigned int ntimes_cpu=1; unsigned int ntimes_gpu=1; unsigned int time_cpu = 0; unsigned int time_gpu = 0; for(;;) { // Time Naive CPU multiplication unsigned int time_cpu_1 = GetTickCount(); for( unsigned int i=0; do_cpu && i<ntimes_cpu; i++ ) CpuMatMul(A, B, C); unsigned int time_cpu_2 = GetTickCount(); // Time arrayfire GPU implementation unsigned int time_gpu_1 = GetTickCount(); for( unsigned int i=0; do_gpu && i<ntimes_gpu; i++ ) af_test_for_timing(); unsigned int time_gpu_2 = GetTickCount(); // Report on timing if( do_cpu ) { time_cpu = time_cpu_2-time_cpu_1; if( ntimes_cpu == 1 ) printf( "CPU time %u milliseconds\n", time_cpu ); else printf( "CPU time %.2f milliseconds (per iteration, %u iterations, %u ms total)\n", ((float)time_cpu)/ntimes_cpu, ntimes_cpu, time_cpu ); } if( do_gpu ) { time_gpu = time_gpu_2-time_gpu_1; if( ntimes_gpu == 1 ) printf( "GPU time %u milliseconds\n", time_gpu ); else printf( "GPU time %.2f milliseconds (per iteration, %u iterations, %u ms total)\n", ((float)time_gpu)/ntimes_gpu, ntimes_gpu, time_gpu ); } // If necessary, repeat with looping to increase timing accuracy const unsigned int min_time_ms = 1000; if( do_cpu && time_cpu<min_time_ms ) ntimes_cpu *= 4; else do_cpu = false; if( do_gpu && time_gpu<min_time_ms ) ntimes_gpu *= 4; else do_gpu = false; if( do_cpu || do_gpu ) printf( "\nRepeating with more loops, to improve timing accuracy\n" ); else break; } printf( "\nTiming summary:\n" ); printf( "Naive CPU time %.2f milliseconds\n", ((float)time_cpu)/ntimes_cpu ); printf( "Arrayfire GPU time %.2f milliseconds\n", ((float)time_gpu)/ntimes_gpu ); printf( "For comparison, arrayfire GPU time using arrayfire hi-res timer %.2f millisecs\n", af_time*1000 ); // Free in reverse order to alloc() C.free(); B.free(); A.free(); } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); throw; } } // Naive but reliable and simple matrix multiplication - for reference void CpuMatMul( const Matrix &A, const Matrix &B, Matrix &C ) { for( int row=0; row<A.height; row++ ) { for( int col=0; col<A.width; col++ ) { float value=0; for( int e=0; e<A.width; ++e ) value += (A.elements[row * A.width + e]) * (B.elements[e * B.width + col]); C.elements[row * C.width + col] = value; } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 Daniel Nicoletti <dantti12@gmail.com> * * 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 "dispatcher_p.h" #include "common.h" #include "context.h" #include "controller.h" #include "action.h" #include "request_p.h" #include "dispatchtypepath.h" #include <QUrl> #include <QMetaMethod> #include <QStringBuilder> #include <QDebug> using namespace Cutelyst; Dispatcher::Dispatcher(QObject *parent) : QObject(parent), d_ptr(new DispatcherPrivate) { } Dispatcher::~Dispatcher() { delete d_ptr; } void Dispatcher::setupActions(const QList<Controller*> &controllers) { Q_D(Dispatcher); if (d->dispatchers.isEmpty()) { registerDispatchType(new DispatchTypePath(this)); } ActionList registeredActions; Q_FOREACH (Controller *controller, controllers) { bool instanceUsed = false; Q_FOREACH (Action *action, controller->actions()) { bool registered = false; if (action->isValid() && !d->actionHash.contains(action->privateName())) { if (!action->attributes().contains("Private")) { // Register the action with each dispatcher Q_FOREACH (DispatchType *dispatch, d->dispatchers) { if (dispatch->registerAction(action)) { registered = true; } } } else { // We register private actions registered = true; } } // The Begin, Auto, End actions are not // registered by Dispatchers but we need them // as private actions anyway if (registered) { d->actionHash.insert(action->privateName(), action); d->containerHash[action->ns()] << action; registeredActions.append(action); instanceUsed = true; } else if (action->name() != "_DISPATCH" && action->name() != "_BEGIN" && action->name() != "_AUTO" && action->name() != "_ACTION" && action->name() != "_END") { qCDebug(CUTELYST_DISPATCHER) << "The action" << action->name() << "of" << action->controller()->objectName() << "controller was not registered in any dispatcher." " If you still want to access it internally (via actionFor())" " you may make it's method private."; } else if (d->showInternalActions) { qCDebug(CUTELYST_DISPATCHER) << "The action" << action->name() << "of" << action->controller()->objectName() << "controller was alread registered by the" << d->actionHash.value(action->privateName())->controller()->objectName() << "controller."; } } if (instanceUsed) { d->constrollerHash.insert(controller->objectName().toLatin1(), controller); } } // Cache root actions, BEFORE the controllers set them d->rootActions = d->containerHash.value(""); Q_FOREACH (Controller *controller, controllers) { controller->setupActions(this); } Q_FOREACH (Action *action, registeredActions) { action->dispatcherReady(this); } qCDebug(CUTELYST_DISPATCHER) << endl << printActions().data() << endl; } bool Dispatcher::dispatch(Context *ctx) { if (ctx->action()) { QByteArray action = ctx->ns(); action.reserve(action.size() + 12); action.prepend('/'); action.append("/_DISPATCH", 10); return forward(ctx, action); } else { const QString &path = ctx->req()->path(); if (path.isEmpty()) { ctx->error(tr("No default action defined")); } else { ctx->error(tr("Unknown resource \"%1\".").arg(path)); }; } return false; } bool Dispatcher::forward(Context *ctx, const Action *action, const QStringList &arguments) { Q_ASSERT(action); return action->dispatch(ctx); } bool Dispatcher::forward(Context *ctx, const QByteArray &opname, const QStringList &arguments) { const Action *action = command2Action(ctx, opname); if (action) { return action->dispatch(ctx); } qCCritical(CUTELYST_DISPATCHER) << "Action not found" << action; return false; } void Dispatcher::prepareAction(Context *ctx) { Q_D(Dispatcher); Request *request = ctx->request(); QByteArray path = request->path(); QList<QByteArray> pathParts = path.split('/'); QStringList args; int pos = path.size(); QByteArray actionPath; // "/foo/bar" // "/foo/" skip // "/foo" // "/" do { actionPath = path.mid(1, pos); Q_FOREACH (DispatchType *type, d->dispatchers) { if (type->match(ctx, actionPath, args)) { request->d_ptr->args = args; if (!request->match().isEmpty()) { qCDebug(CUTELYST_DISPATCHER) << "Path is" << request->match(); } if (!args.isEmpty()) { qCDebug(CUTELYST_DISPATCHER) << "Arguments are" << args.join(QLatin1Char('/')); } return; } } // leave the loop if we are at the root "/" if (pos <= 1) { break; } pos = path.lastIndexOf('/', pos); if (pos != 0) { // Remove trailing '/' --pos; } args.prepend(QUrl::fromPercentEncoding(pathParts.takeLast())); } while (pos != -2); } const Action *Dispatcher::getAction(const QByteArray &name, const QByteArray &nameSpace) const { Q_D(const Dispatcher); if (name.isEmpty()) { return 0; } QByteArray action = cleanNamespace(nameSpace); action.reserve(action.size() + name.size() + 1); action.append('/'); action.append(name); return d->actionHash.value(action); } const Action *Dispatcher::getActionByPath(const QByteArray &path) const { Q_D(const Dispatcher); QByteArray _path = path; if (!_path.startsWith('/')) { _path.prepend('/'); } return d->actionHash.value(_path); } ActionList Dispatcher::getActions(const QByteArray &name, const QByteArray &nameSpace) const { Q_D(const Dispatcher); ActionList ret; if (name.isEmpty()) { return ret; } QByteArray _ns = cleanNamespace(nameSpace); ActionList containers = d->getContainers(_ns); Q_FOREACH (Action *action, containers) { if (action->name() == name) { ret.prepend(action); } } return ret; } QHash<QByteArray, Controller *> Dispatcher::controllers() const { Q_D(const Dispatcher); return d->constrollerHash; } QByteArray Dispatcher::uriForAction(const Action *action, const QStringList &captures) const { Q_D(const Dispatcher); Q_FOREACH (DispatchType *dispatch, d->dispatchers) { QByteArray uri = dispatch->uriForAction(action, captures); if (!uri.isNull()) { return uri.isEmpty() ? QByteArray("/", 1) : uri; } } return QByteArray(); } void Dispatcher::registerDispatchType(DispatchType *dispatchType) { Q_D(Dispatcher); d->dispatchers.append(dispatchType); } QByteArray Dispatcher::printActions() { Q_D(Dispatcher); QByteArray buffer; QTextStream out(&buffer, QIODevice::WriteOnly); out << "Loaded Private actions:" << endl; QByteArray privateTitle("Private"); QByteArray classTitle("Class"); QByteArray methodTitle("Method"); int privateLength = privateTitle.length(); int classLength = classTitle.length(); int actionLength = methodTitle.length(); QHash<QByteArray, Action*>::ConstIterator it = d->actionHash.constBegin(); while (it != d->actionHash.constEnd()) { Action *action = it.value(); if (d->showInternalActions || !action->name().startsWith('_')) { QByteArray path = it.key(); if (!path.startsWith('/')) { path.prepend('/'); } privateLength = qMax(privateLength, path.length()); classLength = qMax(classLength, action->className().length()); actionLength = qMax(actionLength, action->name().length()); } ++it; } out << "." << QString().fill(QLatin1Char('-'), privateLength + 2).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), classLength + 2).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), actionLength + 2).toUtf8().data() << "." << endl; out << "| " << privateTitle.leftJustified(privateLength).data() << " | " << classTitle.leftJustified(classLength).data() << " | " << methodTitle.leftJustified(actionLength).data() << " |" << endl; out << "." << QByteArray().fill('-', privateLength + 2).data() << "+" << QByteArray().fill('-', classLength + 2).data() << "+" << QByteArray().fill('-', actionLength + 2).data() << "." << endl; QList<QByteArray> keys = d->actionHash.keys(); qSort(keys.begin(), keys.end()); Q_FOREACH (const QByteArray &key, keys) { Action *action = d->actionHash.value(key); if (d->showInternalActions || !action->name().startsWith('_')) { QByteArray path = key; if (!path.startsWith('/')) { path.prepend('/'); } out << "| " << path.leftJustified(privateLength).data() << " | " << action->className().leftJustified(classLength).data() << " | " << action->name().leftJustified(actionLength).data() << " |" << endl; } } out << "." << QByteArray().fill('-', privateLength + 2).data() << "+" << QByteArray().fill('-', classLength + 2).data() << "+" << QByteArray().fill('-', actionLength + 2).data() << "." << endl; // List all public actions Q_FOREACH (DispatchType *dispatch, d->dispatchers) { out << endl << dispatch->list(); } return buffer; } const Action *Dispatcher::command2Action(Context *ctx, const QByteArray &command, const QStringList &extraParams) { Q_D(Dispatcher); // qDebug() << Q_FUNC_INFO << "Command" << command; const Action *ret = d->actionHash.value(command); if (!ret) { ret = invokeAsPath(ctx, command, ctx->args()); } return ret; } QByteArray Dispatcher::actionRel2Abs(Context *ctx, const QByteArray &path) { QByteArray ret = path; if (!ret.startsWith('/')) { // TODO at Catalyst it uses // c->stack->last()->namespace ret.prepend('/'); ret.prepend(ctx->action()->ns()); } if (ret.startsWith('/')) { ret.remove(0, 1); } return ret; } const Action *Dispatcher::invokeAsPath(Context *ctx, const QByteArray &relativePath, const QStringList &args) { const Action *ret; QByteArray path = actionRel2Abs(ctx, relativePath); int pos = path.lastIndexOf('/'); int lastPos = path.size(); do { if (pos == -1) { ret = getAction(path, QByteArray()); if (ret) { return ret; } } else { QByteArray name = path.mid(pos + 1, lastPos); path = path.mid(0, pos); ret = getAction(name, path); if (ret) { return ret; } } lastPos = pos; pos = path.indexOf('/', pos - 1); } while (pos != -1); return 0; } QByteArray Dispatcher::cleanNamespace(const QByteArray &ns) const { QByteArray ret = ns; bool lastWasSlash = true; // remove initial slash int nsSize = ns.size(); const char * data = ret.constData(); for (int i = 0; i < nsSize; ++i) { if (data[i] == '/') { if (lastWasSlash) { ret.remove(i, 1); data = ret.constData(); --nsSize; } else { lastWasSlash = true; } } else { lastWasSlash = false; } } return ret; } ActionList DispatcherPrivate::getContainers(const QByteArray &ns) const { ActionList ret; if (ns != "/") { int pos = ns.size(); // qDebug() << pos << ns.mid(0, pos); while (pos > 0) { // qDebug() << pos << ns.mid(0, pos); ret.append(containerHash.value(ns.mid(0, pos))); pos = ns.lastIndexOf('/', pos - 1); } } // qDebug() << containerHash.size() << rootActions; ret.append(rootActions); return ret; } <commit_msg>Internal actions don't start with / remove it from the getActionByPath<commit_after>/* * Copyright (C) 2013 Daniel Nicoletti <dantti12@gmail.com> * * 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 "dispatcher_p.h" #include "common.h" #include "context.h" #include "controller.h" #include "action.h" #include "request_p.h" #include "dispatchtypepath.h" #include <QUrl> #include <QMetaMethod> #include <QStringBuilder> #include <QDebug> using namespace Cutelyst; Dispatcher::Dispatcher(QObject *parent) : QObject(parent), d_ptr(new DispatcherPrivate) { } Dispatcher::~Dispatcher() { delete d_ptr; } void Dispatcher::setupActions(const QList<Controller*> &controllers) { Q_D(Dispatcher); if (d->dispatchers.isEmpty()) { registerDispatchType(new DispatchTypePath(this)); } ActionList registeredActions; Q_FOREACH (Controller *controller, controllers) { bool instanceUsed = false; Q_FOREACH (Action *action, controller->actions()) { bool registered = false; if (action->isValid() && !d->actionHash.contains(action->privateName())) { if (!action->attributes().contains("Private")) { // Register the action with each dispatcher Q_FOREACH (DispatchType *dispatch, d->dispatchers) { if (dispatch->registerAction(action)) { registered = true; } } } else { // We register private actions registered = true; } } // The Begin, Auto, End actions are not // registered by Dispatchers but we need them // as private actions anyway if (registered) { d->actionHash.insert(action->privateName(), action); d->containerHash[action->ns()] << action; registeredActions.append(action); instanceUsed = true; } else if (action->name() != "_DISPATCH" && action->name() != "_BEGIN" && action->name() != "_AUTO" && action->name() != "_ACTION" && action->name() != "_END") { qCDebug(CUTELYST_DISPATCHER) << "The action" << action->name() << "of" << action->controller()->objectName() << "controller was not registered in any dispatcher." " If you still want to access it internally (via actionFor())" " you may make it's method private."; } else if (d->showInternalActions) { qCDebug(CUTELYST_DISPATCHER) << "The action" << action->name() << "of" << action->controller()->objectName() << "controller was alread registered by the" << d->actionHash.value(action->privateName())->controller()->objectName() << "controller."; } } if (instanceUsed) { d->constrollerHash.insert(controller->objectName().toLatin1(), controller); } } // Cache root actions, BEFORE the controllers set them d->rootActions = d->containerHash.value(""); Q_FOREACH (Controller *controller, controllers) { controller->setupActions(this); } Q_FOREACH (Action *action, registeredActions) { action->dispatcherReady(this); } qCDebug(CUTELYST_DISPATCHER) << endl << printActions().data() << endl; } bool Dispatcher::dispatch(Context *ctx) { if (ctx->action()) { QByteArray action = ctx->ns(); action.reserve(action.size() + 12); action.prepend('/'); action.append("/_DISPATCH", 10); return forward(ctx, action); } else { const QString &path = ctx->req()->path(); if (path.isEmpty()) { ctx->error(tr("No default action defined")); } else { ctx->error(tr("Unknown resource \"%1\".").arg(path)); }; } return false; } bool Dispatcher::forward(Context *ctx, const Action *action, const QStringList &arguments) { Q_ASSERT(action); return action->dispatch(ctx); } bool Dispatcher::forward(Context *ctx, const QByteArray &opname, const QStringList &arguments) { const Action *action = command2Action(ctx, opname); if (action) { return action->dispatch(ctx); } qCCritical(CUTELYST_DISPATCHER) << "Action not found" << action; return false; } void Dispatcher::prepareAction(Context *ctx) { Q_D(Dispatcher); Request *request = ctx->request(); QByteArray path = request->path(); QList<QByteArray> pathParts = path.split('/'); QStringList args; int pos = path.size(); QByteArray actionPath; // "/foo/bar" // "/foo/" skip // "/foo" // "/" do { actionPath = path.mid(1, pos); Q_FOREACH (DispatchType *type, d->dispatchers) { if (type->match(ctx, actionPath, args)) { request->d_ptr->args = args; if (!request->match().isEmpty()) { qCDebug(CUTELYST_DISPATCHER) << "Path is" << request->match(); } if (!args.isEmpty()) { qCDebug(CUTELYST_DISPATCHER) << "Arguments are" << args.join(QLatin1Char('/')); } return; } } // leave the loop if we are at the root "/" if (pos <= 1) { break; } pos = path.lastIndexOf('/', pos); if (pos != 0) { // Remove trailing '/' --pos; } args.prepend(QUrl::fromPercentEncoding(pathParts.takeLast())); } while (pos != -2); } const Action *Dispatcher::getAction(const QByteArray &name, const QByteArray &nameSpace) const { Q_D(const Dispatcher); if (name.isEmpty()) { return 0; } QByteArray action = cleanNamespace(nameSpace); action.reserve(action.size() + name.size() + 1); action.append('/'); action.append(name); return d->actionHash.value(action); } const Action *Dispatcher::getActionByPath(const QByteArray &path) const { Q_D(const Dispatcher); QByteArray _path = path; if (_path.startsWith('/')) { _path.remove(0, 1); } return d->actionHash.value(_path); } ActionList Dispatcher::getActions(const QByteArray &name, const QByteArray &nameSpace) const { Q_D(const Dispatcher); ActionList ret; if (name.isEmpty()) { return ret; } QByteArray _ns = cleanNamespace(nameSpace); ActionList containers = d->getContainers(_ns); Q_FOREACH (Action *action, containers) { if (action->name() == name) { ret.prepend(action); } } return ret; } QHash<QByteArray, Controller *> Dispatcher::controllers() const { Q_D(const Dispatcher); return d->constrollerHash; } QByteArray Dispatcher::uriForAction(const Action *action, const QStringList &captures) const { Q_D(const Dispatcher); Q_FOREACH (DispatchType *dispatch, d->dispatchers) { QByteArray uri = dispatch->uriForAction(action, captures); if (!uri.isNull()) { return uri.isEmpty() ? QByteArray("/", 1) : uri; } } return QByteArray(); } void Dispatcher::registerDispatchType(DispatchType *dispatchType) { Q_D(Dispatcher); d->dispatchers.append(dispatchType); } QByteArray Dispatcher::printActions() { Q_D(Dispatcher); QByteArray buffer; QTextStream out(&buffer, QIODevice::WriteOnly); out << "Loaded Private actions:" << endl; QByteArray privateTitle("Private"); QByteArray classTitle("Class"); QByteArray methodTitle("Method"); int privateLength = privateTitle.length(); int classLength = classTitle.length(); int actionLength = methodTitle.length(); QHash<QByteArray, Action*>::ConstIterator it = d->actionHash.constBegin(); while (it != d->actionHash.constEnd()) { Action *action = it.value(); if (d->showInternalActions || !action->name().startsWith('_')) { QByteArray path = it.key(); if (!path.startsWith('/')) { path.prepend('/'); } privateLength = qMax(privateLength, path.length()); classLength = qMax(classLength, action->className().length()); actionLength = qMax(actionLength, action->name().length()); } ++it; } out << "." << QString().fill(QLatin1Char('-'), privateLength + 2).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), classLength + 2).toUtf8().data() << "+" << QString().fill(QLatin1Char('-'), actionLength + 2).toUtf8().data() << "." << endl; out << "| " << privateTitle.leftJustified(privateLength).data() << " | " << classTitle.leftJustified(classLength).data() << " | " << methodTitle.leftJustified(actionLength).data() << " |" << endl; out << "." << QByteArray().fill('-', privateLength + 2).data() << "+" << QByteArray().fill('-', classLength + 2).data() << "+" << QByteArray().fill('-', actionLength + 2).data() << "." << endl; QList<QByteArray> keys = d->actionHash.keys(); qSort(keys.begin(), keys.end()); Q_FOREACH (const QByteArray &key, keys) { Action *action = d->actionHash.value(key); if (d->showInternalActions || !action->name().startsWith('_')) { QByteArray path = key; if (!path.startsWith('/')) { path.prepend('/'); } out << "| " << path.leftJustified(privateLength).data() << " | " << action->className().leftJustified(classLength).data() << " | " << action->name().leftJustified(actionLength).data() << " |" << endl; } } out << "." << QByteArray().fill('-', privateLength + 2).data() << "+" << QByteArray().fill('-', classLength + 2).data() << "+" << QByteArray().fill('-', actionLength + 2).data() << "." << endl; // List all public actions Q_FOREACH (DispatchType *dispatch, d->dispatchers) { out << endl << dispatch->list(); } return buffer; } const Action *Dispatcher::command2Action(Context *ctx, const QByteArray &command, const QStringList &extraParams) { Q_D(Dispatcher); // qDebug() << Q_FUNC_INFO << "Command" << command; const Action *ret = d->actionHash.value(command); if (!ret) { ret = invokeAsPath(ctx, command, ctx->args()); } return ret; } QByteArray Dispatcher::actionRel2Abs(Context *ctx, const QByteArray &path) { QByteArray ret = path; if (!ret.startsWith('/')) { // TODO at Catalyst it uses // c->stack->last()->namespace ret.prepend('/'); ret.prepend(ctx->action()->ns()); } if (ret.startsWith('/')) { ret.remove(0, 1); } return ret; } const Action *Dispatcher::invokeAsPath(Context *ctx, const QByteArray &relativePath, const QStringList &args) { const Action *ret; QByteArray path = actionRel2Abs(ctx, relativePath); int pos = path.lastIndexOf('/'); int lastPos = path.size(); do { if (pos == -1) { ret = getAction(path, QByteArray()); if (ret) { return ret; } } else { QByteArray name = path.mid(pos + 1, lastPos); path = path.mid(0, pos); ret = getAction(name, path); if (ret) { return ret; } } lastPos = pos; pos = path.indexOf('/', pos - 1); } while (pos != -1); return 0; } QByteArray Dispatcher::cleanNamespace(const QByteArray &ns) const { QByteArray ret = ns; bool lastWasSlash = true; // remove initial slash int nsSize = ns.size(); const char * data = ret.constData(); for (int i = 0; i < nsSize; ++i) { if (data[i] == '/') { if (lastWasSlash) { ret.remove(i, 1); data = ret.constData(); --nsSize; } else { lastWasSlash = true; } } else { lastWasSlash = false; } } return ret; } ActionList DispatcherPrivate::getContainers(const QByteArray &ns) const { ActionList ret; if (ns != "/") { int pos = ns.size(); // qDebug() << pos << ns.mid(0, pos); while (pos > 0) { // qDebug() << pos << ns.mid(0, pos); ret.append(containerHash.value(ns.mid(0, pos))); pos = ns.lastIndexOf('/', pos - 1); } } // qDebug() << containerHash.size() << rootActions; ret.append(rootActions); return ret; } <|endoftext|>
<commit_before>/* Copyright (C) 2018 Alexandr Akulich <akulichalexander@gmail.com> This file is a part of TelegramQt library. 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. */ #include "RpcError.hpp" #include "MTProto/TLValues.hpp" #include "RawStream.hpp" #include <QHash> #include <QMetaEnum> #include <QRegularExpression> #include <QLoggingCategory> namespace Telegram { //QMetaEnum rpcErrorReasonEnum() //{ // QMetaEnum reasonEnum = QMetaEnum::fromType<RpcError::Reason>(); // return reasonEnum; //} bool RpcError::readFromStream(RawStreamEx &stream) { quint32 v; quint32 code; stream >> v; if (v != TLValue::RpcError) { return false; } stream >> code; stream >> message; type = static_cast<RpcError::Type>(code); reasonFromString(message, &reason, &argument); return !stream.error(); } QString RpcError::reasonToString(RpcError::Reason reason, quint32 argument) { static const QMetaEnum reasonEnum = QMetaEnum::fromType<Reason>(); static QHash<quint32, QString> reasons; if (reasons.contains(reason)) { return reasons.value(reason); } const char *key = reasonEnum.valueToKey(reason); if (!key) { qWarning() << Q_FUNC_INFO << "Unable to make a text for the given reason" << reason; return QString(); } const QString reasonKey = QString::fromLatin1(key); static const QRegularExpression regExpr(QStringLiteral("(?=[A-Z][^A-Z]*)")); QStringList reasonWords = reasonKey.split(regExpr); if (reasonWords.count() < 2) { return reasonWords.first().toUpper(); } reasonWords.removeFirst(); // The first element is always empty for this regexp. bool hasArg = false; for (QString &word : reasonWords) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)) if (word == QLatin1Char('X')) { #else if ((word.length() == 1) && (word.at(0) == QLatin1Char('X'))) { #endif hasArg = true; word = QString::number(argument); break; } } const QString result = reasonWords.join(QLatin1Char('_')).toUpper(); if (!hasArg) { reasons.insert(reason, result); } return result; } bool RpcError::reasonFromString(const QByteArray &str, RpcError::Reason *reason, quint32 *argument) { if (str.isEmpty()) { return false; } static const QMetaEnum reasonEnum = QMetaEnum::fromType<Reason>(); auto reasonWords = str.split('_'); for (QByteArray &word : reasonWords) { bool ok; const quint32 arg = word.toUInt(&ok); if (ok) { *argument = arg; word = QByteArrayLiteral("X"); continue; } word = word.toLower(); word[0] = QChar::fromLatin1(word.at(0)).toUpper().toLatin1(); } const QByteArray reasonKey = reasonWords.join(QByteArray()); bool ok; int value = reasonEnum.keyToValue(reasonKey.constData(), &ok); if (!ok) { return false; } *reason = static_cast<RpcError::Reason>(value); return true; } RawStreamEx &operator>>(RawStreamEx &stream, RpcError &error) { error.readFromStream(stream); return stream; } RawStreamEx &operator<<(RawStreamEx &stream, const RpcError &error) { stream << TLValue::RpcError; quint32 code = error.type; stream << code; stream << error.message; return stream; } RpcError::RpcError(RpcError::Reason r, quint32 arg) : reason(r), argument(arg) { switch (r) { case UnknownReason: type = UnknownType; break; case PhoneNumberInvalid: case PhoneCodeHashEmpty: case PhoneCodeInvalid: case PhoneCodeEmpty: case PhoneCodeExpired: case PhoneNumberUnoccupied: case PeerIdInvalid: case UserIdInvalid: case InputFetchError: case LocationInvalid: case OffsetInvalid: // Offset must be divisible by 1KB case LimitInvalid: // Limit must be divisible by 1KB type = BadRequest; break; case FileMigrateX: case PhoneMigrateX: // case NetworkMigrateX: // case UserMigrateX: type = SeeOther; break; // case FirstnameInvalid: // case LastnameInvalid: // case UsernameInvalid: // case UsernameOccupied: // case UsernameNotModified: // case ApiIdInvalid: // case PasswordHashInvalid: // case PhoneNumberOccupied: // case FilePartXMissing: // case AuthKeyUnregistered: // case AuthKeyInvalid: // case UserDeactivated: // case SessionRevoked: // case SessionExpired: // case ActiveUserRequired: // case AuthKeyPermEmpty: case SessionPasswordNeeded: type = Unauthorized; break; case FloodWaitX: type = Flood; default: break; } message = reasonToString(r, argument).toLatin1(); } } // Telegram <commit_msg>RpcError: Cleanup Reason-to-Type code<commit_after>/* Copyright (C) 2018 Alexandr Akulich <akulichalexander@gmail.com> This file is a part of TelegramQt library. 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. */ #include "RpcError.hpp" #include "MTProto/TLValues.hpp" #include "RawStream.hpp" #include <QHash> #include <QMetaEnum> #include <QRegularExpression> #include <QLoggingCategory> namespace Telegram { //QMetaEnum rpcErrorReasonEnum() //{ // QMetaEnum reasonEnum = QMetaEnum::fromType<RpcError::Reason>(); // return reasonEnum; //} bool RpcError::readFromStream(RawStreamEx &stream) { quint32 v; quint32 code; stream >> v; if (v != TLValue::RpcError) { return false; } stream >> code; stream >> message; type = static_cast<RpcError::Type>(code); reasonFromString(message, &reason, &argument); return !stream.error(); } QString RpcError::reasonToString(RpcError::Reason reason, quint32 argument) { static const QMetaEnum reasonEnum = QMetaEnum::fromType<Reason>(); static QHash<quint32, QString> reasons; if (reasons.contains(reason)) { return reasons.value(reason); } const char *key = reasonEnum.valueToKey(reason); if (!key) { qWarning() << Q_FUNC_INFO << "Unable to make a text for the given reason" << reason; return QString(); } const QString reasonKey = QString::fromLatin1(key); static const QRegularExpression regExpr(QStringLiteral("(?=[A-Z][^A-Z]*)")); QStringList reasonWords = reasonKey.split(regExpr); if (reasonWords.count() < 2) { return reasonWords.first().toUpper(); } reasonWords.removeFirst(); // The first element is always empty for this regexp. bool hasArg = false; for (QString &word : reasonWords) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)) if (word == QLatin1Char('X')) { #else if ((word.length() == 1) && (word.at(0) == QLatin1Char('X'))) { #endif hasArg = true; word = QString::number(argument); break; } } const QString result = reasonWords.join(QLatin1Char('_')).toUpper(); if (!hasArg) { reasons.insert(reason, result); } return result; } bool RpcError::reasonFromString(const QByteArray &str, RpcError::Reason *reason, quint32 *argument) { if (str.isEmpty()) { return false; } static const QMetaEnum reasonEnum = QMetaEnum::fromType<Reason>(); auto reasonWords = str.split('_'); for (QByteArray &word : reasonWords) { bool ok; const quint32 arg = word.toUInt(&ok); if (ok) { *argument = arg; word = QByteArrayLiteral("X"); continue; } word = word.toLower(); word[0] = QChar::fromLatin1(word.at(0)).toUpper().toLatin1(); } const QByteArray reasonKey = reasonWords.join(QByteArray()); bool ok; int value = reasonEnum.keyToValue(reasonKey.constData(), &ok); if (!ok) { return false; } *reason = static_cast<RpcError::Reason>(value); return true; } RawStreamEx &operator>>(RawStreamEx &stream, RpcError &error) { error.readFromStream(stream); return stream; } RawStreamEx &operator<<(RawStreamEx &stream, const RpcError &error) { stream << TLValue::RpcError; quint32 code = error.type; stream << code; stream << error.message; return stream; } RpcError::RpcError(RpcError::Reason r, quint32 arg) : reason(r), argument(arg) { switch (r) { case UnknownReason: type = UnknownType; break; case InputFetchError: case LimitInvalid: // Limit must be divisible by 1KB case LocationInvalid: case OffsetInvalid: // Offset must be divisible by 1KB case PeerIdInvalid: case PhoneCodeEmpty: case PhoneCodeExpired: case PhoneCodeHashEmpty: case PhoneCodeInvalid: case PhoneNumberInvalid: case PhoneNumberUnoccupied: case UserIdInvalid: type = BadRequest; break; case FileMigrateX: case PhoneMigrateX: type = SeeOther; break; case SessionPasswordNeeded: type = Unauthorized; break; case FloodWaitX: type = Flood; break; default: type = UnknownType; break; } message = reasonToString(r, argument).toLatin1(); } } // Telegram <|endoftext|>
<commit_before>/* Title: Main program Copyright (c) 2000 Cambridge University Technical Services Limited Further development copyright David C.J. Matthews 2001-12 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #elif defined(WIN32) #include "winconfig.h" #else #error "No configuration file" #endif #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_ASSERT_H #include <assert.h> #define ASSERT(x) assert(x) #else #define ASSERT(x) 0 #endif #ifdef HAVE_TCHAR_H #include <tchar.h> #endif #include "globals.h" #include "sys.h" #include "gc.h" #include "run_time.h" #include "machine_dep.h" #include "version.h" #include "diagnostics.h" #include "processes.h" #include "mpoly.h" #include "scanaddrs.h" #include "save_vec.h" #include "../polyexports.h" #include "memmgr.h" #include "pexport.h" #ifdef WINDOWS_PC #include "Console.h" #endif static void InitHeaderFromExport(exportDescription *exports); NORETURNFN(static void Usage(const char *message)); // Return the entry in the io vector corresponding to the Poly system call. PolyWord *IoEntry(unsigned sysOp) { MemSpace *space = gMem.IoSpace(); return space->bottom + sysOp * IO_SPACING; } struct _userOptions userOptions; UNSIGNEDADDR exportTimeStamp; enum { OPT_HEAP, OPT_IMMUTABLE, OPT_MUTABLE, OPT_ALLOCATION, OPT_RESERVE, OPT_GCTHREADS, OPT_DEBUGOPTS, OPT_DEBUGFILE }; struct __argtab { const char *argName, *argHelp; unsigned argKey; } argTable[] = { { "-H", "Initial heap size (MB)", OPT_HEAP }, { "--heap", "Initial heap size (MB)", OPT_HEAP }, { "--immutable", "Initial size of immutable buffer (MB)", OPT_IMMUTABLE }, { "--mutable", "Initial size of mutable buffer(MB)", OPT_MUTABLE }, { "--allocation", "Size of allocation area(MB)", OPT_ALLOCATION }, { "--stackspace", "Space to reserve for thread stacks and C++ heap(MB)", OPT_RESERVE }, { "--gcthreads", "Number of threads to use for garbage collection", OPT_GCTHREADS }, { "--debug", "Debug options: checkobjects, gc, x", OPT_DEBUGOPTS }, { "--logfile", "Logging file (default is to log to stdout)", OPT_DEBUGFILE } }; struct __debugOpts { const char *optName, *optHelp; unsigned optKey; } debugOptTable[] = { { "checkobjects", "Perform additional debugging checks", DEBUG_CHECK_OBJECTS }, { "gc", "Log summary garbage-collector information", DEBUG_GC }, { "gcdetail", "Log detailed garbage-collector information", DEBUG_GC_DETAIL }, { "memmgr", "Memory manager information", DEBUG_MEMMGR }, { "threads", "Thread related information", DEBUG_THREADS }, { "gctasks", "Log multi-thread GC information", DEBUG_GCTASKS }, { "heapsize", "Log heap resizing data", DEBUG_HEAPSIZE }, { "x", "Log X-windows information", DEBUG_X}, { "sharing", "Information from PolyML.shareCommonData", DEBUG_SHARING} }; /* In the Windows version this is called from WinMain in Console.c */ int polymain(int argc, char **argv, exportDescription *exports) { unsigned hsize=0, isize=0, msize=0, rsize=0, asize=0; /* Get arguments. */ memset(&userOptions, 0, sizeof(userOptions)); /* Reset it */ userOptions.gcthreads = 1; // Single threaded // Get the program name for CommandLine.name. This is allowed to be a full path or // just the last component so we return whatever the system provides. if (argc > 0) userOptions.programName = argv[0]; else userOptions.programName = ""; // Set it to a valid empty string char *importFileName = 0; debugOptions = 0; userOptions.user_arg_count = 0; userOptions.user_arg_strings = (char**)malloc(argc * sizeof(char*)); // Enough room for all of them // Process the argument list removing those recognised by the RTS and adding the // remainder to the user argument list. for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { bool argUsed = false; for (unsigned j = 0; j < sizeof(argTable)/sizeof(argTable[0]); j++) { unsigned argl = strlen(argTable[j].argName); if (strncmp(argv[i], argTable[j].argName, argl) == 0) { char *p, *endp; if (strlen(argv[i]) == argl) { // If it has used all the argument pick the next i++; p = argv[i]; } else { p = argv[i]+argl; if (*p == '=') p++; // Skip an equals sign } if (i >= argc) printf("Incomplete %s option\n", argTable[j].argName); else switch (argTable[j].argKey) { case OPT_HEAP: hsize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_IMMUTABLE: isize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_MUTABLE: msize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_ALLOCATION: asize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_RESERVE: rsize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_GCTHREADS: userOptions.gcthreads = strtol(p, &endp, 10); if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_DEBUGOPTS: while (*p != '\0') { // Debug options are separated by commas char *q = strchr(p, ','); if (q == NULL) q = p+strlen(p); for (unsigned k = 0; k < sizeof(debugOptTable)/sizeof(debugOptTable[0]); k++) { if (strlen(debugOptTable[k].optName) == (size_t)(q-p) && strncmp(p, debugOptTable[k].optName, q-p) == 0) debugOptions |= debugOptTable[k].optKey; } if (*q == ',') p = q+1; else p = q; } break; case OPT_DEBUGFILE: SetLogFile(p); break; } argUsed = true; break; } } if (! argUsed) // Add it to the user args. userOptions.user_arg_strings[userOptions.user_arg_count++] = argv[i]; } else if (exports == 0 && importFileName == 0) importFileName = argv[i]; else userOptions.user_arg_strings[userOptions.user_arg_count++] = argv[i]; } if (exports == 0 && importFileName == 0) Usage("Missing import file name"); if (userOptions.gcthreads == 0) // For the moment, at any rate, indicate that we should use as many // threads as there are processors by a thread count of zero. userOptions.gcthreads = NumberOfProcessors(); // Initialise the run-time system before creating the heap. InitModules(); CreateHeap(hsize, isize, msize, asize, rsize); PolyObject *rootFunction = 0; if (exports != 0) { InitHeaderFromExport(exports); rootFunction = (PolyObject *)exports->rootFunction; } else { if (importFileName != 0) rootFunction = ImportPortable(importFileName); if (rootFunction == 0) exit(1); } /* Initialise the interface vector. */ machineDependent->InitInterfaceVector(); /* machine dependent entries. */ // This word has a zero value and is used for null strings. add_word_to_io_area(POLY_SYS_emptystring, PolyWord::FromUnsigned(0)); // This is used to represent zero-sized vectors. // N.B. This assumes that the word before is zero because it's // actually the length word we want to be zero here. add_word_to_io_area(POLY_SYS_nullvector, PolyWord::FromUnsigned(0)); /* The standard input and output streams are persistent i.e. references to the the standard input in one session will refer to the standard input in the next. */ add_word_to_io_area(POLY_SYS_stdin, PolyWord::FromUnsigned(0)); add_word_to_io_area(POLY_SYS_stdout, PolyWord::FromUnsigned(1)); add_word_to_io_area(POLY_SYS_stderr, PolyWord::FromUnsigned(2)); StartModules(); // Set up the initial process to run the root function. processes->BeginRootThread(rootFunction); finish(0); /*NOTREACHED*/ return 0; /* just to keep lint happy */ } void Uninitialise(void) // Close down everything and free all resources. Stop any threads or timers. { StopModules(); } void finish (int n) { // Make sure we don't get any interrupts once the destructors are // applied to globals or statics. Uninitialise(); #if defined(WINDOWS_PC) ExitThread(n); #else exit (n); #endif } // Print a message and exit if an argument is malformed. void Usage(const char *message) { if (message) printf("%s\n", message); for (unsigned j = 0; j < sizeof(argTable)/sizeof(argTable[0]); j++) { printf("%s <%s>\n", argTable[j].argName, argTable[j].argHelp); } fflush(stdout); #if defined(WINDOWS_PC) if (useConsole) { MessageBox(hMainWindow, _T("Poly/ML has exited"), _T("Poly/ML"), MB_OK); } #endif exit (1); } // Return a string containing the argument names. Can be printed out in response // to a --help argument. It is up to the ML application to do that since it may well // want to produce information about any arguments it chooses to process. char *RTSArgHelp(void) { static char buff[2000]; char *p = buff; for (unsigned j = 0; j < sizeof(argTable)/sizeof(argTable[0]); j++) { int spaces = sprintf(p, "%s <%s>\n", argTable[j].argName, argTable[j].argHelp); p += spaces; } { int spaces = sprintf(p, "Debug options:\n"); p += spaces; } for (unsigned k = 0; k < sizeof(debugOptTable)/sizeof(debugOptTable[0]); k++) { int spaces = sprintf(p, "%s <%s>\n", debugOptTable[k].optName, debugOptTable[k].optHelp); p += spaces; } ASSERT((unsigned)(p - buff) < (unsigned)sizeof(buff)); return buff; } void InitHeaderFromExport(exportDescription *exports) { // Check the structure sizes stored in the export structure match the versions // used in this library. if (exports->structLength != sizeof(exportDescription) || exports->memTableSize != sizeof(memoryTableEntry) || exports->rtsVersion < FIRST_supported_version || exports->rtsVersion > LAST_supported_version) { #if (FIRST_supported_version == LAST_supported_version) Exit("The exported object file has version %0.2f but this library supports %0.2f", ((float)exports->rtsVersion) / 100.0, ((float)FIRST_supported_version) / 100.0); #else Exit("The exported object file has version %0.2f but this library supports %0.2f-%0.2f", ((float)exports->rtsVersion) / 100.0, ((float)FIRST_supported_version) / 100.0, ((float)LAST_supported_version) / 100.0); #endif } // We could also check the RTS version and the architecture. exportTimeStamp = exports->timeStamp; // Needed for load and save. memoryTableEntry *memTable = exports->memTable; for (unsigned i = 0; i < exports->memTableEntries; i++) { // Construct a new space for each of the entries. if (i == exports->ioIndex) (void)gMem.InitIOSpace((PolyWord*)memTable[i].mtAddr, memTable[i].mtLength/sizeof(PolyWord)); else (void)gMem.NewPermanentSpace( (PolyWord*)memTable[i].mtAddr, memTable[i].mtLength/sizeof(PolyWord), memTable[i].mtFlags, memTable[i].mtIndex); } } <commit_msg>Handle the, extremely rare, situation of being unable to set up the permanent memory spaces.<commit_after>/* Title: Main program Copyright (c) 2000 Cambridge University Technical Services Limited Further development copyright David C.J. Matthews 2001-12 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #elif defined(WIN32) #include "winconfig.h" #else #error "No configuration file" #endif #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_ASSERT_H #include <assert.h> #define ASSERT(x) assert(x) #else #define ASSERT(x) 0 #endif #ifdef HAVE_TCHAR_H #include <tchar.h> #endif #include "globals.h" #include "sys.h" #include "gc.h" #include "run_time.h" #include "machine_dep.h" #include "version.h" #include "diagnostics.h" #include "processes.h" #include "mpoly.h" #include "scanaddrs.h" #include "save_vec.h" #include "../polyexports.h" #include "memmgr.h" #include "pexport.h" #ifdef WINDOWS_PC #include "Console.h" #endif static void InitHeaderFromExport(exportDescription *exports); NORETURNFN(static void Usage(const char *message)); // Return the entry in the io vector corresponding to the Poly system call. PolyWord *IoEntry(unsigned sysOp) { MemSpace *space = gMem.IoSpace(); return space->bottom + sysOp * IO_SPACING; } struct _userOptions userOptions; UNSIGNEDADDR exportTimeStamp; enum { OPT_HEAP, OPT_IMMUTABLE, OPT_MUTABLE, OPT_ALLOCATION, OPT_RESERVE, OPT_GCTHREADS, OPT_DEBUGOPTS, OPT_DEBUGFILE }; struct __argtab { const char *argName, *argHelp; unsigned argKey; } argTable[] = { { "-H", "Initial heap size (MB)", OPT_HEAP }, { "--heap", "Initial heap size (MB)", OPT_HEAP }, { "--immutable", "Initial size of immutable buffer (MB)", OPT_IMMUTABLE }, { "--mutable", "Initial size of mutable buffer(MB)", OPT_MUTABLE }, { "--allocation", "Size of allocation area(MB)", OPT_ALLOCATION }, { "--stackspace", "Space to reserve for thread stacks and C++ heap(MB)", OPT_RESERVE }, { "--gcthreads", "Number of threads to use for garbage collection", OPT_GCTHREADS }, { "--debug", "Debug options: checkobjects, gc, x", OPT_DEBUGOPTS }, { "--logfile", "Logging file (default is to log to stdout)", OPT_DEBUGFILE } }; struct __debugOpts { const char *optName, *optHelp; unsigned optKey; } debugOptTable[] = { { "checkobjects", "Perform additional debugging checks", DEBUG_CHECK_OBJECTS }, { "gc", "Log summary garbage-collector information", DEBUG_GC }, { "gcdetail", "Log detailed garbage-collector information", DEBUG_GC_DETAIL }, { "memmgr", "Memory manager information", DEBUG_MEMMGR }, { "threads", "Thread related information", DEBUG_THREADS }, { "gctasks", "Log multi-thread GC information", DEBUG_GCTASKS }, { "heapsize", "Log heap resizing data", DEBUG_HEAPSIZE }, { "x", "Log X-windows information", DEBUG_X}, { "sharing", "Information from PolyML.shareCommonData", DEBUG_SHARING} }; /* In the Windows version this is called from WinMain in Console.c */ int polymain(int argc, char **argv, exportDescription *exports) { unsigned hsize=0, isize=0, msize=0, rsize=0, asize=0; /* Get arguments. */ memset(&userOptions, 0, sizeof(userOptions)); /* Reset it */ userOptions.gcthreads = 1; // Single threaded // Get the program name for CommandLine.name. This is allowed to be a full path or // just the last component so we return whatever the system provides. if (argc > 0) userOptions.programName = argv[0]; else userOptions.programName = ""; // Set it to a valid empty string char *importFileName = 0; debugOptions = 0; userOptions.user_arg_count = 0; userOptions.user_arg_strings = (char**)malloc(argc * sizeof(char*)); // Enough room for all of them // Process the argument list removing those recognised by the RTS and adding the // remainder to the user argument list. for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { bool argUsed = false; for (unsigned j = 0; j < sizeof(argTable)/sizeof(argTable[0]); j++) { unsigned argl = strlen(argTable[j].argName); if (strncmp(argv[i], argTable[j].argName, argl) == 0) { char *p, *endp; if (strlen(argv[i]) == argl) { // If it has used all the argument pick the next i++; p = argv[i]; } else { p = argv[i]+argl; if (*p == '=') p++; // Skip an equals sign } if (i >= argc) printf("Incomplete %s option\n", argTable[j].argName); else switch (argTable[j].argKey) { case OPT_HEAP: hsize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_IMMUTABLE: isize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_MUTABLE: msize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_ALLOCATION: asize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_RESERVE: rsize = strtol(p, &endp, 10) * 1024; if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_GCTHREADS: userOptions.gcthreads = strtol(p, &endp, 10); if (*endp != '\0') printf("Incomplete %s option\n", argTable[j].argName); break; case OPT_DEBUGOPTS: while (*p != '\0') { // Debug options are separated by commas char *q = strchr(p, ','); if (q == NULL) q = p+strlen(p); for (unsigned k = 0; k < sizeof(debugOptTable)/sizeof(debugOptTable[0]); k++) { if (strlen(debugOptTable[k].optName) == (size_t)(q-p) && strncmp(p, debugOptTable[k].optName, q-p) == 0) debugOptions |= debugOptTable[k].optKey; } if (*q == ',') p = q+1; else p = q; } break; case OPT_DEBUGFILE: SetLogFile(p); break; } argUsed = true; break; } } if (! argUsed) // Add it to the user args. userOptions.user_arg_strings[userOptions.user_arg_count++] = argv[i]; } else if (exports == 0 && importFileName == 0) importFileName = argv[i]; else userOptions.user_arg_strings[userOptions.user_arg_count++] = argv[i]; } if (exports == 0 && importFileName == 0) Usage("Missing import file name"); if (userOptions.gcthreads == 0) // For the moment, at any rate, indicate that we should use as many // threads as there are processors by a thread count of zero. userOptions.gcthreads = NumberOfProcessors(); // Initialise the run-time system before creating the heap. InitModules(); CreateHeap(hsize, isize, msize, asize, rsize); PolyObject *rootFunction = 0; if (exports != 0) { InitHeaderFromExport(exports); rootFunction = (PolyObject *)exports->rootFunction; } else { if (importFileName != 0) rootFunction = ImportPortable(importFileName); if (rootFunction == 0) exit(1); } /* Initialise the interface vector. */ machineDependent->InitInterfaceVector(); /* machine dependent entries. */ // This word has a zero value and is used for null strings. add_word_to_io_area(POLY_SYS_emptystring, PolyWord::FromUnsigned(0)); // This is used to represent zero-sized vectors. // N.B. This assumes that the word before is zero because it's // actually the length word we want to be zero here. add_word_to_io_area(POLY_SYS_nullvector, PolyWord::FromUnsigned(0)); /* The standard input and output streams are persistent i.e. references to the the standard input in one session will refer to the standard input in the next. */ add_word_to_io_area(POLY_SYS_stdin, PolyWord::FromUnsigned(0)); add_word_to_io_area(POLY_SYS_stdout, PolyWord::FromUnsigned(1)); add_word_to_io_area(POLY_SYS_stderr, PolyWord::FromUnsigned(2)); StartModules(); // Set up the initial process to run the root function. processes->BeginRootThread(rootFunction); finish(0); /*NOTREACHED*/ return 0; /* just to keep lint happy */ } void Uninitialise(void) // Close down everything and free all resources. Stop any threads or timers. { StopModules(); } void finish (int n) { // Make sure we don't get any interrupts once the destructors are // applied to globals or statics. Uninitialise(); #if defined(WINDOWS_PC) ExitThread(n); #else exit (n); #endif } // Print a message and exit if an argument is malformed. void Usage(const char *message) { if (message) printf("%s\n", message); for (unsigned j = 0; j < sizeof(argTable)/sizeof(argTable[0]); j++) { printf("%s <%s>\n", argTable[j].argName, argTable[j].argHelp); } fflush(stdout); #if defined(WINDOWS_PC) if (useConsole) { MessageBox(hMainWindow, _T("Poly/ML has exited"), _T("Poly/ML"), MB_OK); } #endif exit (1); } // Return a string containing the argument names. Can be printed out in response // to a --help argument. It is up to the ML application to do that since it may well // want to produce information about any arguments it chooses to process. char *RTSArgHelp(void) { static char buff[2000]; char *p = buff; for (unsigned j = 0; j < sizeof(argTable)/sizeof(argTable[0]); j++) { int spaces = sprintf(p, "%s <%s>\n", argTable[j].argName, argTable[j].argHelp); p += spaces; } { int spaces = sprintf(p, "Debug options:\n"); p += spaces; } for (unsigned k = 0; k < sizeof(debugOptTable)/sizeof(debugOptTable[0]); k++) { int spaces = sprintf(p, "%s <%s>\n", debugOptTable[k].optName, debugOptTable[k].optHelp); p += spaces; } ASSERT((unsigned)(p - buff) < (unsigned)sizeof(buff)); return buff; } void InitHeaderFromExport(exportDescription *exports) { // Check the structure sizes stored in the export structure match the versions // used in this library. if (exports->structLength != sizeof(exportDescription) || exports->memTableSize != sizeof(memoryTableEntry) || exports->rtsVersion < FIRST_supported_version || exports->rtsVersion > LAST_supported_version) { #if (FIRST_supported_version == LAST_supported_version) Exit("The exported object file has version %0.2f but this library supports %0.2f", ((float)exports->rtsVersion) / 100.0, ((float)FIRST_supported_version) / 100.0); #else Exit("The exported object file has version %0.2f but this library supports %0.2f-%0.2f", ((float)exports->rtsVersion) / 100.0, ((float)FIRST_supported_version) / 100.0, ((float)LAST_supported_version) / 100.0); #endif } // We could also check the RTS version and the architecture. exportTimeStamp = exports->timeStamp; // Needed for load and save. memoryTableEntry *memTable = exports->memTable; for (unsigned i = 0; i < exports->memTableEntries; i++) { // Construct a new space for each of the entries. if (i == exports->ioIndex) { if (gMem.InitIOSpace((PolyWord*)memTable[i].mtAddr, memTable[i].mtLength/sizeof(PolyWord)) == 0) Exit("Unable to initialise the memory space"); } else { if (gMem.NewPermanentSpace( (PolyWord*)memTable[i].mtAddr, memTable[i].mtLength/sizeof(PolyWord), memTable[i].mtFlags, memTable[i].mtIndex) == 0) Exit("Unable to initialise a permanent memory space"); } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "processcommandexecutor.h" #include "artifact.h" #include "command.h" #include "transformer.h" #include <language/language.h> #include <logging/logger.h> #include <logging/translator.h> #include <tools/error.h> #include <tools/fileinfo.h> #include <tools/hostosinfo.h> #include <tools/processresult.h> #include <tools/processresult_p.h> #include <tools/qbsassert.h> #include <QDir> #include <QScriptEngine> #include <QScriptValue> #include <QTemporaryFile> #include <QTimer> namespace qbs { namespace Internal { static QStringList populateExecutableSuffixes() { QStringList result; result << QString(); if (HostOsInfo::isWindowsHost()) { result << QLatin1String(".com") << QLatin1String(".exe") << QLatin1String(".bat") << QLatin1String(".cmd"); } return result; } const QStringList ProcessCommandExecutor::m_executableSuffixes = populateExecutableSuffixes(); ProcessCommandExecutor::ProcessCommandExecutor(const Logger &logger, QObject *parent) : AbstractCommandExecutor(logger, parent) { connect(&m_process, SIGNAL(error(QProcess::ProcessError)), SLOT(onProcessError())); connect(&m_process, SIGNAL(finished(int)), SLOT(onProcessFinished(int))); } // returns an empty string or one that starts with a space! static QString commandArgsToString(const QStringList &args) { QString result; QRegExp ws("\\s"); foreach (const QString &arg, args) { result += QLatin1Char(' '); if (arg.contains(ws)) result += QLatin1Char('"') + arg + QLatin1Char('"'); else result += arg; } return result; } void ProcessCommandExecutor::doStart() { QBS_ASSERT(m_process.state() == QProcess::NotRunning, return); const ProcessCommand * const cmd = processCommand(); QString program = cmd->program(); if (FileInfo::isAbsolute(cmd->program())) { if (HostOsInfo::isWindowsHost()) program = findProcessCommandBySuffix(); } else { program = findProcessCommandInPath(); } QProcessEnvironment env = m_buildEnvironment; const QProcessEnvironment &additionalVariables = cmd->environment(); foreach (const QString &key, additionalVariables.keys()) env.insert(key, additionalVariables.value(key)); m_process.setProcessEnvironment(env); QStringList arguments = cmd->arguments(); QString argString = commandArgsToString(arguments); if (!cmd->isSilent()) logger().qbsInfo() << program << argString; if (dryRun()) { QTimer::singleShot(0, this, SIGNAL(finished())); // Don't call back on the caller. return; } // Automatically use response files, if the command line gets to long. if (!cmd->responseFileUsagePrefix().isEmpty()) { const int commandLineLength = program.length() + argString.length(); if (cmd->responseFileThreshold() >= 0 && commandLineLength > cmd->responseFileThreshold()) { if (logger().debugEnabled()) { logger().qbsDebug() << QString::fromLocal8Bit("[EXEC] Using response file. " "Threshold is %1. Command line length %2.") .arg(cmd->responseFileThreshold()).arg(commandLineLength); } // The QTemporaryFile keeps a handle on the file, even if closed. // On Windows, some commands (e.g. msvc link.exe) won't accept that. // We need to delete the file manually, later. QTemporaryFile responseFile; responseFile.setAutoRemove(false); responseFile.setFileTemplate(QDir::tempPath() + "/qbsresp"); if (!responseFile.open()) { emit error(ErrorInfo(Tr::tr("Cannot create response file '%1'.") .arg(responseFile.fileName()))); return; } for (int i = 0; i < cmd->arguments().count(); ++i) { responseFile.write(cmd->arguments().at(i).toLocal8Bit()); responseFile.write("\n"); } responseFile.close(); m_responseFileName = responseFile.fileName(); arguments.clear(); arguments += QDir::toNativeSeparators(cmd->responseFileUsagePrefix() + responseFile.fileName()); } } logger().qbsDebug() << "[EXEC] Running external process; full command line is: " << program << " " << commandArgsToString(arguments); logger().qbsTrace() << "[EXEC] Additional environment:" << additionalVariables.toStringList(); m_process.setWorkingDirectory(cmd->workingDir()); m_process.start(program, arguments); m_program = program; m_arguments = arguments; } void ProcessCommandExecutor::waitForFinished() { m_process.waitForFinished(-1); } QString ProcessCommandExecutor::filterProcessOutput(const QByteArray &_output, const QString &filterFunctionSource) { const QString output = QString::fromLocal8Bit(_output); if (filterFunctionSource.isEmpty()) return output; QScriptValue filterFunction = scriptEngine()->evaluate("var f = " + filterFunctionSource + "; f"); if (!filterFunction.isFunction()) { emit error(ErrorInfo(Tr::tr("Error in filter function: %1.\n%2") .arg(filterFunctionSource, filterFunction.toString()))); return output; } QScriptValue outputArg = scriptEngine()->newArray(1); outputArg.setProperty(0, scriptEngine()->toScriptValue(output)); QScriptValue filteredOutput = filterFunction.call(scriptEngine()->undefinedValue(), outputArg); if (filteredOutput.isError()) { emit error(ErrorInfo(Tr::tr("Error when calling output filter function: %1") .arg(filteredOutput.toString()))); return output; } return filteredOutput.toString(); } void ProcessCommandExecutor::sendProcessOutput(bool success) { ProcessResult result; result.d->executableFilePath = m_program; result.d->arguments = m_arguments; result.d->workingDirectory = m_process.workingDirectory(); if (result.workingDirectory().isEmpty()) result.d->workingDirectory = QDir::currentPath(); result.d->exitCode = m_process.exitCode(); result.d->exitStatus = m_process.exitStatus(); result.d->success = success; QString tmp = filterProcessOutput(m_process.readAllStandardOutput(), processCommand()->stdoutFilterFunction()); if (!tmp.isEmpty()) { if (tmp.endsWith(QLatin1Char('\n'))) tmp.chop(1); result.d->stdOut = tmp.split(QLatin1Char('\n')); } tmp = filterProcessOutput(m_process.readAllStandardError(), processCommand()->stderrFilterFunction()); if (!tmp.isEmpty()) { if (tmp.endsWith(QLatin1Char('\n'))) tmp.chop(1); result.d->stdErr = tmp.split(QLatin1Char('\n')); } emit reportProcessResult(result); } void ProcessCommandExecutor::onProcessError() { sendProcessOutput(false); removeResponseFile(); QString errorMessage; const QString binary = QDir::toNativeSeparators(processCommand()->program()); switch (m_process.error()) { case QProcess::FailedToStart: errorMessage = Tr::tr("The process '%1' could not be started: %2"). arg(binary, m_process.errorString()); break; case QProcess::Crashed: errorMessage = Tr::tr("The process '%1' crashed.").arg(binary); break; case QProcess::Timedout: errorMessage = Tr::tr("The process '%1' timed out.").arg(binary); break; case QProcess::ReadError: errorMessage = Tr::tr("Error reading process output from '%1'.").arg(binary); break; case QProcess::WriteError: errorMessage = Tr::tr("Error writing to process '%1'.").arg(binary); break; default: errorMessage = Tr::tr("Unknown process error running '%1'.").arg(binary); break; } emit error(ErrorInfo(errorMessage)); } void ProcessCommandExecutor::onProcessFinished(int exitCode) { removeResponseFile(); const bool errorOccurred = exitCode > processCommand()->maxExitCode(); sendProcessOutput(!errorOccurred); if (Q_UNLIKELY(errorOccurred)) { emit error(ErrorInfo(Tr::tr("Process failed with exit code %1.").arg(exitCode))); return; } emit finished(); } void ProcessCommandExecutor::removeResponseFile() { if (m_responseFileName.isEmpty()) return; QFile::remove(m_responseFileName); m_responseFileName.clear(); } QString ProcessCommandExecutor::findProcessCommandInPath() { const ResolvedProductPtr product = transformer()->product(); const ProcessCommand * const cmd = processCommand(); QString fullProgramPath = product->executablePathCache.value(cmd->program()); if (!fullProgramPath.isEmpty()) return fullProgramPath; fullProgramPath = cmd->program(); if (logger().traceEnabled()) logger().qbsTrace() << "[EXEC] looking for executable in PATH " << fullProgramPath; const QProcessEnvironment &buildEnvironment = product->buildEnvironment; QStringList pathEnv = buildEnvironment.value("PATH").split(HostOsInfo::pathListSeparator(), QString::SkipEmptyParts); if (HostOsInfo::isWindowsHost()) pathEnv.prepend(QLatin1String(".")); for (int i = 0; i < pathEnv.count(); ++i) { QString directory = pathEnv.at(i); if (directory == QLatin1String(".")) directory = cmd->workingDir(); if (!directory.isEmpty()) { const QChar lastChar = directory.at(directory.count() - 1); if (lastChar != QLatin1Char('/') && lastChar != QLatin1Char('\\')) directory.append(QLatin1Char('/')); } if (findProcessCandidateCheck(directory, fullProgramPath, fullProgramPath)) break; } product->executablePathCache.insert(cmd->program(), fullProgramPath); return fullProgramPath; } QString ProcessCommandExecutor::findProcessCommandBySuffix() { const ResolvedProductPtr product = transformer()->product(); const ProcessCommand * const cmd = processCommand(); QString fullProgramPath = product->executablePathCache.value(cmd->program()); if (!fullProgramPath.isEmpty()) return fullProgramPath; fullProgramPath = cmd->program(); if (logger().traceEnabled()) logger().qbsTrace() << "[EXEC] looking for executable by suffix " << fullProgramPath; const QString emptyDirectory; findProcessCandidateCheck(emptyDirectory, fullProgramPath, fullProgramPath); product->executablePathCache.insert(cmd->program(), fullProgramPath); return fullProgramPath; } bool ProcessCommandExecutor::findProcessCandidateCheck(const QString &directory, const QString &program, QString &fullProgramPath) { for (int i = 0; i < m_executableSuffixes.count(); ++i) { QString candidate = directory + program + m_executableSuffixes.at(i); if (logger().traceEnabled()) logger().qbsTrace() << "[EXEC] candidate: " << candidate; if (FileInfo::exists(candidate)) { fullProgramPath = candidate; return true; } } return false; } const ProcessCommand *ProcessCommandExecutor::processCommand() const { return static_cast<const ProcessCommand *>(command()); } } // namespace Internal } // namespace qbs <commit_msg>Fix incorrect logging output.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "processcommandexecutor.h" #include "artifact.h" #include "command.h" #include "transformer.h" #include <language/language.h> #include <logging/logger.h> #include <logging/translator.h> #include <tools/error.h> #include <tools/fileinfo.h> #include <tools/hostosinfo.h> #include <tools/processresult.h> #include <tools/processresult_p.h> #include <tools/qbsassert.h> #include <QDir> #include <QScriptEngine> #include <QScriptValue> #include <QTemporaryFile> #include <QTimer> namespace qbs { namespace Internal { static QStringList populateExecutableSuffixes() { QStringList result; result << QString(); if (HostOsInfo::isWindowsHost()) { result << QLatin1String(".com") << QLatin1String(".exe") << QLatin1String(".bat") << QLatin1String(".cmd"); } return result; } const QStringList ProcessCommandExecutor::m_executableSuffixes = populateExecutableSuffixes(); ProcessCommandExecutor::ProcessCommandExecutor(const Logger &logger, QObject *parent) : AbstractCommandExecutor(logger, parent) { connect(&m_process, SIGNAL(error(QProcess::ProcessError)), SLOT(onProcessError())); connect(&m_process, SIGNAL(finished(int)), SLOT(onProcessFinished(int))); } // returns an empty string or one that starts with a space! static QString commandArgsToString(const QStringList &args) { QString result; QRegExp ws("\\s"); foreach (const QString &arg, args) { result += QLatin1Char(' '); if (arg.contains(ws) || arg.isEmpty()) result += QLatin1Char('"') + arg + QLatin1Char('"'); else result += arg; } return result; } void ProcessCommandExecutor::doStart() { QBS_ASSERT(m_process.state() == QProcess::NotRunning, return); const ProcessCommand * const cmd = processCommand(); QString program = cmd->program(); if (FileInfo::isAbsolute(cmd->program())) { if (HostOsInfo::isWindowsHost()) program = findProcessCommandBySuffix(); } else { program = findProcessCommandInPath(); } QProcessEnvironment env = m_buildEnvironment; const QProcessEnvironment &additionalVariables = cmd->environment(); foreach (const QString &key, additionalVariables.keys()) env.insert(key, additionalVariables.value(key)); m_process.setProcessEnvironment(env); QStringList arguments = cmd->arguments(); QString argString = commandArgsToString(arguments); if (!cmd->isSilent()) logger().qbsInfo() << program << argString; if (dryRun()) { QTimer::singleShot(0, this, SIGNAL(finished())); // Don't call back on the caller. return; } // Automatically use response files, if the command line gets to long. if (!cmd->responseFileUsagePrefix().isEmpty()) { const int commandLineLength = program.length() + argString.length(); if (cmd->responseFileThreshold() >= 0 && commandLineLength > cmd->responseFileThreshold()) { if (logger().debugEnabled()) { logger().qbsDebug() << QString::fromLocal8Bit("[EXEC] Using response file. " "Threshold is %1. Command line length %2.") .arg(cmd->responseFileThreshold()).arg(commandLineLength); } // The QTemporaryFile keeps a handle on the file, even if closed. // On Windows, some commands (e.g. msvc link.exe) won't accept that. // We need to delete the file manually, later. QTemporaryFile responseFile; responseFile.setAutoRemove(false); responseFile.setFileTemplate(QDir::tempPath() + "/qbsresp"); if (!responseFile.open()) { emit error(ErrorInfo(Tr::tr("Cannot create response file '%1'.") .arg(responseFile.fileName()))); return; } for (int i = 0; i < cmd->arguments().count(); ++i) { responseFile.write(cmd->arguments().at(i).toLocal8Bit()); responseFile.write("\n"); } responseFile.close(); m_responseFileName = responseFile.fileName(); arguments.clear(); arguments += QDir::toNativeSeparators(cmd->responseFileUsagePrefix() + responseFile.fileName()); } } logger().qbsDebug() << "[EXEC] Running external process; full command line is: " << program << commandArgsToString(arguments); logger().qbsTrace() << "[EXEC] Additional environment:" << additionalVariables.toStringList(); m_process.setWorkingDirectory(cmd->workingDir()); m_process.start(program, arguments); m_program = program; m_arguments = arguments; } void ProcessCommandExecutor::waitForFinished() { m_process.waitForFinished(-1); } QString ProcessCommandExecutor::filterProcessOutput(const QByteArray &_output, const QString &filterFunctionSource) { const QString output = QString::fromLocal8Bit(_output); if (filterFunctionSource.isEmpty()) return output; QScriptValue filterFunction = scriptEngine()->evaluate("var f = " + filterFunctionSource + "; f"); if (!filterFunction.isFunction()) { emit error(ErrorInfo(Tr::tr("Error in filter function: %1.\n%2") .arg(filterFunctionSource, filterFunction.toString()))); return output; } QScriptValue outputArg = scriptEngine()->newArray(1); outputArg.setProperty(0, scriptEngine()->toScriptValue(output)); QScriptValue filteredOutput = filterFunction.call(scriptEngine()->undefinedValue(), outputArg); if (filteredOutput.isError()) { emit error(ErrorInfo(Tr::tr("Error when calling output filter function: %1") .arg(filteredOutput.toString()))); return output; } return filteredOutput.toString(); } void ProcessCommandExecutor::sendProcessOutput(bool success) { ProcessResult result; result.d->executableFilePath = m_program; result.d->arguments = m_arguments; result.d->workingDirectory = m_process.workingDirectory(); if (result.workingDirectory().isEmpty()) result.d->workingDirectory = QDir::currentPath(); result.d->exitCode = m_process.exitCode(); result.d->exitStatus = m_process.exitStatus(); result.d->success = success; QString tmp = filterProcessOutput(m_process.readAllStandardOutput(), processCommand()->stdoutFilterFunction()); if (!tmp.isEmpty()) { if (tmp.endsWith(QLatin1Char('\n'))) tmp.chop(1); result.d->stdOut = tmp.split(QLatin1Char('\n')); } tmp = filterProcessOutput(m_process.readAllStandardError(), processCommand()->stderrFilterFunction()); if (!tmp.isEmpty()) { if (tmp.endsWith(QLatin1Char('\n'))) tmp.chop(1); result.d->stdErr = tmp.split(QLatin1Char('\n')); } emit reportProcessResult(result); } void ProcessCommandExecutor::onProcessError() { sendProcessOutput(false); removeResponseFile(); QString errorMessage; const QString binary = QDir::toNativeSeparators(processCommand()->program()); switch (m_process.error()) { case QProcess::FailedToStart: errorMessage = Tr::tr("The process '%1' could not be started: %2"). arg(binary, m_process.errorString()); break; case QProcess::Crashed: errorMessage = Tr::tr("The process '%1' crashed.").arg(binary); break; case QProcess::Timedout: errorMessage = Tr::tr("The process '%1' timed out.").arg(binary); break; case QProcess::ReadError: errorMessage = Tr::tr("Error reading process output from '%1'.").arg(binary); break; case QProcess::WriteError: errorMessage = Tr::tr("Error writing to process '%1'.").arg(binary); break; default: errorMessage = Tr::tr("Unknown process error running '%1'.").arg(binary); break; } emit error(ErrorInfo(errorMessage)); } void ProcessCommandExecutor::onProcessFinished(int exitCode) { removeResponseFile(); const bool errorOccurred = exitCode > processCommand()->maxExitCode(); sendProcessOutput(!errorOccurred); if (Q_UNLIKELY(errorOccurred)) { emit error(ErrorInfo(Tr::tr("Process failed with exit code %1.").arg(exitCode))); return; } emit finished(); } void ProcessCommandExecutor::removeResponseFile() { if (m_responseFileName.isEmpty()) return; QFile::remove(m_responseFileName); m_responseFileName.clear(); } QString ProcessCommandExecutor::findProcessCommandInPath() { const ResolvedProductPtr product = transformer()->product(); const ProcessCommand * const cmd = processCommand(); QString fullProgramPath = product->executablePathCache.value(cmd->program()); if (!fullProgramPath.isEmpty()) return fullProgramPath; fullProgramPath = cmd->program(); if (logger().traceEnabled()) logger().qbsTrace() << "[EXEC] looking for executable in PATH " << fullProgramPath; const QProcessEnvironment &buildEnvironment = product->buildEnvironment; QStringList pathEnv = buildEnvironment.value("PATH").split(HostOsInfo::pathListSeparator(), QString::SkipEmptyParts); if (HostOsInfo::isWindowsHost()) pathEnv.prepend(QLatin1String(".")); for (int i = 0; i < pathEnv.count(); ++i) { QString directory = pathEnv.at(i); if (directory == QLatin1String(".")) directory = cmd->workingDir(); if (!directory.isEmpty()) { const QChar lastChar = directory.at(directory.count() - 1); if (lastChar != QLatin1Char('/') && lastChar != QLatin1Char('\\')) directory.append(QLatin1Char('/')); } if (findProcessCandidateCheck(directory, fullProgramPath, fullProgramPath)) break; } product->executablePathCache.insert(cmd->program(), fullProgramPath); return fullProgramPath; } QString ProcessCommandExecutor::findProcessCommandBySuffix() { const ResolvedProductPtr product = transformer()->product(); const ProcessCommand * const cmd = processCommand(); QString fullProgramPath = product->executablePathCache.value(cmd->program()); if (!fullProgramPath.isEmpty()) return fullProgramPath; fullProgramPath = cmd->program(); if (logger().traceEnabled()) logger().qbsTrace() << "[EXEC] looking for executable by suffix " << fullProgramPath; const QString emptyDirectory; findProcessCandidateCheck(emptyDirectory, fullProgramPath, fullProgramPath); product->executablePathCache.insert(cmd->program(), fullProgramPath); return fullProgramPath; } bool ProcessCommandExecutor::findProcessCandidateCheck(const QString &directory, const QString &program, QString &fullProgramPath) { for (int i = 0; i < m_executableSuffixes.count(); ++i) { QString candidate = directory + program + m_executableSuffixes.at(i); if (logger().traceEnabled()) logger().qbsTrace() << "[EXEC] candidate: " << candidate; if (FileInfo::exists(candidate)) { fullProgramPath = candidate; return true; } } return false; } const ProcessCommand *ProcessCommandExecutor::processCommand() const { return static_cast<const ProcessCommand *>(command()); } } // namespace Internal } // namespace qbs <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cassert> #include <fstream> #include <sstream> #include <boost/asio.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <coin/android.hpp> #include <coin/configuration.hpp> #include <coin/filesystem.hpp> #include <coin/logger.hpp> #include <coin/network.hpp> #include <coin/protocol.hpp> #include <coin/zerotime.hpp> #include <coin/wallet.hpp> using namespace coin; configuration::configuration() : m_network_port_tcp(protocol::default_tcp_port) , m_network_tcp_inbound_maximum(network::tcp_inbound_maximum) , m_network_udp_enable(false) , m_wallet_transaction_history_maximum(wallet::configuration_interval_history) , m_wallet_keypool_size(wallet::configuration_keypool_size) , m_zerotime_depth(zerotime::depth) , m_zerotime_answers_minimum(zerotime::answers_minimum) , m_wallet_rescan(false) , m_mining_proof_of_stake(true) { // ... } bool configuration::load() { log_info("Configuration is loading from disk."); boost::property_tree::ptree pt; try { std::stringstream ss; /** * Read the json configuration from disk. */ read_json(filesystem::data_path() + "config.dat", pt); /** * Get the version. */ auto file_version = std::stoul( pt.get("version", std::to_string(version)) ); (void)file_version; log_debug("Configuration read version = " << file_version << "."); assert(file_version == version); /** * Get the network.tcp.port */ m_network_port_tcp = std::stoul( pt.get("network.tcp.port", std::to_string(protocol::default_tcp_port)) ); log_debug( "Configuration read network.tcp.port = " << m_network_port_tcp << "." ); /** * Get the network.tcp.inbound.maximum. */ m_network_tcp_inbound_maximum = std::stoul(pt.get( "network.tcp.inbound.maximum", std::to_string(network::tcp_inbound_maximum)) ); log_debug( "Configuration read network.tcp.inbound.maximum = " << m_network_tcp_inbound_maximum << "." ); /** * Enforce the minimum network.tcp.inbound.maximum. */ if (m_network_tcp_inbound_maximum < network::tcp_inbound_minimum) { m_network_tcp_inbound_maximum = network::tcp_inbound_minimum; } /** * Get the network.udp.enable. */ m_network_udp_enable = std::stoul(pt.get( "network.udp.enable", std::to_string(false)) ); log_debug( "Configuration read network.udp.enable = " << m_network_udp_enable << "." ); /** * Get the wallet.transaction.history.maximum. */ m_wallet_transaction_history_maximum = std::stoul(pt.get( "wallet.transaction.history.maximum", std::to_string(m_wallet_transaction_history_maximum)) ); log_debug( "Configuration read wallet.transaction.history.maximum = " << m_wallet_transaction_history_maximum << "." ); /** * Get the wallet.keypool.size. */ m_wallet_keypool_size = std::stoi(pt.get( "wallet.keypool.size", std::to_string(m_wallet_keypool_size)) ); log_debug( "Configuration read wallet.keypool.size = " << m_wallet_keypool_size << "." ); /** * Get the zerotime.depth. */ m_zerotime_depth = std::stoi(pt.get( "zerotime.depth", std::to_string(m_zerotime_depth)) ); log_debug( "Configuration read zerotime.depth = " << static_cast<std::uint32_t> (m_zerotime_depth) << "." ); /** * Get the zerotime.answers.minimum. */ m_zerotime_answers_minimum = std::stoi(pt.get( "zerotime.answers.minimum", std::to_string(m_zerotime_answers_minimum)) ); /** * Enforce the minimum zerotime.answers.minimum. */ if (m_zerotime_answers_minimum < zerotime::answers_maximum) { m_zerotime_answers_minimum = zerotime::answers_maximum; } log_debug( "Configuration read zerotime.answers.minimum = " << static_cast<std::uint32_t> (m_zerotime_answers_minimum) << "." ); /** * Get the wallet.rescan. */ m_wallet_rescan = std::stoi(pt.get( "wallet.rescan", std::to_string(m_wallet_rescan)) ); log_debug( "Configuration read wallet.rescan = " << m_wallet_rescan << "." ); /** * Get the mining.proof-of-stake. */ m_mining_proof_of_stake = std::stoi(pt.get( "mining.proof-of-stake", std::to_string(m_mining_proof_of_stake)) ); log_debug( "Configuration read mining.proof-of-stake = " << m_mining_proof_of_stake << "." ); } catch (std::exception & e) { log_error("Configuration failed to load, what = " << e.what() << "."); return false; } if (m_args.size() > 0) { #if (!defined _MSC_VER) #warning :TODO: Iterate the args and override the variables (if found). #endif } return true; } bool configuration::save() { log_info("Configuration is saving to disk."); try { boost::property_tree::ptree pt; /** * Put the version into property tree. */ pt.put("version", std::to_string(version)); /** * Put the network.tcp.port into property tree. */ pt.put("network.tcp.port", std::to_string(m_network_port_tcp)); /** * Put the network.tcp.inbound.maximum into property tree. */ pt.put( "network.tcp.inbound.maximum", std::to_string(m_network_tcp_inbound_maximum) ); /** * Put the network.udp.enable into property tree. */ pt.put( "network.udp.enable", std::to_string(m_network_udp_enable) ); /** * Put the wallet.transaction.history.maximum into property tree. */ pt.put( "wallet.transaction.history.maximum", std::to_string(m_wallet_transaction_history_maximum) ); /** * Put the wallet.keypool.size into property tree. */ pt.put( "wallet.keypool.size", std::to_string(m_wallet_keypool_size) ); /** * Put the zerotime.depth into property tree. */ pt.put( "zerotime.depth", std::to_string(m_zerotime_depth) ); /** * Put the zerotime.answers.minimum into property tree. */ pt.put( "zerotime.answers.minimum", std::to_string(m_zerotime_answers_minimum) ); /** * Put the wallet.rescan into property tree. */ pt.put( "wallet.rescan", std::to_string(m_wallet_rescan) ); /** * Put the mining.proof-of-stake into property tree. */ pt.put( "mining.proof-of-stake", std::to_string(m_mining_proof_of_stake) ); /** * The std::stringstream. */ std::stringstream ss; /** * Write property tree to json file. */ write_json(ss, pt, false); /** * Open the output file stream. */ std::ofstream ofs( filesystem::data_path() + "config.dat" ); /** * Write the json. */ ofs << ss.str(); /** * Flush to disk. */ ofs.flush(); } catch (std::exception & e) { log_error("Configuration failed to save, what = " << e.what() << "."); return false; } return true; } void configuration::set_args(const std::map<std::string, std::string> & val) { m_args = val; } std::map<std::string, std::string> & configuration::args() { return m_args; } void configuration::set_network_port_tcp(const std::uint16_t & val) { m_network_port_tcp = val; } const std::uint16_t & configuration::network_port_tcp() const { return m_network_port_tcp; } void configuration::set_network_tcp_inbound_maximum(const std::size_t & val) { if (val < network::tcp_inbound_minimum) { m_network_tcp_inbound_maximum = network::tcp_inbound_minimum; } else { m_network_tcp_inbound_maximum = val; } } const std::size_t & configuration::network_tcp_inbound_maximum() const { return m_network_tcp_inbound_maximum; } void configuration::set_network_udp_enable(const bool & val) { m_network_udp_enable = val; } const bool & configuration::network_udp_enable() const { return m_network_udp_enable; } <commit_msg>Post merge cleanups<commit_after>/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cassert> #include <fstream> #include <sstream> #include <boost/asio.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <coin/android.hpp> #include <coin/configuration.hpp> #include <coin/filesystem.hpp> #include <coin/logger.hpp> #include <coin/network.hpp> #include <coin/protocol.hpp> #include <coin/zerotime.hpp> #include <coin/wallet.hpp> using namespace coin; configuration::configuration() : m_network_port_tcp(protocol::default_tcp_port) , m_network_tcp_inbound_maximum(network::tcp_inbound_maximum) , m_network_udp_enable(false) , m_wallet_transaction_history_maximum(wallet::configuration_interval_history) , m_wallet_keypool_size(wallet::configuration_keypool_size) , m_zerotime_depth(zerotime::depth) , m_zerotime_answers_minimum(zerotime::answers_minimum) , m_wallet_rescan(false) , m_mining_proof_of_stake(true) { // ... } bool configuration::load() { log_info("Configuration is loading from disk."); boost::property_tree::ptree pt; try { std::stringstream ss; /** * Read the json configuration from disk. */ read_json(filesystem::data_path() + "config.dat", pt); /** * Get the version. */ auto file_version = std::stoul( pt.get("version", std::to_string(version)) ); (void)file_version; log_debug("Configuration read version = " << file_version << "."); assert(file_version == version); /** * Get the network.tcp.port */ m_network_port_tcp = std::stoul( pt.get("network.tcp.port", std::to_string(protocol::default_tcp_port)) ); log_debug( "Configuration read network.tcp.port = " << m_network_port_tcp << "." ); /** * Get the network.tcp.inbound.maximum. */ m_network_tcp_inbound_maximum = std::stoul(pt.get( "network.tcp.inbound.maximum", std::to_string(network::tcp_inbound_maximum)) ); log_debug( "Configuration read network.tcp.inbound.maximum = " << m_network_tcp_inbound_maximum << "." ); /** * Enforce the minimum network.tcp.inbound.maximum. */ if (m_network_tcp_inbound_maximum < network::tcp_inbound_minimum) { m_network_tcp_inbound_maximum = network::tcp_inbound_minimum; } /** * Get the network.udp.enable. */ m_network_udp_enable = std::stoul(pt.get( "network.udp.enable", std::to_string(false)) ); log_debug( "Configuration read network.udp.enable = " << m_network_udp_enable << "." ); /** * Get the wallet.transaction.history.maximum. */ m_wallet_transaction_history_maximum = std::stoul(pt.get( "wallet.transaction.history.maximum", std::to_string(m_wallet_transaction_history_maximum)) ); log_debug( "Configuration read wallet.transaction.history.maximum = " << m_wallet_transaction_history_maximum << "." ); /** * Get the wallet.keypool.size. */ m_wallet_keypool_size = std::stoi(pt.get( "wallet.keypool.size", std::to_string(m_wallet_keypool_size)) ); log_debug( "Configuration read wallet.keypool.size = " << m_wallet_keypool_size << "." ); /** * Get the zerotime.depth. */ m_zerotime_depth = std::stoi(pt.get( "zerotime.depth", std::to_string(m_zerotime_depth)) ); log_debug( "Configuration read zerotime.depth = " << static_cast<std::uint32_t> (m_zerotime_depth) << "." ); /** * Get the zerotime.answers.minimum. */ m_zerotime_answers_minimum = std::stoi(pt.get( "zerotime.answers.minimum", std::to_string(m_zerotime_answers_minimum)) ); /** * Enforce the minimum zerotime.answers.minimum. */ if (m_zerotime_answers_minimum > zerotime::answers_maximum) { m_zerotime_answers_minimum = zerotime::answers_maximum; } log_debug( "Configuration read zerotime.answers.minimum = " << static_cast<std::uint32_t> (m_zerotime_answers_minimum) << "." ); /** * Get the wallet.rescan. */ m_wallet_rescan = std::stoi(pt.get( "wallet.rescan", std::to_string(m_wallet_rescan)) ); log_debug( "Configuration read wallet.rescan = " << m_wallet_rescan << "." ); /** * Get the mining.proof-of-stake. */ m_mining_proof_of_stake = std::stoi(pt.get( "mining.proof-of-stake", std::to_string(m_mining_proof_of_stake)) ); log_debug( "Configuration read mining.proof-of-stake = " << m_mining_proof_of_stake << "." ); } catch (std::exception & e) { log_error("Configuration failed to load, what = " << e.what() << "."); return false; } if (m_args.size() > 0) { #if (!defined _MSC_VER) #warning :TODO: Iterate the args and override the variables (if found). #endif } return true; } bool configuration::save() { log_info("Configuration is saving to disk."); try { boost::property_tree::ptree pt; /** * Put the version into property tree. */ pt.put("version", std::to_string(version)); /** * Put the network.tcp.port into property tree. */ pt.put("network.tcp.port", std::to_string(m_network_port_tcp)); /** * Put the network.tcp.inbound.maximum into property tree. */ pt.put( "network.tcp.inbound.maximum", std::to_string(m_network_tcp_inbound_maximum) ); /** * Put the network.udp.enable into property tree. */ pt.put( "network.udp.enable", std::to_string(m_network_udp_enable) ); /** * Put the wallet.transaction.history.maximum into property tree. */ pt.put( "wallet.transaction.history.maximum", std::to_string(m_wallet_transaction_history_maximum) ); /** * Put the wallet.keypool.size into property tree. */ pt.put( "wallet.keypool.size", std::to_string(m_wallet_keypool_size) ); /** * Put the zerotime.depth into property tree. */ pt.put( "zerotime.depth", std::to_string(m_zerotime_depth) ); /** * Put the zerotime.answers.minimum into property tree. */ pt.put( "zerotime.answers.minimum", std::to_string(m_zerotime_answers_minimum) ); /** * Put the wallet.rescan into property tree. */ pt.put( "wallet.rescan", std::to_string(m_wallet_rescan) ); /** * Put the mining.proof-of-stake into property tree. */ pt.put( "mining.proof-of-stake", std::to_string(m_mining_proof_of_stake) ); /** * The std::stringstream. */ std::stringstream ss; /** * Write property tree to json file. */ write_json(ss, pt, false); /** * Open the output file stream. */ std::ofstream ofs( filesystem::data_path() + "config.dat" ); /** * Write the json. */ ofs << ss.str(); /** * Flush to disk. */ ofs.flush(); } catch (std::exception & e) { log_error("Configuration failed to save, what = " << e.what() << "."); return false; } return true; } void configuration::set_args(const std::map<std::string, std::string> & val) { m_args = val; } std::map<std::string, std::string> & configuration::args() { return m_args; } void configuration::set_network_port_tcp(const std::uint16_t & val) { m_network_port_tcp = val; } const std::uint16_t & configuration::network_port_tcp() const { return m_network_port_tcp; } void configuration::set_network_tcp_inbound_maximum(const std::size_t & val) { if (val < network::tcp_inbound_minimum) { m_network_tcp_inbound_maximum = network::tcp_inbound_minimum; } else { m_network_tcp_inbound_maximum = val; } } const std::size_t & configuration::network_tcp_inbound_maximum() const { return m_network_tcp_inbound_maximum; } void configuration::set_network_udp_enable(const bool & val) { m_network_udp_enable = val; } const bool & configuration::network_udp_enable() const { return m_network_udp_enable; } <|endoftext|>
<commit_before>/* * * Copyright 2019 Asylo authors * * 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 "asylo/util/lock_guard.h" #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" #include "asylo/platform/core/trusted_mutex.h" #include "asylo/platform/core/trusted_spin_lock.h" #include "asylo/util/thread.h" namespace asylo { namespace { using ::testing::InSequence; using ::testing::StrictMock; // The most boring and incorrect fake lock. class MockLock { public: MOCK_METHOD(void, Lock, ()); MOCK_METHOD(void, Marker, ()); MOCK_METHOD(void, Unlock, ()); }; TEST(MockLockGuardTest, LockOnce) { StrictMock<MockLock> lock; { // Guarantee Lock happens before Unlock by using InSequence. InSequence s; EXPECT_CALL(lock, Marker()).Times(1); EXPECT_CALL(lock, Lock()).Times(1); EXPECT_CALL(lock, Marker()).Times(1); EXPECT_CALL(lock, Unlock()).Times(1); EXPECT_CALL(lock, Marker()).Times(1); } lock.Marker(); { LockGuard guard(&lock); lock.Marker(); } lock.Marker(); } static constexpr int kNumThreads = 6; static constexpr int kNumIters = 500; // Enable testing with multiple different lock types by parameterizing // tests over the lock type. template <class T> class OneArgLockGuardTest : public testing::Test {}; TYPED_TEST_SUITE_P(OneArgLockGuardTest); template <typename LockType> void increment_then_decrement(volatile int* counter, int original_value, LockType* lock) { LockGuard guard(lock); EXPECT_EQ(*counter, original_value); *counter = *counter + 1; EXPECT_EQ(*counter, original_value + 1); *counter = *counter - 1; EXPECT_EQ(*counter, original_value); } // Ensure that the LockGuard correctly acquires and releases the lock, // by using it for mutual exclusion. TYPED_TEST_P(OneArgLockGuardTest, OneArgOneLockNonrecursive) { TypeParam lock(/*is_recursive = */ false); volatile int counter GUARDED_BY(lock) = 0; std::vector<Thread> threads; for (int i = 0; i < kNumThreads; i++) { threads.emplace_back([&counter, &lock] { for (int j = 0; j < kNumIters; j++) { increment_then_decrement(&counter, 0, &lock); } }); } for (auto& thread : threads) { thread.Join(); } } // Ensure that the LockGuard correctly acquires and releases the lock, // in a re-entrant (or recursive) case. TYPED_TEST_P(OneArgLockGuardTest, OneArgOneLockRecursive) { TypeParam lock(/*is_recursive = */ true); volatile int counter GUARDED_BY(lock) = 0; std::vector<Thread> threads; for (int i = 0; i < kNumThreads; i++) { threads.emplace_back([&counter, &lock] { for (int j = 0; j < kNumIters; j++) { LockGuard guard(&lock); EXPECT_EQ(counter, 0); counter++; EXPECT_EQ(counter, 1); { increment_then_decrement(&counter, 1, &lock); } EXPECT_EQ(counter, 1); counter--; EXPECT_EQ(counter, 0); } }); } for (auto& thread : threads) { thread.Join(); } } REGISTER_TYPED_TEST_SUITE_P(OneArgLockGuardTest, OneArgOneLockRecursive, OneArgOneLockNonrecursive); typedef testing::Types<TrustedMutex, TrustedSpinLock> OneArgLockTypes; INSTANTIATE_TYPED_TEST_SUITE_P(LockGuardAllLocksTest, OneArgLockGuardTest, OneArgLockTypes); template <class T> class ZeroArgLockGuardTest : public testing::Test {}; TYPED_TEST_SUITE_P(ZeroArgLockGuardTest); // Ensure that the LockGuard correctly acquires and releases the lock, // by using it for mutual exclusion. TYPED_TEST_P(ZeroArgLockGuardTest, ZeroArgOneLock) { TypeParam lock; volatile int counter GUARDED_BY(lock) = 0; std::vector<Thread> threads; for (int i = 0; i < kNumThreads; i++) { threads.emplace_back([&counter, &lock] { for (int j = 0; j < kNumIters; j++) { increment_then_decrement(&counter, 0, &lock); } }); } for (auto& thread : threads) { thread.Join(); } } REGISTER_TYPED_TEST_SUITE_P(ZeroArgLockGuardTest, ZeroArgOneLock); typedef testing::Types<absl::Mutex> ZeroArgLockTypes; INSTANTIATE_TYPED_TEST_SUITE_P(LockGuardAllLocksTest, ZeroArgLockGuardTest, ZeroArgLockTypes); } // namespace } // namespace asylo <commit_msg>Abseil thread annotation macros are now prefixed by ABSL_<commit_after>/* * * Copyright 2019 Asylo authors * * 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 "asylo/util/lock_guard.h" #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" #include "asylo/platform/core/trusted_mutex.h" #include "asylo/platform/core/trusted_spin_lock.h" #include "asylo/util/thread.h" namespace asylo { namespace { using ::testing::InSequence; using ::testing::StrictMock; // The most boring and incorrect fake lock. class MockLock { public: MOCK_METHOD(void, Lock, ()); MOCK_METHOD(void, Marker, ()); MOCK_METHOD(void, Unlock, ()); }; TEST(MockLockGuardTest, LockOnce) { StrictMock<MockLock> lock; { // Guarantee Lock happens before Unlock by using InSequence. InSequence s; EXPECT_CALL(lock, Marker()).Times(1); EXPECT_CALL(lock, Lock()).Times(1); EXPECT_CALL(lock, Marker()).Times(1); EXPECT_CALL(lock, Unlock()).Times(1); EXPECT_CALL(lock, Marker()).Times(1); } lock.Marker(); { LockGuard guard(&lock); lock.Marker(); } lock.Marker(); } static constexpr int kNumThreads = 6; static constexpr int kNumIters = 500; // Enable testing with multiple different lock types by parameterizing // tests over the lock type. template <class T> class OneArgLockGuardTest : public testing::Test {}; TYPED_TEST_SUITE_P(OneArgLockGuardTest); template <typename LockType> void increment_then_decrement(volatile int* counter, int original_value, LockType* lock) { LockGuard guard(lock); EXPECT_EQ(*counter, original_value); *counter = *counter + 1; EXPECT_EQ(*counter, original_value + 1); *counter = *counter - 1; EXPECT_EQ(*counter, original_value); } // Ensure that the LockGuard correctly acquires and releases the lock, // by using it for mutual exclusion. TYPED_TEST_P(OneArgLockGuardTest, OneArgOneLockNonrecursive) { TypeParam lock(/*is_recursive = */ false); volatile int counter ABSL_GUARDED_BY(lock) = 0; std::vector<Thread> threads; for (int i = 0; i < kNumThreads; i++) { threads.emplace_back([&counter, &lock] { for (int j = 0; j < kNumIters; j++) { increment_then_decrement(&counter, 0, &lock); } }); } for (auto& thread : threads) { thread.Join(); } } // Ensure that the LockGuard correctly acquires and releases the lock, // in a re-entrant (or recursive) case. TYPED_TEST_P(OneArgLockGuardTest, OneArgOneLockRecursive) { TypeParam lock(/*is_recursive = */ true); volatile int counter ABSL_GUARDED_BY(lock) = 0; std::vector<Thread> threads; for (int i = 0; i < kNumThreads; i++) { threads.emplace_back([&counter, &lock] { for (int j = 0; j < kNumIters; j++) { LockGuard guard(&lock); EXPECT_EQ(counter, 0); counter++; EXPECT_EQ(counter, 1); { increment_then_decrement(&counter, 1, &lock); } EXPECT_EQ(counter, 1); counter--; EXPECT_EQ(counter, 0); } }); } for (auto& thread : threads) { thread.Join(); } } REGISTER_TYPED_TEST_SUITE_P(OneArgLockGuardTest, OneArgOneLockRecursive, OneArgOneLockNonrecursive); typedef testing::Types<TrustedMutex, TrustedSpinLock> OneArgLockTypes; INSTANTIATE_TYPED_TEST_SUITE_P(LockGuardAllLocksTest, OneArgLockGuardTest, OneArgLockTypes); template <class T> class ZeroArgLockGuardTest : public testing::Test {}; TYPED_TEST_SUITE_P(ZeroArgLockGuardTest); // Ensure that the LockGuard correctly acquires and releases the lock, // by using it for mutual exclusion. TYPED_TEST_P(ZeroArgLockGuardTest, ZeroArgOneLock) { TypeParam lock; volatile int counter ABSL_GUARDED_BY(lock) = 0; std::vector<Thread> threads; for (int i = 0; i < kNumThreads; i++) { threads.emplace_back([&counter, &lock] { for (int j = 0; j < kNumIters; j++) { increment_then_decrement(&counter, 0, &lock); } }); } for (auto& thread : threads) { thread.Join(); } } REGISTER_TYPED_TEST_SUITE_P(ZeroArgLockGuardTest, ZeroArgOneLock); typedef testing::Types<absl::Mutex> ZeroArgLockTypes; INSTANTIATE_TYPED_TEST_SUITE_P(LockGuardAllLocksTest, ZeroArgLockGuardTest, ZeroArgLockTypes); } // namespace } // namespace asylo <|endoftext|>
<commit_before>//#define ENABLE_DEBUG_TRACES #include "libport/compiler.hh" #include "libport/unistd.h" #include "libport/sysexits.hh" #include "libport/windows.hh" #include <iostream> #include <fstream> #include <algorithm> #include <boost/foreach.hpp> #include "libport/cli.hh" #include "libport/program-name.hh" #include "libport/tokenizer.hh" #include "libport/utime.hh" #include "libport/read-stdin.hh" #include "libport/exception.hh" // Inclusion order matters for windows. Leave userver.hh after network.hh. #include <network/bsdnet/network.hh> #include "kernel/userver.hh" #include "kernel/uconnection.hh" #include "ubanner.hh" class ConsoleServer : public UServer { public: ConsoleServer(int period, bool fast) : UServer(period, "console"), fast(fast), ctime(0) { if (const char* cp = getenv ("URBI_PATH")) { std::string up(cp); std::list<std::string> paths; BOOST_FOREACH (const std::string& s, libport::make_tokenizer(up, ":")) { if (s[0] == '\\' && paths.back().length() == 1) paths.back() += ':' + s; else paths.push_back(s); } BOOST_FOREACH (const std::string& s, paths) search_path.append_dir(s); } } virtual ~ConsoleServer() {} virtual void shutdown() { UServer::shutdown (); exit (EX_OK); } virtual void beforeWork() { ctime += static_cast<libport::utime_t>(period_get()) * 1000LL; } virtual void reset() {} virtual void reboot() {} virtual libport::utime_t getTime() { if (fast) return ctime; else return libport::utime(); } virtual ufloat getPower() { return ufloat(1); } //! Called to display the header at each coonection start virtual void getCustomHeader(int line, char* header, int maxlength) { // FIXME: This interface is really really ridiculous and fragile. strncpy(header, uconsole_banner[line], maxlength); } virtual UErrorValue saveFile (const std::string& filename, const std::string& content) { //! \todo check this code std::ofstream os (filename.c_str ()); os << content; os.close (); return os.good () ? USUCCESS : UFAIL; } virtual void effectiveDisplay(const char* t) { std::cout << t; } bool fast; libport::utime_t ctime; }; namespace { static void usage () { std::cout << "usage: " << libport::program_name << " [OPTIONS] [FILE]\n" "\n" " FILE to load\n" "\n" "Options:\n" " -h, --help display this message and exit successfully\n" " -v, --version display version information\n" " -P, --period PERIOD base URBI interval in milliseconds\n" " -p, --port PORT tcp port URBI will listen to.\n" " -f, --fast ignore system time, go as fast as possible\n" " -i, --interactive read and parse stdin in a nonblocking way\n" " -w, --port-file FILE write port number to specified file.\n" ; exit (EX_OK); } static void version () { userver_package_info_dump(std::cout) << std::endl; exit (EX_OK); } } int main (int argc, const char* argv[]) { libport::program_name = argv[0]; // Input file. const char* in = "/dev/stdin"; /// The period. int arg_period = 32; /// The port to use. 0 means automatic selection. int arg_port = 0; /// Where to write the port we use. const char* arg_port_filename = 0; /// fast mode bool fast = false; /// interactive mode bool interactive = false; // Parse the command line. { int argp = 1; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "--fast" || arg == "-f") fast = true; else if (arg == "--help" || arg == "-h") usage(); else if (arg == "--interactive" || arg == "-i") interactive = true; else if (arg == "--period" || arg == "-P") arg_period = libport::convert_argument<int> (arg, argv[++i]); else if (arg == "--port" || arg == "-p") arg_port = libport::convert_argument<int> (arg, argv[++i]); else if (arg == "--port-file" || arg == "-w") arg_port_filename = argv[++i]; else if (arg == "--version" || arg == "-v") version(); else if (arg[0] == '-') libport::invalid_option (arg); else // An argument. switch (argp++) { case 1: in = argv[i]; break; default: std::cerr << libport::program_name << ": unexpected argument: " << arg << std::endl << libport::exit (EX_USAGE); break; } } } ConsoleServer s (arg_period, fast); int port = Network::createTCPServer(arg_port, "localhost"); if (!port) std::cerr << libport::program_name << ": cannot bind to port " << arg_port << " on localhost" << std::endl << libport::exit (EX_UNAVAILABLE); if (arg_port_filename) std::ofstream(arg_port_filename, std::ios::out) << port << std::endl; s.initialize (); UConnection& c = s.getGhostConnection (); std::cerr << libport::program_name << ": got ghost connection" << std::endl; if (!interactive) if (s.loadFile(in, c.recv_queue_get ()) != USUCCESS) std::cerr << libport::program_name << ": failed to process " << in << std::endl << libport::exit(EX_NOINPUT); c.new_data_added_get() = true; std::cerr << libport::program_name << ": going to work..." << std::endl; libport::utime_t next_time = 0; while (true) { if (interactive) { std::string input; try { input = libport::read_stdin(); } catch(libport::exception::Exception e) { std::cerr << e.what() << std::endl; interactive = false; } if (!input.empty()) s.getGhostConnection ().received (input.c_str(), input.length()); } libport::utime_t select_time = 0; if (!fast) { libport::utime_t ctime = libport::utime(); if (ctime < next_time) select_time = next_time - ctime; if (interactive) select_time = std::min(100000LL, select_time); } Network::selectAndProcess(select_time); next_time = s.work (); } } <commit_msg>Make the console server work correctly in --fast<commit_after>//#define ENABLE_DEBUG_TRACES #include "libport/compiler.hh" #include "libport/unistd.h" #include "libport/sysexits.hh" #include "libport/windows.hh" #include <iostream> #include <fstream> #include <algorithm> #include <boost/foreach.hpp> #include "libport/cli.hh" #include "libport/program-name.hh" #include "libport/tokenizer.hh" #include "libport/utime.hh" #include "libport/read-stdin.hh" #include "libport/exception.hh" // Inclusion order matters for windows. Leave userver.hh after network.hh. #include <network/bsdnet/network.hh> #include "kernel/userver.hh" #include "kernel/uconnection.hh" #include "ubanner.hh" class ConsoleServer : public UServer { public: ConsoleServer(int period, bool fast) : UServer(period, "console"), fast(fast), ctime(0) { if (const char* cp = getenv ("URBI_PATH")) { std::string up(cp); std::list<std::string> paths; BOOST_FOREACH (const std::string& s, libport::make_tokenizer(up, ":")) { if (s[0] == '\\' && paths.back().length() == 1) paths.back() += ':' + s; else paths.push_back(s); } BOOST_FOREACH (const std::string& s, paths) search_path.append_dir(s); } } virtual ~ConsoleServer() {} virtual void shutdown() { UServer::shutdown (); exit (EX_OK); } virtual void beforeWork() { } virtual void reset() {} virtual void reboot() {} virtual libport::utime_t getTime() { if (fast) return ctime; else return libport::utime(); } virtual ufloat getPower() { return ufloat(1); } //! Called to display the header at each coonection start virtual void getCustomHeader(int line, char* header, int maxlength) { // FIXME: This interface is really really ridiculous and fragile. strncpy(header, uconsole_banner[line], maxlength); } virtual UErrorValue saveFile (const std::string& filename, const std::string& content) { //! \todo check this code std::ofstream os (filename.c_str ()); os << content; os.close (); return os.good () ? USUCCESS : UFAIL; } virtual void effectiveDisplay(const char* t) { std::cout << t; } bool fast; libport::utime_t ctime; }; namespace { static void usage () { std::cout << "usage: " << libport::program_name << " [OPTIONS] [FILE]\n" "\n" " FILE to load\n" "\n" "Options:\n" " -h, --help display this message and exit successfully\n" " -v, --version display version information\n" " -P, --period PERIOD base URBI interval in milliseconds\n" " -p, --port PORT tcp port URBI will listen to.\n" " -f, --fast ignore system time, go as fast as possible\n" " -i, --interactive read and parse stdin in a nonblocking way\n" " -w, --port-file FILE write port number to specified file.\n" ; exit (EX_OK); } static void version () { userver_package_info_dump(std::cout) << std::endl; exit (EX_OK); } } int main (int argc, const char* argv[]) { libport::program_name = argv[0]; // Input file. const char* in = "/dev/stdin"; /// The period. int arg_period = 32; /// The port to use. 0 means automatic selection. int arg_port = 0; /// Where to write the port we use. const char* arg_port_filename = 0; /// fast mode bool fast = false; /// interactive mode bool interactive = false; // Parse the command line. { int argp = 1; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "--fast" || arg == "-f") fast = true; else if (arg == "--help" || arg == "-h") usage(); else if (arg == "--interactive" || arg == "-i") interactive = true; else if (arg == "--period" || arg == "-P") arg_period = libport::convert_argument<int> (arg, argv[++i]); else if (arg == "--port" || arg == "-p") arg_port = libport::convert_argument<int> (arg, argv[++i]); else if (arg == "--port-file" || arg == "-w") arg_port_filename = argv[++i]; else if (arg == "--version" || arg == "-v") version(); else if (arg[0] == '-') libport::invalid_option (arg); else // An argument. switch (argp++) { case 1: in = argv[i]; break; default: std::cerr << libport::program_name << ": unexpected argument: " << arg << std::endl << libport::exit (EX_USAGE); break; } } } ConsoleServer s (arg_period, fast); int port = Network::createTCPServer(arg_port, "localhost"); if (!port) std::cerr << libport::program_name << ": cannot bind to port " << arg_port << " on localhost" << std::endl << libport::exit (EX_UNAVAILABLE); if (arg_port_filename) std::ofstream(arg_port_filename, std::ios::out) << port << std::endl; s.initialize (); UConnection& c = s.getGhostConnection (); std::cerr << libport::program_name << ": got ghost connection" << std::endl; if (!interactive) if (s.loadFile(in, c.recv_queue_get ()) != USUCCESS) std::cerr << libport::program_name << ": failed to process " << in << std::endl << libport::exit(EX_NOINPUT); c.new_data_added_get() = true; std::cerr << libport::program_name << ": going to work..." << std::endl; libport::utime_t next_time = 0; while (true) { if (interactive) { std::string input; try { input = libport::read_stdin(); } catch(libport::exception::Exception e) { std::cerr << e.what() << std::endl; interactive = false; } if (!input.empty()) s.getGhostConnection ().received (input.c_str(), input.length()); } libport::utime_t select_time = 0; if (!fast) { libport::utime_t ctime = libport::utime(); if (ctime < next_time) select_time = next_time - ctime; if (interactive) select_time = std::min(100000LL, select_time); } Network::selectAndProcess(select_time); next_time = s.work (); s.ctime = std::max (next_time, s.ctime + 1000L); } } <|endoftext|>
<commit_before>/* * Adapted from code copyright 2009-2011 Intel Corporation * Modifications Copyright 2012, Blender Foundation. * * 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. */ //#define __KERNEL_SSE__ #include <stdlib.h> #include "bvh_binning.h" #include "util_algorithm.h" #include "util_boundbox.h" #include "util_types.h" CCL_NAMESPACE_BEGIN /* SSE replacements */ __forceinline void prefetch_L1 (const void* /*ptr*/) { } __forceinline void prefetch_L2 (const void* /*ptr*/) { } __forceinline void prefetch_L3 (const void* /*ptr*/) { } __forceinline void prefetch_NTA(const void* /*ptr*/) { } template<size_t src> __forceinline float extract(const int4& b) { return b[src]; } template<size_t dst> __forceinline const float4 insert(const float4& a, const float b) { float4 r = a; r[dst] = b; return r; } __forceinline int get_best_dimension(const float4& bestSAH) { // return (int)__bsf(movemask(reduce_min(bestSAH) == bestSAH)); float minSAH = min(bestSAH.x, min(bestSAH.y, bestSAH.z)); if(bestSAH.x == minSAH) return 0; else if(bestSAH.y == minSAH) return 1; else return 2; } /* BVH Object Binning */ BVHObjectBinning::BVHObjectBinning(const BVHRange& job, BVHReference *prims) : BVHRange(job), splitSAH(FLT_MAX), dim(0), pos(0) { /* compute number of bins to use and precompute scaling factor for binning */ num_bins = min(size_t(MAX_BINS), size_t(4.0f + 0.05f*size())); scale = rcp(cent_bounds().size()) * make_float3((float)num_bins); /* initialize binning counter and bounds */ BoundBox bin_bounds[MAX_BINS][4]; /* bounds for every bin in every dimension */ int4 bin_count[MAX_BINS]; /* number of primitives mapped to bin */ for(size_t i = 0; i < num_bins; i++) { bin_count[i] = make_int4(0); bin_bounds[i][0] = bin_bounds[i][1] = bin_bounds[i][2] = BoundBox::empty; } /* map geometry to bins, unrolled once */ { ssize_t i; for(i = 0; i < ssize_t(size()) - 1; i += 2) { prefetch_L2(&prims[start() + i + 8]); /* map even and odd primitive to bin */ const BVHReference& prim0 = prims[start() + i + 0]; const BVHReference& prim1 = prims[start() + i + 1]; int4 bin0 = get_bin(prim0.bounds()); int4 bin1 = get_bin(prim1.bounds()); /* increase bounds for bins for even primitive */ int b00 = (int)extract<0>(bin0); bin_count[b00][0]++; bin_bounds[b00][0].grow(prim0.bounds()); int b01 = (int)extract<1>(bin0); bin_count[b01][1]++; bin_bounds[b01][1].grow(prim0.bounds()); int b02 = (int)extract<2>(bin0); bin_count[b02][2]++; bin_bounds[b02][2].grow(prim0.bounds()); /* increase bounds of bins for odd primitive */ int b10 = (int)extract<0>(bin1); bin_count[b10][0]++; bin_bounds[b10][0].grow(prim1.bounds()); int b11 = (int)extract<1>(bin1); bin_count[b11][1]++; bin_bounds[b11][1].grow(prim1.bounds()); int b12 = (int)extract<2>(bin1); bin_count[b12][2]++; bin_bounds[b12][2].grow(prim1.bounds()); } /* for uneven number of primitives */ if(i < ssize_t(size())) { /* map primitive to bin */ const BVHReference& prim0 = prims[start() + i]; int4 bin0 = get_bin(prim0.bounds()); /* increase bounds of bins */ int b00 = (int)extract<0>(bin0); bin_count[b00][0]++; bin_bounds[b00][0].grow(prim0.bounds()); int b01 = (int)extract<1>(bin0); bin_count[b01][1]++; bin_bounds[b01][1].grow(prim0.bounds()); int b02 = (int)extract<2>(bin0); bin_count[b02][2]++; bin_bounds[b02][2].grow(prim0.bounds()); } } /* sweep from right to left and compute parallel prefix of merged bounds */ float4 r_area[MAX_BINS]; /* area of bounds of primitives on the right */ float4 r_count[MAX_BINS]; /* number of primitives on the right */ int4 count = make_int4(0); BoundBox bx = BoundBox::empty; BoundBox by = BoundBox::empty; BoundBox bz = BoundBox::empty; for(size_t i = num_bins - 1; i > 0; i--) { count = count + bin_count[i]; r_count[i] = blocks(count); bx = merge(bx,bin_bounds[i][0]); r_area[i][0] = bx.half_area(); by = merge(by,bin_bounds[i][1]); r_area[i][1] = by.half_area(); bz = merge(bz,bin_bounds[i][2]); r_area[i][2] = bz.half_area(); r_area[i][3] = r_area[i][2]; } /* sweep from left to right and compute SAH */ int4 ii = make_int4(1); float4 bestSAH = make_float4(FLT_MAX); int4 bestSplit = make_int4(-1); count = make_int4(0); bx = BoundBox::empty; by = BoundBox::empty; bz = BoundBox::empty; for(size_t i = 1; i < num_bins; i++, ii += make_int4(1)) { count = count + bin_count[i-1]; bx = merge(bx,bin_bounds[i-1][0]); float Ax = bx.half_area(); by = merge(by,bin_bounds[i-1][1]); float Ay = by.half_area(); bz = merge(bz,bin_bounds[i-1][2]); float Az = bz.half_area(); float4 lCount = blocks(count); float4 lArea = make_float4(Ax,Ay,Az,Az); float4 sah = lArea*lCount + r_area[i]*r_count[i]; bestSplit = select(sah < bestSAH,ii,bestSplit); bestSAH = min(sah,bestSAH); } int4 mask = float3_to_float4(cent_bounds().size()) <= make_float4(0.0f); bestSAH = insert<3>(select(mask, make_float4(FLT_MAX), bestSAH), FLT_MAX); /* find best dimension */ dim = get_best_dimension(bestSAH); splitSAH = bestSAH[dim]; pos = bestSplit[dim]; leafSAH = bounds().half_area() * blocks(size()); } void BVHObjectBinning::split(BVHReference* prims, BVHObjectBinning& left_o, BVHObjectBinning& right_o) const { size_t N = size(); BoundBox lgeom_bounds = BoundBox::empty; BoundBox rgeom_bounds = BoundBox::empty; BoundBox lcent_bounds = BoundBox::empty; BoundBox rcent_bounds = BoundBox::empty; ssize_t l = 0, r = N-1; while(l <= r) { prefetch_L2(&prims[start() + l + 8]); prefetch_L2(&prims[start() + r - 8]); BVHReference prim = prims[start() + l]; float3 center = prim.bounds().center2(); if(get_bin(center)[dim] < pos) { lgeom_bounds.grow(prim.bounds()); lcent_bounds.grow(center); l++; } else { rgeom_bounds.grow(prim.bounds()); rcent_bounds.grow(center); swap(prims[start()+l],prims[start()+r]); r--; } } /* finish */ if(l != 0 && N-1-r != 0) { right_o = BVHObjectBinning(BVHRange(rgeom_bounds, rcent_bounds, start() + l, N-1-r), prims); left_o = BVHObjectBinning(BVHRange(lgeom_bounds, lcent_bounds, start(), l), prims); return; } /* object medium split if we did not make progress, can happen when all * primitives have same centroid */ lgeom_bounds = BoundBox::empty; rgeom_bounds = BoundBox::empty; lcent_bounds = BoundBox::empty; rcent_bounds = BoundBox::empty; for(size_t i = 0; i < N/2; i++) { lgeom_bounds.grow(prims[start()+i].bounds()); lcent_bounds.grow(prims[start()+i].bounds().center2()); } for(size_t i = N/2; i < N; i++) { rgeom_bounds.grow(prims[start()+i].bounds()); rcent_bounds.grow(prims[start()+i].bounds().center2()); } right_o = BVHObjectBinning(BVHRange(rgeom_bounds, rcent_bounds, start() + N/2, N/2 + N%2), prims); left_o = BVHObjectBinning(BVHRange(lgeom_bounds, lcent_bounds, start(), N/2), prims); } CCL_NAMESPACE_END <commit_msg>Avoid reference copy<commit_after>/* * Adapted from code copyright 2009-2011 Intel Corporation * Modifications Copyright 2012, Blender Foundation. * * 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. */ //#define __KERNEL_SSE__ #include <stdlib.h> #include "bvh_binning.h" #include "util_algorithm.h" #include "util_boundbox.h" #include "util_types.h" CCL_NAMESPACE_BEGIN /* SSE replacements */ __forceinline void prefetch_L1 (const void* /*ptr*/) { } __forceinline void prefetch_L2 (const void* /*ptr*/) { } __forceinline void prefetch_L3 (const void* /*ptr*/) { } __forceinline void prefetch_NTA(const void* /*ptr*/) { } template<size_t src> __forceinline float extract(const int4& b) { return b[src]; } template<size_t dst> __forceinline const float4 insert(const float4& a, const float b) { float4 r = a; r[dst] = b; return r; } __forceinline int get_best_dimension(const float4& bestSAH) { // return (int)__bsf(movemask(reduce_min(bestSAH) == bestSAH)); float minSAH = min(bestSAH.x, min(bestSAH.y, bestSAH.z)); if(bestSAH.x == minSAH) return 0; else if(bestSAH.y == minSAH) return 1; else return 2; } /* BVH Object Binning */ BVHObjectBinning::BVHObjectBinning(const BVHRange& job, BVHReference *prims) : BVHRange(job), splitSAH(FLT_MAX), dim(0), pos(0) { /* compute number of bins to use and precompute scaling factor for binning */ num_bins = min(size_t(MAX_BINS), size_t(4.0f + 0.05f*size())); scale = rcp(cent_bounds().size()) * make_float3((float)num_bins); /* initialize binning counter and bounds */ BoundBox bin_bounds[MAX_BINS][4]; /* bounds for every bin in every dimension */ int4 bin_count[MAX_BINS]; /* number of primitives mapped to bin */ for(size_t i = 0; i < num_bins; i++) { bin_count[i] = make_int4(0); bin_bounds[i][0] = bin_bounds[i][1] = bin_bounds[i][2] = BoundBox::empty; } /* map geometry to bins, unrolled once */ { ssize_t i; for(i = 0; i < ssize_t(size()) - 1; i += 2) { prefetch_L2(&prims[start() + i + 8]); /* map even and odd primitive to bin */ const BVHReference& prim0 = prims[start() + i + 0]; const BVHReference& prim1 = prims[start() + i + 1]; int4 bin0 = get_bin(prim0.bounds()); int4 bin1 = get_bin(prim1.bounds()); /* increase bounds for bins for even primitive */ int b00 = (int)extract<0>(bin0); bin_count[b00][0]++; bin_bounds[b00][0].grow(prim0.bounds()); int b01 = (int)extract<1>(bin0); bin_count[b01][1]++; bin_bounds[b01][1].grow(prim0.bounds()); int b02 = (int)extract<2>(bin0); bin_count[b02][2]++; bin_bounds[b02][2].grow(prim0.bounds()); /* increase bounds of bins for odd primitive */ int b10 = (int)extract<0>(bin1); bin_count[b10][0]++; bin_bounds[b10][0].grow(prim1.bounds()); int b11 = (int)extract<1>(bin1); bin_count[b11][1]++; bin_bounds[b11][1].grow(prim1.bounds()); int b12 = (int)extract<2>(bin1); bin_count[b12][2]++; bin_bounds[b12][2].grow(prim1.bounds()); } /* for uneven number of primitives */ if(i < ssize_t(size())) { /* map primitive to bin */ const BVHReference& prim0 = prims[start() + i]; int4 bin0 = get_bin(prim0.bounds()); /* increase bounds of bins */ int b00 = (int)extract<0>(bin0); bin_count[b00][0]++; bin_bounds[b00][0].grow(prim0.bounds()); int b01 = (int)extract<1>(bin0); bin_count[b01][1]++; bin_bounds[b01][1].grow(prim0.bounds()); int b02 = (int)extract<2>(bin0); bin_count[b02][2]++; bin_bounds[b02][2].grow(prim0.bounds()); } } /* sweep from right to left and compute parallel prefix of merged bounds */ float4 r_area[MAX_BINS]; /* area of bounds of primitives on the right */ float4 r_count[MAX_BINS]; /* number of primitives on the right */ int4 count = make_int4(0); BoundBox bx = BoundBox::empty; BoundBox by = BoundBox::empty; BoundBox bz = BoundBox::empty; for(size_t i = num_bins - 1; i > 0; i--) { count = count + bin_count[i]; r_count[i] = blocks(count); bx = merge(bx,bin_bounds[i][0]); r_area[i][0] = bx.half_area(); by = merge(by,bin_bounds[i][1]); r_area[i][1] = by.half_area(); bz = merge(bz,bin_bounds[i][2]); r_area[i][2] = bz.half_area(); r_area[i][3] = r_area[i][2]; } /* sweep from left to right and compute SAH */ int4 ii = make_int4(1); float4 bestSAH = make_float4(FLT_MAX); int4 bestSplit = make_int4(-1); count = make_int4(0); bx = BoundBox::empty; by = BoundBox::empty; bz = BoundBox::empty; for(size_t i = 1; i < num_bins; i++, ii += make_int4(1)) { count = count + bin_count[i-1]; bx = merge(bx,bin_bounds[i-1][0]); float Ax = bx.half_area(); by = merge(by,bin_bounds[i-1][1]); float Ay = by.half_area(); bz = merge(bz,bin_bounds[i-1][2]); float Az = bz.half_area(); float4 lCount = blocks(count); float4 lArea = make_float4(Ax,Ay,Az,Az); float4 sah = lArea*lCount + r_area[i]*r_count[i]; bestSplit = select(sah < bestSAH,ii,bestSplit); bestSAH = min(sah,bestSAH); } int4 mask = float3_to_float4(cent_bounds().size()) <= make_float4(0.0f); bestSAH = insert<3>(select(mask, make_float4(FLT_MAX), bestSAH), FLT_MAX); /* find best dimension */ dim = get_best_dimension(bestSAH); splitSAH = bestSAH[dim]; pos = bestSplit[dim]; leafSAH = bounds().half_area() * blocks(size()); } void BVHObjectBinning::split(BVHReference* prims, BVHObjectBinning& left_o, BVHObjectBinning& right_o) const { size_t N = size(); BoundBox lgeom_bounds = BoundBox::empty; BoundBox rgeom_bounds = BoundBox::empty; BoundBox lcent_bounds = BoundBox::empty; BoundBox rcent_bounds = BoundBox::empty; ssize_t l = 0, r = N-1; while(l <= r) { prefetch_L2(&prims[start() + l + 8]); prefetch_L2(&prims[start() + r - 8]); const BVHReference& prim = prims[start() + l]; float3 center = prim.bounds().center2(); if(get_bin(center)[dim] < pos) { lgeom_bounds.grow(prim.bounds()); lcent_bounds.grow(center); l++; } else { rgeom_bounds.grow(prim.bounds()); rcent_bounds.grow(center); swap(prims[start()+l],prims[start()+r]); r--; } } /* finish */ if(l != 0 && N-1-r != 0) { right_o = BVHObjectBinning(BVHRange(rgeom_bounds, rcent_bounds, start() + l, N-1-r), prims); left_o = BVHObjectBinning(BVHRange(lgeom_bounds, lcent_bounds, start(), l), prims); return; } /* object medium split if we did not make progress, can happen when all * primitives have same centroid */ lgeom_bounds = BoundBox::empty; rgeom_bounds = BoundBox::empty; lcent_bounds = BoundBox::empty; rcent_bounds = BoundBox::empty; for(size_t i = 0; i < N/2; i++) { lgeom_bounds.grow(prims[start()+i].bounds()); lcent_bounds.grow(prims[start()+i].bounds().center2()); } for(size_t i = N/2; i < N; i++) { rgeom_bounds.grow(prims[start()+i].bounds()); rcent_bounds.grow(prims[start()+i].bounds().center2()); } right_o = BVHObjectBinning(BVHRange(rgeom_bounds, rcent_bounds, start() + N/2, N/2 + N%2), prims); left_o = BVHObjectBinning(BVHRange(lgeom_bounds, lcent_bounds, start(), N/2), prims); } CCL_NAMESPACE_END <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "JoinMenu.h" /* system headers */ #include <string> #include <vector> /* common implementation headers */ #include "FontManager.h" /* local implementation headers */ #include "StartupInfo.h" #include "MainMenu.h" #include "HUDDialogStack.h" #include "MenuDefaultKey.h" #include "ServerStartMenu.h" #include "ServerMenu.h" #include "Protocol.h" #include "HUDuiControl.h" #include "HUDuiLabel.h" #include "HUDuiTypeIn.h" #include "HUDuiList.h" #include "TimeKeeper.h" /* from playing.h */ StartupInfo* getStartupInfo(); void joinGame(); JoinMenu* JoinMenu::activeMenu = NULL; JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL) { // cache font face ID int fontFace = MainMenu::getFontFace(); // add controls std::vector<HUDuiControl*>& list = getControls(); StartupInfo* info = getStartupInfo(); HUDuiLabel* label = new HUDuiLabel; label->setFontFace(fontFace); label->setString("Join Game"); list.push_back(label); findServer = new HUDuiLabel; findServer->setFontFace(fontFace); findServer->setString("Find Server"); list.push_back(findServer); connectLabel = new HUDuiLabel; connectLabel->setFontFace(fontFace); connectLabel->setString("Connect"); list.push_back(connectLabel); callsign = new HUDuiTypeIn; callsign->setFontFace(fontFace); callsign->setLabel("Callsign:"); callsign->setMaxLength(CallSignLen - 1); callsign->setString(info->callsign); list.push_back(callsign); password = new HUDuiTypeIn; password->setObfuscation(true); password->setFontFace(fontFace); password->setLabel("Password:"); password->setMaxLength(CallSignLen - 1); password->setString(info->password); list.push_back(password); team = new HUDuiList; team->setFontFace(fontFace); team->setLabel("Team:"); team->setCallback(teamCallback, NULL); std::vector<std::string>& teams = team->getList(); // these do not need to be in enum order, but must match getTeam() & setTeam() teams.push_back(std::string(Team::getName(AutomaticTeam))); teams.push_back(std::string(Team::getName(RogueTeam))); teams.push_back(std::string(Team::getName(RedTeam))); teams.push_back(std::string(Team::getName(GreenTeam))); teams.push_back(std::string(Team::getName(BlueTeam))); teams.push_back(std::string(Team::getName(PurpleTeam))); teams.push_back(std::string(Team::getName(ObserverTeam))); team->update(); setTeam(info->team); list.push_back(team); server = new HUDuiTypeIn; server->setFontFace(fontFace); server->setLabel("Server:"); server->setMaxLength(64); server->setString(info->serverName); list.push_back(server); char buffer[10]; sprintf(buffer, "%d", info->serverPort); port = new HUDuiTypeIn; port->setFontFace(fontFace); port->setLabel("Port:"); port->setMaxLength(5); port->setString(buffer); list.push_back(port); email = new HUDuiTypeIn; email->setFontFace(fontFace); email->setLabel("Email:"); email->setMaxLength(EmailLen - 1); email->setString(info->email); list.push_back(email); startServer = new HUDuiLabel; startServer->setFontFace(fontFace); startServer->setString("Start Server"); list.push_back(startServer); status = new HUDuiLabel; status->setFontFace(fontFace); status->setString(""); list.push_back(status); failedMessage = new HUDuiLabel; failedMessage->setFontFace(fontFace); failedMessage->setString(""); list.push_back(failedMessage); initNavigation(list, 1, list.size() - 3); } JoinMenu::~JoinMenu() { delete serverStartMenu; delete serverMenu; } HUDuiDefaultKey* JoinMenu::getDefaultKey() { return MenuDefaultKey::getInstance(); } void JoinMenu::show() { activeMenu = this; StartupInfo* info = getStartupInfo(); // set fields callsign->setString(info->callsign); setTeam(info->team); server->setString(info->serverName); char buffer[10]; sprintf(buffer, "%d", info->serverPort); port->setString(buffer); // clear status setStatus(""); setFailedMessage(""); } void JoinMenu::dismiss() { loadInfo(); activeMenu = NULL; } void JoinMenu::loadInfo() { // load startup info with current settings StartupInfo* info = getStartupInfo(); strcpy(info->callsign, callsign->getString().c_str()); info->team = getTeam(); strcpy(info->serverName, server->getString().c_str()); info->serverPort = atoi(port->getString().c_str()); strcpy(info->email, email->getString().c_str()); } void JoinMenu::execute() { HUDuiControl* focus = HUDui::getFocus(); if (focus == startServer) { if (!serverStartMenu) serverStartMenu = new ServerStartMenu; HUDDialogStack::get()->push(serverStartMenu); } else if (focus == findServer) { if (!serverMenu) serverMenu = new ServerMenu; HUDDialogStack::get()->push(serverMenu); } else if (focus == connectLabel) { // load startup info loadInfo(); // make sure we've got what we need StartupInfo* info = getStartupInfo(); if (info->callsign[0] == '\0') { setStatus("You must enter a callsign."); return; } if (info->serverName[0] == '\0') { setStatus("You must enter a server."); return; } if (info->serverPort <= 0 || info->serverPort > 65535) { char buffer[60]; sprintf(buffer, "Port is invalid. Try %d.", ServerPort); setStatus(buffer); return; } // let user know we're trying setStatus("Trying..."); // schedule attempt to join game joinGame(); } } void JoinMenu::setFailedMessage(const char* msg) { failedMessage->setString(msg); FontManager &fm = FontManager::instance(); const float width = fm.getStrLength(MainMenu::getFontFace(), failedMessage->getFontSize(), failedMessage->getString()); failedMessage->setPosition(center - 0.5f * width, failedMessage->getY()); } TeamColor JoinMenu::getTeam() const { return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1); } void JoinMenu::setTeam(TeamColor teamcol) { team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1); } void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *) { status->setString(msg); FontManager &fm = FontManager::instance(); const float width = fm.getStrLength(status->getFontFace(), status->getFontSize(), status->getString()); status->setPosition(center - 0.5f * width, status->getY()); } void JoinMenu::teamCallback(HUDuiControl*, void*) { // do nothing (for now) } void JoinMenu::resize(int width, int height) { HUDDialog::resize(width, height); // use a big font for title, smaller font for the rest const float titleFontSize = (float)height / 15.0f; const float fontSize = (float)height / 36.0f; center = 0.5f * (float)width; FontManager &fm = FontManager::instance(); // reposition title std::vector<HUDuiControl*>& list = getControls(); HUDuiLabel* title = (HUDuiLabel*)list[0]; title->setFontSize(titleFontSize); const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString()); const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, ""); float x = 0.5f * ((float)width - titleWidth); float y = (float)height - titleHeight; title->setPosition(x, y); // reposition options x = 0.5f * ((float)width - 0.5f * titleWidth); y -= 0.6f * titleHeight; list[1]->setFontSize(fontSize); const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, ""); const int count = list.size(); for (int i = 1; i < count; i++) { list[i]->setFontSize(fontSize); list[i]->setPosition(x, y); y -= 1.0f * h; if (i <= 2 || i == 7) y -= 0.5f * h; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>store password in startup info<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "JoinMenu.h" /* system headers */ #include <string> #include <vector> /* common implementation headers */ #include "FontManager.h" /* local implementation headers */ #include "StartupInfo.h" #include "MainMenu.h" #include "HUDDialogStack.h" #include "MenuDefaultKey.h" #include "ServerStartMenu.h" #include "ServerMenu.h" #include "Protocol.h" #include "HUDuiControl.h" #include "HUDuiLabel.h" #include "HUDuiTypeIn.h" #include "HUDuiList.h" #include "TimeKeeper.h" /* from playing.h */ StartupInfo* getStartupInfo(); void joinGame(); JoinMenu* JoinMenu::activeMenu = NULL; JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL) { // cache font face ID int fontFace = MainMenu::getFontFace(); // add controls std::vector<HUDuiControl*>& list = getControls(); StartupInfo* info = getStartupInfo(); HUDuiLabel* label = new HUDuiLabel; label->setFontFace(fontFace); label->setString("Join Game"); list.push_back(label); findServer = new HUDuiLabel; findServer->setFontFace(fontFace); findServer->setString("Find Server"); list.push_back(findServer); connectLabel = new HUDuiLabel; connectLabel->setFontFace(fontFace); connectLabel->setString("Connect"); list.push_back(connectLabel); callsign = new HUDuiTypeIn; callsign->setFontFace(fontFace); callsign->setLabel("Callsign:"); callsign->setMaxLength(CallSignLen - 1); callsign->setString(info->callsign); list.push_back(callsign); password = new HUDuiTypeIn; password->setObfuscation(true); password->setFontFace(fontFace); password->setLabel("Password:"); password->setMaxLength(CallSignLen - 1); password->setString(info->password); list.push_back(password); team = new HUDuiList; team->setFontFace(fontFace); team->setLabel("Team:"); team->setCallback(teamCallback, NULL); std::vector<std::string>& teams = team->getList(); // these do not need to be in enum order, but must match getTeam() & setTeam() teams.push_back(std::string(Team::getName(AutomaticTeam))); teams.push_back(std::string(Team::getName(RogueTeam))); teams.push_back(std::string(Team::getName(RedTeam))); teams.push_back(std::string(Team::getName(GreenTeam))); teams.push_back(std::string(Team::getName(BlueTeam))); teams.push_back(std::string(Team::getName(PurpleTeam))); teams.push_back(std::string(Team::getName(ObserverTeam))); team->update(); setTeam(info->team); list.push_back(team); server = new HUDuiTypeIn; server->setFontFace(fontFace); server->setLabel("Server:"); server->setMaxLength(64); server->setString(info->serverName); list.push_back(server); char buffer[10]; sprintf(buffer, "%d", info->serverPort); port = new HUDuiTypeIn; port->setFontFace(fontFace); port->setLabel("Port:"); port->setMaxLength(5); port->setString(buffer); list.push_back(port); email = new HUDuiTypeIn; email->setFontFace(fontFace); email->setLabel("Email:"); email->setMaxLength(EmailLen - 1); email->setString(info->email); list.push_back(email); startServer = new HUDuiLabel; startServer->setFontFace(fontFace); startServer->setString("Start Server"); list.push_back(startServer); status = new HUDuiLabel; status->setFontFace(fontFace); status->setString(""); list.push_back(status); failedMessage = new HUDuiLabel; failedMessage->setFontFace(fontFace); failedMessage->setString(""); list.push_back(failedMessage); initNavigation(list, 1, list.size() - 3); } JoinMenu::~JoinMenu() { delete serverStartMenu; delete serverMenu; } HUDuiDefaultKey* JoinMenu::getDefaultKey() { return MenuDefaultKey::getInstance(); } void JoinMenu::show() { activeMenu = this; StartupInfo* info = getStartupInfo(); // set fields callsign->setString(info->callsign); password->setString(info->password); setTeam(info->team); server->setString(info->serverName); char buffer[10]; sprintf(buffer, "%d", info->serverPort); port->setString(buffer); // clear status setStatus(""); setFailedMessage(""); } void JoinMenu::dismiss() { loadInfo(); activeMenu = NULL; } void JoinMenu::loadInfo() { // load startup info with current settings StartupInfo* info = getStartupInfo(); strcpy(info->callsign, callsign->getString().c_str()); strcpy(info->password, password->getString().c_str()); info->team = getTeam(); strcpy(info->serverName, server->getString().c_str()); info->serverPort = atoi(port->getString().c_str()); strcpy(info->email, email->getString().c_str()); } void JoinMenu::execute() { HUDuiControl* focus = HUDui::getFocus(); if (focus == startServer) { if (!serverStartMenu) serverStartMenu = new ServerStartMenu; HUDDialogStack::get()->push(serverStartMenu); } else if (focus == findServer) { if (!serverMenu) serverMenu = new ServerMenu; HUDDialogStack::get()->push(serverMenu); } else if (focus == connectLabel) { // load startup info loadInfo(); // make sure we've got what we need StartupInfo* info = getStartupInfo(); if (info->callsign[0] == '\0') { setStatus("You must enter a callsign."); return; } if (info->serverName[0] == '\0') { setStatus("You must enter a server."); return; } if (info->serverPort <= 0 || info->serverPort > 65535) { char buffer[60]; sprintf(buffer, "Port is invalid. Try %d.", ServerPort); setStatus(buffer); return; } // let user know we're trying setStatus("Trying..."); // schedule attempt to join game joinGame(); } } void JoinMenu::setFailedMessage(const char* msg) { failedMessage->setString(msg); FontManager &fm = FontManager::instance(); const float width = fm.getStrLength(MainMenu::getFontFace(), failedMessage->getFontSize(), failedMessage->getString()); failedMessage->setPosition(center - 0.5f * width, failedMessage->getY()); } TeamColor JoinMenu::getTeam() const { return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1); } void JoinMenu::setTeam(TeamColor teamcol) { team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1); } void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *) { status->setString(msg); FontManager &fm = FontManager::instance(); const float width = fm.getStrLength(status->getFontFace(), status->getFontSize(), status->getString()); status->setPosition(center - 0.5f * width, status->getY()); } void JoinMenu::teamCallback(HUDuiControl*, void*) { // do nothing (for now) } void JoinMenu::resize(int width, int height) { HUDDialog::resize(width, height); // use a big font for title, smaller font for the rest const float titleFontSize = (float)height / 15.0f; const float fontSize = (float)height / 36.0f; center = 0.5f * (float)width; FontManager &fm = FontManager::instance(); // reposition title std::vector<HUDuiControl*>& list = getControls(); HUDuiLabel* title = (HUDuiLabel*)list[0]; title->setFontSize(titleFontSize); const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString()); const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, ""); float x = 0.5f * ((float)width - titleWidth); float y = (float)height - titleHeight; title->setPosition(x, y); // reposition options x = 0.5f * ((float)width - 0.5f * titleWidth); y -= 0.6f * titleHeight; list[1]->setFontSize(fontSize); const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, ""); const int count = list.size(); for (int i = 1; i < count; i++) { list[i]->setFontSize(fontSize); list[i]->setPosition(x, y); y -= 1.0f * h; if (i <= 2 || i == 7) y -= 0.5f * h; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>